Notification.java revision a13bfae217553bcdd545794121c045f5a6da28ba
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.content.Context; 21import android.content.Intent; 22import android.content.res.Resources; 23import android.graphics.Bitmap; 24import android.graphics.PorterDuff; 25import android.media.AudioManager; 26import android.net.Uri; 27import android.os.BadParcelableException; 28import android.os.Build; 29import android.os.Bundle; 30import android.os.Parcel; 31import android.os.Parcelable; 32import android.os.SystemClock; 33import android.os.UserHandle; 34import android.text.TextUtils; 35import android.util.Log; 36import android.util.TypedValue; 37import android.view.View; 38import android.widget.ProgressBar; 39import android.widget.RemoteViews; 40 41import com.android.internal.R; 42import com.android.internal.util.NotificationColorUtil; 43 44import java.lang.annotation.Retention; 45import java.lang.annotation.RetentionPolicy; 46import java.text.NumberFormat; 47import java.util.ArrayList; 48 49/** 50 * A class that represents how a persistent notification is to be presented to 51 * the user using the {@link android.app.NotificationManager}. 52 * 53 * <p>The {@link Notification.Builder Notification.Builder} has been added to make it 54 * easier to construct Notifications.</p> 55 * 56 * <div class="special reference"> 57 * <h3>Developer Guides</h3> 58 * <p>For a guide to creating notifications, read the 59 * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a> 60 * developer guide.</p> 61 * </div> 62 */ 63public class Notification implements Parcelable 64{ 65 private static final String TAG = "Notification"; 66 67 /** 68 * Use all default values (where applicable). 69 */ 70 public static final int DEFAULT_ALL = ~0; 71 72 /** 73 * Use the default notification sound. This will ignore any given 74 * {@link #sound}. 75 * 76 77 * @see #defaults 78 */ 79 80 public static final int DEFAULT_SOUND = 1; 81 82 /** 83 * Use the default notification vibrate. This will ignore any given 84 * {@link #vibrate}. Using phone vibration requires the 85 * {@link android.Manifest.permission#VIBRATE VIBRATE} permission. 86 * 87 * @see #defaults 88 */ 89 90 public static final int DEFAULT_VIBRATE = 2; 91 92 /** 93 * Use the default notification lights. This will ignore the 94 * {@link #FLAG_SHOW_LIGHTS} bit, and {@link #ledARGB}, {@link #ledOffMS}, or 95 * {@link #ledOnMS}. 96 * 97 * @see #defaults 98 */ 99 100 public static final int DEFAULT_LIGHTS = 4; 101 102 /** 103 * A timestamp related to this notification, in milliseconds since the epoch. 104 * 105 * Default value: {@link System#currentTimeMillis() Now}. 106 * 107 * Choose a timestamp that will be most relevant to the user. For most finite events, this 108 * corresponds to the time the event happened (or will happen, in the case of events that have 109 * yet to occur but about which the user is being informed). Indefinite events should be 110 * timestamped according to when the activity began. 111 * 112 * Some examples: 113 * 114 * <ul> 115 * <li>Notification of a new chat message should be stamped when the message was received.</li> 116 * <li>Notification of an ongoing file download (with a progress bar, for example) should be stamped when the download started.</li> 117 * <li>Notification of a completed file download should be stamped when the download finished.</li> 118 * <li>Notification of an upcoming meeting should be stamped with the time the meeting will begin (that is, in the future).</li> 119 * <li>Notification of an ongoing stopwatch (increasing timer) should be stamped with the watch's start time. 120 * <li>Notification of an ongoing countdown timer should be stamped with the timer's end time. 121 * </ul> 122 * 123 */ 124 public long when; 125 126 /** 127 * The resource id of a drawable to use as the icon in the status bar. 128 * This is required; notifications with an invalid icon resource will not be shown. 129 */ 130 public int icon; 131 132 /** 133 * If the icon in the status bar is to have more than one level, you can set this. Otherwise, 134 * leave it at its default value of 0. 135 * 136 * @see android.widget.ImageView#setImageLevel 137 * @see android.graphics.drawable.Drawable#setLevel 138 */ 139 public int iconLevel; 140 141 /** 142 * The number of events that this notification represents. For example, in a new mail 143 * notification, this could be the number of unread messages. 144 * 145 * The system may or may not use this field to modify the appearance of the notification. For 146 * example, before {@link android.os.Build.VERSION_CODES#HONEYCOMB}, this number was 147 * superimposed over the icon in the status bar. Starting with 148 * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, the template used by 149 * {@link Notification.Builder} has displayed the number in the expanded notification view. 150 * 151 * If the number is 0 or negative, it is never shown. 152 */ 153 public int number; 154 155 /** 156 * The intent to execute when the expanded status entry is clicked. If 157 * this is an activity, it must include the 158 * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires 159 * that you take care of task management as described in the 160 * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back 161 * Stack</a> document. In particular, make sure to read the notification section 162 * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html#HandlingNotifications">Handling 163 * Notifications</a> for the correct ways to launch an application from a 164 * notification. 165 */ 166 public PendingIntent contentIntent; 167 168 /** 169 * The intent to execute when the notification is explicitly dismissed by the user, either with 170 * the "Clear All" button or by swiping it away individually. 171 * 172 * This probably shouldn't be launching an activity since several of those will be sent 173 * at the same time. 174 */ 175 public PendingIntent deleteIntent; 176 177 /** 178 * An intent to launch instead of posting the notification to the status bar. 179 * 180 * @see Notification.Builder#setFullScreenIntent 181 */ 182 public PendingIntent fullScreenIntent; 183 184 /** 185 * Text to scroll across the screen when this item is added to 186 * the status bar on large and smaller devices. 187 * 188 * @see #tickerView 189 */ 190 public CharSequence tickerText; 191 192 /** 193 * The view to show as the ticker in the status bar when the notification 194 * is posted. 195 */ 196 public RemoteViews tickerView; 197 198 /** 199 * The view that will represent this notification in the expanded status bar. 200 */ 201 public RemoteViews contentView; 202 203 /** 204 * A large-format version of {@link #contentView}, giving the Notification an 205 * opportunity to show more detail. The system UI may choose to show this 206 * instead of the normal content view at its discretion. 207 */ 208 public RemoteViews bigContentView; 209 210 211 /** 212 * @hide 213 * A medium-format version of {@link #contentView}, giving the Notification an 214 * opportunity to add action buttons to contentView. The system UI may 215 * choose to show this as a popup notification at its discretion. 216 */ 217 public RemoteViews headsUpContentView; 218 219 /** 220 * The bitmap that may escape the bounds of the panel and bar. 221 */ 222 public Bitmap largeIcon; 223 224 /** 225 * The sound to play. 226 * 227 * <p> 228 * To play the default notification sound, see {@link #defaults}. 229 * </p> 230 */ 231 public Uri sound; 232 233 /** 234 * Use this constant as the value for audioStreamType to request that 235 * the default stream type for notifications be used. Currently the 236 * default stream type is {@link AudioManager#STREAM_NOTIFICATION}. 237 */ 238 public static final int STREAM_DEFAULT = -1; 239 240 /** 241 * The audio stream type to use when playing the sound. 242 * Should be one of the STREAM_ constants from 243 * {@link android.media.AudioManager}. 244 */ 245 public int audioStreamType = STREAM_DEFAULT; 246 247 /** 248 * The pattern with which to vibrate. 249 * 250 * <p> 251 * To vibrate the default pattern, see {@link #defaults}. 252 * </p> 253 * 254 * @see android.os.Vibrator#vibrate(long[],int) 255 */ 256 public long[] vibrate; 257 258 /** 259 * The color of the led. The hardware will do its best approximation. 260 * 261 * @see #FLAG_SHOW_LIGHTS 262 * @see #flags 263 */ 264 public int ledARGB; 265 266 /** 267 * The number of milliseconds for the LED to be on while it's flashing. 268 * The hardware will do its best approximation. 269 * 270 * @see #FLAG_SHOW_LIGHTS 271 * @see #flags 272 */ 273 public int ledOnMS; 274 275 /** 276 * The number of milliseconds for the LED to be off while it's flashing. 277 * The hardware will do its best approximation. 278 * 279 * @see #FLAG_SHOW_LIGHTS 280 * @see #flags 281 */ 282 public int ledOffMS; 283 284 /** 285 * Specifies which values should be taken from the defaults. 286 * <p> 287 * To set, OR the desired from {@link #DEFAULT_SOUND}, 288 * {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}. For all default 289 * values, use {@link #DEFAULT_ALL}. 290 * </p> 291 */ 292 public int defaults; 293 294 /** 295 * Bit to be bitwise-ored into the {@link #flags} field that should be 296 * set if you want the LED on for this notification. 297 * <ul> 298 * <li>To turn the LED off, pass 0 in the alpha channel for colorARGB 299 * or 0 for both ledOnMS and ledOffMS.</li> 300 * <li>To turn the LED on, pass 1 for ledOnMS and 0 for ledOffMS.</li> 301 * <li>To flash the LED, pass the number of milliseconds that it should 302 * be on and off to ledOnMS and ledOffMS.</li> 303 * </ul> 304 * <p> 305 * Since hardware varies, you are not guaranteed that any of the values 306 * you pass are honored exactly. Use the system defaults (TODO) if possible 307 * because they will be set to values that work on any given hardware. 308 * <p> 309 * The alpha channel must be set for forward compatibility. 310 * 311 */ 312 public static final int FLAG_SHOW_LIGHTS = 0x00000001; 313 314 /** 315 * Bit to be bitwise-ored into the {@link #flags} field that should be 316 * set if this notification is in reference to something that is ongoing, 317 * like a phone call. It should not be set if this notification is in 318 * reference to something that happened at a particular point in time, 319 * like a missed phone call. 320 */ 321 public static final int FLAG_ONGOING_EVENT = 0x00000002; 322 323 /** 324 * Bit to be bitwise-ored into the {@link #flags} field that if set, 325 * the audio will be repeated until the notification is 326 * cancelled or the notification window is opened. 327 */ 328 public static final int FLAG_INSISTENT = 0x00000004; 329 330 /** 331 * Bit to be bitwise-ored into the {@link #flags} field that should be 332 * set if you would only like the sound, vibrate and ticker to be played 333 * if the notification was not already showing. 334 */ 335 public static final int FLAG_ONLY_ALERT_ONCE = 0x00000008; 336 337 /** 338 * Bit to be bitwise-ored into the {@link #flags} field that should be 339 * set if the notification should be canceled when it is clicked by the 340 * user. 341 342 */ 343 public static final int FLAG_AUTO_CANCEL = 0x00000010; 344 345 /** 346 * Bit to be bitwise-ored into the {@link #flags} field that should be 347 * set if the notification should not be canceled when the user clicks 348 * the Clear all button. 349 */ 350 public static final int FLAG_NO_CLEAR = 0x00000020; 351 352 /** 353 * Bit to be bitwise-ored into the {@link #flags} field that should be 354 * set if this notification represents a currently running service. This 355 * will normally be set for you by {@link Service#startForeground}. 356 */ 357 public static final int FLAG_FOREGROUND_SERVICE = 0x00000040; 358 359 /** 360 * Obsolete flag indicating high-priority notifications; use the priority field instead. 361 * 362 * @deprecated Use {@link #priority} with a positive value. 363 */ 364 public static final int FLAG_HIGH_PRIORITY = 0x00000080; 365 366 /** 367 * Bit to be bitswise-ored into the {@link #flags} field that should be 368 * set if this notification is relevant to the current device only 369 * and it is not recommended that it bridge to other devices. 370 */ 371 public static final int FLAG_LOCAL_ONLY = 0x00000100; 372 373 public int flags; 374 375 /** @hide */ 376 @IntDef({PRIORITY_DEFAULT,PRIORITY_LOW,PRIORITY_MIN,PRIORITY_HIGH,PRIORITY_MAX}) 377 @Retention(RetentionPolicy.SOURCE) 378 public @interface Priority {} 379 380 /** 381 * Default notification {@link #priority}. If your application does not prioritize its own 382 * notifications, use this value for all notifications. 383 */ 384 public static final int PRIORITY_DEFAULT = 0; 385 386 /** 387 * Lower {@link #priority}, for items that are less important. The UI may choose to show these 388 * items smaller, or at a different position in the list, compared with your app's 389 * {@link #PRIORITY_DEFAULT} items. 390 */ 391 public static final int PRIORITY_LOW = -1; 392 393 /** 394 * Lowest {@link #priority}; these items might not be shown to the user except under special 395 * circumstances, such as detailed notification logs. 396 */ 397 public static final int PRIORITY_MIN = -2; 398 399 /** 400 * Higher {@link #priority}, for more important notifications or alerts. The UI may choose to 401 * show these items larger, or at a different position in notification lists, compared with 402 * your app's {@link #PRIORITY_DEFAULT} items. 403 */ 404 public static final int PRIORITY_HIGH = 1; 405 406 /** 407 * Highest {@link #priority}, for your application's most important items that require the 408 * user's prompt attention or input. 409 */ 410 public static final int PRIORITY_MAX = 2; 411 412 /** 413 * Relative priority for this notification. 414 * 415 * Priority is an indication of how much of the user's valuable attention should be consumed by 416 * this notification. Low-priority notifications may be hidden from the user in certain 417 * situations, while the user might be interrupted for a higher-priority notification. The 418 * system will make a determination about how to interpret this priority when presenting 419 * the notification. 420 */ 421 @Priority 422 public int priority; 423 424 /** 425 * Accent color (an ARGB integer like the constants in {@link android.graphics.Color}) 426 * to be applied by the standard Style templates when presenting this notification. 427 * 428 * The current template design constructs a colorful header image by overlaying the 429 * {@link #icon} image (stenciled in white) atop a field of this color. Alpha components are 430 * ignored. 431 */ 432 public int color = COLOR_DEFAULT; 433 434 /** 435 * Special value of {@link #color} telling the system not to decorate this notification with 436 * any special color but instead use default colors when presenting this notification. 437 */ 438 public static final int COLOR_DEFAULT = 0; // AKA Color.TRANSPARENT 439 440 /** 441 * Sphere of visibility of this notification, which affects how and when the SystemUI reveals 442 * the notification's presence and contents in untrusted situations (namely, on the secure 443 * lockscreen). 444 * 445 * The default level, {@link #VISIBILITY_PRIVATE}, behaves exactly as notifications have always 446 * done on Android: The notification's {@link #icon} and {@link #tickerText} (if available) are 447 * shown in all situations, but the contents are only available if the device is unlocked for 448 * the appropriate user. 449 * 450 * A more permissive policy can be expressed by {@link #VISIBILITY_PUBLIC}; such a notification 451 * can be read even in an "insecure" context (that is, above a secure lockscreen). 452 * To modify the public version of this notification—for example, to redact some portions—see 453 * {@link Builder#setPublicVersion(Notification)}. 454 * 455 * Finally, a notification can be made {@link #VISIBILITY_SECRET}, which will suppress its icon 456 * and ticker until the user has bypassed the lockscreen. 457 */ 458 public int visibility; 459 460 public static final int VISIBILITY_PUBLIC = 1; 461 public static final int VISIBILITY_PRIVATE = 0; 462 public static final int VISIBILITY_SECRET = -1; 463 464 /** 465 * Notification category: incoming call (voice or video) or similar synchronous communication request. 466 */ 467 public static final String CATEGORY_CALL = "call"; 468 469 /** 470 * Notification category: incoming direct message (SMS, instant message, etc.). 471 */ 472 public static final String CATEGORY_MESSAGE = "msg"; 473 474 /** 475 * Notification category: asynchronous bulk message (email). 476 */ 477 public static final String CATEGORY_EMAIL = "email"; 478 479 /** 480 * Notification category: calendar event. 481 */ 482 public static final String CATEGORY_EVENT = "event"; 483 484 /** 485 * Notification category: promotion or advertisement. 486 */ 487 public static final String CATEGORY_PROMO = "promo"; 488 489 /** 490 * Notification category: alarm or timer. 491 */ 492 public static final String CATEGORY_ALARM = "alarm"; 493 494 /** 495 * Notification category: progress of a long-running background operation. 496 */ 497 public static final String CATEGORY_PROGRESS = "progress"; 498 499 /** 500 * Notification category: social network or sharing update. 501 */ 502 public static final String CATEGORY_SOCIAL = "social"; 503 504 /** 505 * Notification category: error in background operation or authentication status. 506 */ 507 public static final String CATEGORY_ERROR = "err"; 508 509 /** 510 * Notification category: media transport control for playback. 511 */ 512 public static final String CATEGORY_TRANSPORT = "transport"; 513 514 /** 515 * Notification category: system or device status update. Reserved for system use. 516 */ 517 public static final String CATEGORY_SYSTEM = "sys"; 518 519 /** 520 * Notification category: indication of running background service. 521 */ 522 public static final String CATEGORY_SERVICE = "service"; 523 524 /** 525 * Notification category: a specific, timely recommendation for a single thing. 526 * For example, a news app might want to recommend a news story it believes the user will 527 * want to read next. 528 */ 529 public static final String CATEGORY_RECOMMENDATION = "recommendation"; 530 531 /** 532 * Notification category: ongoing information about device or contextual status. 533 */ 534 public static final String CATEGORY_STATUS = "status"; 535 536 /** 537 * One of the predefined notification categories (see the <code>CATEGORY_*</code> constants) 538 * that best describes this Notification. May be used by the system for ranking and filtering. 539 */ 540 public String category; 541 542 /** 543 * Additional semantic data to be carried around with this Notification. 544 * <p> 545 * The extras keys defined here are intended to capture the original inputs to {@link Builder} 546 * APIs, and are intended to be used by 547 * {@link android.service.notification.NotificationListenerService} implementations to extract 548 * detailed information from notification objects. 549 */ 550 public Bundle extras = new Bundle(); 551 552 /** 553 * {@link #extras} key: this is the title of the notification, 554 * as supplied to {@link Builder#setContentTitle(CharSequence)}. 555 */ 556 public static final String EXTRA_TITLE = "android.title"; 557 558 /** 559 * {@link #extras} key: this is the title of the notification when shown in expanded form, 560 * e.g. as supplied to {@link BigTextStyle#setBigContentTitle(CharSequence)}. 561 */ 562 public static final String EXTRA_TITLE_BIG = EXTRA_TITLE + ".big"; 563 564 /** 565 * {@link #extras} key: this is the main text payload, as supplied to 566 * {@link Builder#setContentText(CharSequence)}. 567 */ 568 public static final String EXTRA_TEXT = "android.text"; 569 570 /** 571 * {@link #extras} key: this is a third line of text, as supplied to 572 * {@link Builder#setSubText(CharSequence)}. 573 */ 574 public static final String EXTRA_SUB_TEXT = "android.subText"; 575 576 /** 577 * {@link #extras} key: this is a small piece of additional text as supplied to 578 * {@link Builder#setContentInfo(CharSequence)}. 579 */ 580 public static final String EXTRA_INFO_TEXT = "android.infoText"; 581 582 /** 583 * {@link #extras} key: this is a line of summary information intended to be shown 584 * alongside expanded notifications, as supplied to (e.g.) 585 * {@link BigTextStyle#setSummaryText(CharSequence)}. 586 */ 587 public static final String EXTRA_SUMMARY_TEXT = "android.summaryText"; 588 589 /** 590 * {@link #extras} key: this is the resource ID of the notification's main small icon, as 591 * supplied to {@link Builder#setSmallIcon(int)}. 592 */ 593 public static final String EXTRA_SMALL_ICON = "android.icon"; 594 595 /** 596 * {@link #extras} key: this is a bitmap to be used instead of the small icon when showing the 597 * notification payload, as 598 * supplied to {@link Builder#setLargeIcon(android.graphics.Bitmap)}. 599 */ 600 public static final String EXTRA_LARGE_ICON = "android.largeIcon"; 601 602 /** 603 * {@link #extras} key: this is a bitmap to be used instead of the one from 604 * {@link Builder#setLargeIcon(android.graphics.Bitmap)} when the notification is 605 * shown in its expanded form, as supplied to 606 * {@link BigPictureStyle#bigLargeIcon(android.graphics.Bitmap)}. 607 */ 608 public static final String EXTRA_LARGE_ICON_BIG = EXTRA_LARGE_ICON + ".big"; 609 610 /** 611 * {@link #extras} key: this is the progress value supplied to 612 * {@link Builder#setProgress(int, int, boolean)}. 613 */ 614 public static final String EXTRA_PROGRESS = "android.progress"; 615 616 /** 617 * {@link #extras} key: this is the maximum value supplied to 618 * {@link Builder#setProgress(int, int, boolean)}. 619 */ 620 public static final String EXTRA_PROGRESS_MAX = "android.progressMax"; 621 622 /** 623 * {@link #extras} key: whether the progress bar is indeterminate, supplied to 624 * {@link Builder#setProgress(int, int, boolean)}. 625 */ 626 public static final String EXTRA_PROGRESS_INDETERMINATE = "android.progressIndeterminate"; 627 628 /** 629 * {@link #extras} key: whether {@link #when} should be shown as a count-up timer (specifically 630 * a {@link android.widget.Chronometer}) instead of a timestamp, as supplied to 631 * {@link Builder#setUsesChronometer(boolean)}. 632 */ 633 public static final String EXTRA_SHOW_CHRONOMETER = "android.showChronometer"; 634 635 /** 636 * {@link #extras} key: whether {@link #when} should be shown, 637 * as supplied to {@link Builder#setShowWhen(boolean)}. 638 */ 639 public static final String EXTRA_SHOW_WHEN = "android.showWhen"; 640 641 /** 642 * {@link #extras} key: this is a bitmap to be shown in {@link BigPictureStyle} expanded 643 * notifications, supplied to {@link BigPictureStyle#bigPicture(android.graphics.Bitmap)}. 644 */ 645 public static final String EXTRA_PICTURE = "android.picture"; 646 647 /** 648 * {@link #extras} key: An array of CharSequences to show in {@link InboxStyle} expanded 649 * notifications, each of which was supplied to {@link InboxStyle#addLine(CharSequence)}. 650 */ 651 public static final String EXTRA_TEXT_LINES = "android.textLines"; 652 public static final String EXTRA_TEMPLATE = "android.template"; 653 654 /** 655 * {@link #extras} key: An array of people that this notification relates to, specified 656 * by contacts provider contact URI. 657 */ 658 public static final String EXTRA_PEOPLE = "android.people"; 659 660 /** 661 * @hide 662 * Extra added by NotificationManagerService to indicate whether 663 * the Notifications's score has been modified. 664 */ 665 public static final String EXTRA_SCORE_MODIFIED = "android.scoreModified"; 666 667 /** 668 * Not used. 669 * @hide 670 */ 671 public static final String EXTRA_AS_HEADS_UP = "headsup"; 672 673 /** 674 * Allow certain system-generated notifications to appear before the device is provisioned. 675 * Only available to notifications coming from the android package. 676 * @hide 677 */ 678 public static final String EXTRA_ALLOW_DURING_SETUP = "android.allowDuringSetup"; 679 680 /** 681 * Value for {@link #EXTRA_AS_HEADS_UP}. 682 * @hide 683 */ 684 public static final int HEADS_UP_NEVER = 0; 685 686 /** 687 * Default value for {@link #EXTRA_AS_HEADS_UP}. 688 * @hide 689 */ 690 public static final int HEADS_UP_ALLOWED = 1; 691 692 /** 693 * Value for {@link #EXTRA_AS_HEADS_UP}. 694 * @hide 695 */ 696 public static final int HEADS_UP_REQUESTED = 2; 697 698 /** 699 * Structure to encapsulate a named action that can be shown as part of this notification. 700 * It must include an icon, a label, and a {@link PendingIntent} to be fired when the action is 701 * selected by the user. 702 * <p> 703 * Apps should use {@link Notification.Builder#addAction(int, CharSequence, PendingIntent)} 704 * or {@link Notification.Builder#addAction(Notification.Action)} 705 * to attach actions. 706 */ 707 public static class Action implements Parcelable { 708 private final Bundle mExtras; 709 710 /** 711 * Small icon representing the action. 712 */ 713 public int icon; 714 /** 715 * Title of the action. 716 */ 717 public CharSequence title; 718 /** 719 * Intent to send when the user invokes this action. May be null, in which case the action 720 * may be rendered in a disabled presentation by the system UI. 721 */ 722 public PendingIntent actionIntent; 723 724 private Action(Parcel in) { 725 icon = in.readInt(); 726 title = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); 727 if (in.readInt() == 1) { 728 actionIntent = PendingIntent.CREATOR.createFromParcel(in); 729 } 730 mExtras = in.readBundle(); 731 } 732 /** 733 * Use {@link Notification.Builder#addAction(int, CharSequence, PendingIntent)}. 734 */ 735 public Action(int icon, CharSequence title, PendingIntent intent) { 736 this(icon, title, intent, new Bundle()); 737 } 738 739 private Action(int icon, CharSequence title, PendingIntent intent, Bundle extras) { 740 this.icon = icon; 741 this.title = title; 742 this.actionIntent = intent; 743 this.mExtras = extras != null ? extras : new Bundle(); 744 } 745 746 /** 747 * Get additional metadata carried around with this Action. 748 */ 749 public Bundle getExtras() { 750 return mExtras; 751 } 752 753 /** 754 * Builder class for {@link Action} objects. 755 */ 756 public static class Builder { 757 private final int mIcon; 758 private final CharSequence mTitle; 759 private final PendingIntent mIntent; 760 private final Bundle mExtras; 761 762 /** 763 * Construct a new builder for {@link Action} object. 764 * @param icon icon to show for this action 765 * @param title the title of the action 766 * @param intent the {@link PendingIntent} to fire when users trigger this action 767 */ 768 public Builder(int icon, CharSequence title, PendingIntent intent) { 769 this(icon, title, intent, new Bundle()); 770 } 771 772 /** 773 * Construct a new builder for {@link Action} object using the fields from an 774 * {@link Action}. 775 * @param action the action to read fields from. 776 */ 777 public Builder(Action action) { 778 this(action.icon, action.title, action.actionIntent, new Bundle(action.mExtras)); 779 } 780 781 private Builder(int icon, CharSequence title, PendingIntent intent, Bundle extras) { 782 mIcon = icon; 783 mTitle = title; 784 mIntent = intent; 785 mExtras = extras; 786 } 787 788 /** 789 * Merge additional metadata into this builder. 790 * 791 * <p>Values within the Bundle will replace existing extras values in this Builder. 792 * 793 * @see Notification.Action#extras 794 */ 795 public Builder addExtras(Bundle extras) { 796 if (extras != null) { 797 mExtras.putAll(extras); 798 } 799 return this; 800 } 801 802 /** 803 * Get the metadata Bundle used by this Builder. 804 * 805 * <p>The returned Bundle is shared with this Builder. 806 */ 807 public Bundle getExtras() { 808 return mExtras; 809 } 810 811 /** 812 * Combine all of the options that have been set and return a new {@link Action} 813 * object. 814 * @return the built action 815 */ 816 public Action build() { 817 return new Action(mIcon, mTitle, mIntent, mExtras); 818 } 819 } 820 821 @Override 822 public Action clone() { 823 return new Action( 824 this.icon, 825 this.title, 826 this.actionIntent, // safe to alias 827 new Bundle(this.mExtras)); 828 } 829 @Override 830 public int describeContents() { 831 return 0; 832 } 833 @Override 834 public void writeToParcel(Parcel out, int flags) { 835 out.writeInt(icon); 836 TextUtils.writeToParcel(title, out, flags); 837 if (actionIntent != null) { 838 out.writeInt(1); 839 actionIntent.writeToParcel(out, flags); 840 } else { 841 out.writeInt(0); 842 } 843 out.writeBundle(mExtras); 844 } 845 public static final Parcelable.Creator<Action> CREATOR = 846 new Parcelable.Creator<Action>() { 847 public Action createFromParcel(Parcel in) { 848 return new Action(in); 849 } 850 public Action[] newArray(int size) { 851 return new Action[size]; 852 } 853 }; 854 } 855 856 /** 857 * Array of all {@link Action} structures attached to this notification by 858 * {@link Builder#addAction(int, CharSequence, PendingIntent)}. Mostly useful for instances of 859 * {@link android.service.notification.NotificationListenerService} that provide an alternative 860 * interface for invoking actions. 861 */ 862 public Action[] actions; 863 864 /** 865 * Replacement version of this notification whose content will be shown 866 * in an insecure context such as atop a secure keyguard. See {@link #visibility} 867 * and {@link #VISIBILITY_PUBLIC}. 868 */ 869 public Notification publicVersion; 870 871 /** 872 * Constructs a Notification object with default values. 873 * You might want to consider using {@link Builder} instead. 874 */ 875 public Notification() 876 { 877 this.when = System.currentTimeMillis(); 878 this.priority = PRIORITY_DEFAULT; 879 } 880 881 /** 882 * @hide 883 */ 884 public Notification(Context context, int icon, CharSequence tickerText, long when, 885 CharSequence contentTitle, CharSequence contentText, Intent contentIntent) 886 { 887 this.when = when; 888 this.icon = icon; 889 this.tickerText = tickerText; 890 setLatestEventInfo(context, contentTitle, contentText, 891 PendingIntent.getActivity(context, 0, contentIntent, 0)); 892 } 893 894 /** 895 * Constructs a Notification object with the information needed to 896 * have a status bar icon without the standard expanded view. 897 * 898 * @param icon The resource id of the icon to put in the status bar. 899 * @param tickerText The text that flows by in the status bar when the notification first 900 * activates. 901 * @param when The time to show in the time field. In the System.currentTimeMillis 902 * timebase. 903 * 904 * @deprecated Use {@link Builder} instead. 905 */ 906 @Deprecated 907 public Notification(int icon, CharSequence tickerText, long when) 908 { 909 this.icon = icon; 910 this.tickerText = tickerText; 911 this.when = when; 912 } 913 914 /** 915 * Unflatten the notification from a parcel. 916 */ 917 public Notification(Parcel parcel) 918 { 919 int version = parcel.readInt(); 920 921 when = parcel.readLong(); 922 icon = parcel.readInt(); 923 number = parcel.readInt(); 924 if (parcel.readInt() != 0) { 925 contentIntent = PendingIntent.CREATOR.createFromParcel(parcel); 926 } 927 if (parcel.readInt() != 0) { 928 deleteIntent = PendingIntent.CREATOR.createFromParcel(parcel); 929 } 930 if (parcel.readInt() != 0) { 931 tickerText = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(parcel); 932 } 933 if (parcel.readInt() != 0) { 934 tickerView = RemoteViews.CREATOR.createFromParcel(parcel); 935 } 936 if (parcel.readInt() != 0) { 937 contentView = RemoteViews.CREATOR.createFromParcel(parcel); 938 } 939 if (parcel.readInt() != 0) { 940 largeIcon = Bitmap.CREATOR.createFromParcel(parcel); 941 } 942 defaults = parcel.readInt(); 943 flags = parcel.readInt(); 944 if (parcel.readInt() != 0) { 945 sound = Uri.CREATOR.createFromParcel(parcel); 946 } 947 948 audioStreamType = parcel.readInt(); 949 vibrate = parcel.createLongArray(); 950 ledARGB = parcel.readInt(); 951 ledOnMS = parcel.readInt(); 952 ledOffMS = parcel.readInt(); 953 iconLevel = parcel.readInt(); 954 955 if (parcel.readInt() != 0) { 956 fullScreenIntent = PendingIntent.CREATOR.createFromParcel(parcel); 957 } 958 959 priority = parcel.readInt(); 960 961 category = parcel.readString(); 962 963 extras = parcel.readBundle(); // may be null 964 965 actions = parcel.createTypedArray(Action.CREATOR); // may be null 966 967 if (parcel.readInt() != 0) { 968 bigContentView = RemoteViews.CREATOR.createFromParcel(parcel); 969 } 970 971 if (parcel.readInt() != 0) { 972 headsUpContentView = RemoteViews.CREATOR.createFromParcel(parcel); 973 } 974 975 visibility = parcel.readInt(); 976 977 if (parcel.readInt() != 0) { 978 publicVersion = Notification.CREATOR.createFromParcel(parcel); 979 } 980 981 color = parcel.readInt(); 982 } 983 984 @Override 985 public Notification clone() { 986 Notification that = new Notification(); 987 cloneInto(that, true); 988 return that; 989 } 990 991 /** 992 * Copy all (or if heavy is false, all except Bitmaps and RemoteViews) members 993 * of this into that. 994 * @hide 995 */ 996 public void cloneInto(Notification that, boolean heavy) { 997 that.when = this.when; 998 that.icon = this.icon; 999 that.number = this.number; 1000 1001 // PendingIntents are global, so there's no reason (or way) to clone them. 1002 that.contentIntent = this.contentIntent; 1003 that.deleteIntent = this.deleteIntent; 1004 that.fullScreenIntent = this.fullScreenIntent; 1005 1006 if (this.tickerText != null) { 1007 that.tickerText = this.tickerText.toString(); 1008 } 1009 if (heavy && this.tickerView != null) { 1010 that.tickerView = this.tickerView.clone(); 1011 } 1012 if (heavy && this.contentView != null) { 1013 that.contentView = this.contentView.clone(); 1014 } 1015 if (heavy && this.largeIcon != null) { 1016 that.largeIcon = Bitmap.createBitmap(this.largeIcon); 1017 } 1018 that.iconLevel = this.iconLevel; 1019 that.sound = this.sound; // android.net.Uri is immutable 1020 that.audioStreamType = this.audioStreamType; 1021 1022 final long[] vibrate = this.vibrate; 1023 if (vibrate != null) { 1024 final int N = vibrate.length; 1025 final long[] vib = that.vibrate = new long[N]; 1026 System.arraycopy(vibrate, 0, vib, 0, N); 1027 } 1028 1029 that.ledARGB = this.ledARGB; 1030 that.ledOnMS = this.ledOnMS; 1031 that.ledOffMS = this.ledOffMS; 1032 that.defaults = this.defaults; 1033 1034 that.flags = this.flags; 1035 1036 that.priority = this.priority; 1037 1038 that.category = this.category; 1039 1040 if (this.extras != null) { 1041 try { 1042 that.extras = new Bundle(this.extras); 1043 // will unparcel 1044 that.extras.size(); 1045 } catch (BadParcelableException e) { 1046 Log.e(TAG, "could not unparcel extras from notification: " + this, e); 1047 that.extras = null; 1048 } 1049 } 1050 1051 if (this.actions != null) { 1052 that.actions = new Action[this.actions.length]; 1053 for(int i=0; i<this.actions.length; i++) { 1054 that.actions[i] = this.actions[i].clone(); 1055 } 1056 } 1057 1058 if (heavy && this.bigContentView != null) { 1059 that.bigContentView = this.bigContentView.clone(); 1060 } 1061 1062 if (heavy && this.headsUpContentView != null) { 1063 that.headsUpContentView = this.headsUpContentView.clone(); 1064 } 1065 1066 that.visibility = this.visibility; 1067 1068 if (this.publicVersion != null) { 1069 that.publicVersion = new Notification(); 1070 this.publicVersion.cloneInto(that.publicVersion, heavy); 1071 } 1072 1073 that.color = this.color; 1074 1075 if (!heavy) { 1076 that.lightenPayload(); // will clean out extras 1077 } 1078 } 1079 1080 /** 1081 * Removes heavyweight parts of the Notification object for archival or for sending to 1082 * listeners when the full contents are not necessary. 1083 * @hide 1084 */ 1085 public final void lightenPayload() { 1086 tickerView = null; 1087 contentView = null; 1088 bigContentView = null; 1089 headsUpContentView = null; 1090 largeIcon = null; 1091 if (extras != null) { 1092 extras.remove(Notification.EXTRA_LARGE_ICON); 1093 extras.remove(Notification.EXTRA_LARGE_ICON_BIG); 1094 extras.remove(Notification.EXTRA_PICTURE); 1095 } 1096 } 1097 1098 /** 1099 * Make sure this CharSequence is safe to put into a bundle, which basically 1100 * means it had better not be some custom Parcelable implementation. 1101 * @hide 1102 */ 1103 public static CharSequence safeCharSequence(CharSequence cs) { 1104 if (cs instanceof Parcelable) { 1105 Log.e(TAG, "warning: " + cs.getClass().getCanonicalName() 1106 + " instance is a custom Parcelable and not allowed in Notification"); 1107 return cs.toString(); 1108 } 1109 1110 return cs; 1111 } 1112 1113 public int describeContents() { 1114 return 0; 1115 } 1116 1117 /** 1118 * Flatten this notification from a parcel. 1119 */ 1120 public void writeToParcel(Parcel parcel, int flags) 1121 { 1122 parcel.writeInt(1); 1123 1124 parcel.writeLong(when); 1125 parcel.writeInt(icon); 1126 parcel.writeInt(number); 1127 if (contentIntent != null) { 1128 parcel.writeInt(1); 1129 contentIntent.writeToParcel(parcel, 0); 1130 } else { 1131 parcel.writeInt(0); 1132 } 1133 if (deleteIntent != null) { 1134 parcel.writeInt(1); 1135 deleteIntent.writeToParcel(parcel, 0); 1136 } else { 1137 parcel.writeInt(0); 1138 } 1139 if (tickerText != null) { 1140 parcel.writeInt(1); 1141 TextUtils.writeToParcel(tickerText, parcel, flags); 1142 } else { 1143 parcel.writeInt(0); 1144 } 1145 if (tickerView != null) { 1146 parcel.writeInt(1); 1147 tickerView.writeToParcel(parcel, 0); 1148 } else { 1149 parcel.writeInt(0); 1150 } 1151 if (contentView != null) { 1152 parcel.writeInt(1); 1153 contentView.writeToParcel(parcel, 0); 1154 } else { 1155 parcel.writeInt(0); 1156 } 1157 if (largeIcon != null) { 1158 parcel.writeInt(1); 1159 largeIcon.writeToParcel(parcel, 0); 1160 } else { 1161 parcel.writeInt(0); 1162 } 1163 1164 parcel.writeInt(defaults); 1165 parcel.writeInt(this.flags); 1166 1167 if (sound != null) { 1168 parcel.writeInt(1); 1169 sound.writeToParcel(parcel, 0); 1170 } else { 1171 parcel.writeInt(0); 1172 } 1173 parcel.writeInt(audioStreamType); 1174 parcel.writeLongArray(vibrate); 1175 parcel.writeInt(ledARGB); 1176 parcel.writeInt(ledOnMS); 1177 parcel.writeInt(ledOffMS); 1178 parcel.writeInt(iconLevel); 1179 1180 if (fullScreenIntent != null) { 1181 parcel.writeInt(1); 1182 fullScreenIntent.writeToParcel(parcel, 0); 1183 } else { 1184 parcel.writeInt(0); 1185 } 1186 1187 parcel.writeInt(priority); 1188 1189 parcel.writeString(category); 1190 1191 parcel.writeBundle(extras); // null ok 1192 1193 parcel.writeTypedArray(actions, 0); // null ok 1194 1195 if (bigContentView != null) { 1196 parcel.writeInt(1); 1197 bigContentView.writeToParcel(parcel, 0); 1198 } else { 1199 parcel.writeInt(0); 1200 } 1201 1202 if (headsUpContentView != null) { 1203 parcel.writeInt(1); 1204 headsUpContentView.writeToParcel(parcel, 0); 1205 } else { 1206 parcel.writeInt(0); 1207 } 1208 1209 parcel.writeInt(visibility); 1210 1211 if (publicVersion != null) { 1212 parcel.writeInt(1); 1213 publicVersion.writeToParcel(parcel, 0); 1214 } else { 1215 parcel.writeInt(0); 1216 } 1217 1218 parcel.writeInt(color); 1219 } 1220 1221 /** 1222 * Parcelable.Creator that instantiates Notification objects 1223 */ 1224 public static final Parcelable.Creator<Notification> CREATOR 1225 = new Parcelable.Creator<Notification>() 1226 { 1227 public Notification createFromParcel(Parcel parcel) 1228 { 1229 return new Notification(parcel); 1230 } 1231 1232 public Notification[] newArray(int size) 1233 { 1234 return new Notification[size]; 1235 } 1236 }; 1237 1238 /** 1239 * Sets the {@link #contentView} field to be a view with the standard "Latest Event" 1240 * layout. 1241 * 1242 * <p>Uses the {@link #icon} and {@link #when} fields to set the icon and time fields 1243 * in the view.</p> 1244 * @param context The context for your application / activity. 1245 * @param contentTitle The title that goes in the expanded entry. 1246 * @param contentText The text that goes in the expanded entry. 1247 * @param contentIntent The intent to launch when the user clicks the expanded notification. 1248 * If this is an activity, it must include the 1249 * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires 1250 * that you take care of task management as described in the 1251 * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back 1252 * Stack</a> document. 1253 * 1254 * @deprecated Use {@link Builder} instead. 1255 */ 1256 @Deprecated 1257 public void setLatestEventInfo(Context context, 1258 CharSequence contentTitle, CharSequence contentText, PendingIntent contentIntent) { 1259 Notification.Builder builder = new Notification.Builder(context); 1260 1261 // First, ensure that key pieces of information that may have been set directly 1262 // are preserved 1263 builder.setWhen(this.when); 1264 builder.setSmallIcon(this.icon); 1265 builder.setPriority(this.priority); 1266 builder.setTicker(this.tickerText); 1267 builder.setNumber(this.number); 1268 builder.mFlags = this.flags; 1269 builder.setSound(this.sound, this.audioStreamType); 1270 builder.setDefaults(this.defaults); 1271 builder.setVibrate(this.vibrate); 1272 1273 // now apply the latestEventInfo fields 1274 if (contentTitle != null) { 1275 builder.setContentTitle(contentTitle); 1276 } 1277 if (contentText != null) { 1278 builder.setContentText(contentText); 1279 } 1280 builder.setContentIntent(contentIntent); 1281 builder.buildInto(this); 1282 } 1283 1284 @Override 1285 public String toString() { 1286 StringBuilder sb = new StringBuilder(); 1287 sb.append("Notification(pri="); 1288 sb.append(priority); 1289 sb.append(" contentView="); 1290 if (contentView != null) { 1291 sb.append(contentView.getPackage()); 1292 sb.append("/0x"); 1293 sb.append(Integer.toHexString(contentView.getLayoutId())); 1294 } else { 1295 sb.append("null"); 1296 } 1297 // TODO(dsandler): defaults take precedence over local values, so reorder the branches below 1298 sb.append(" vibrate="); 1299 if ((this.defaults & DEFAULT_VIBRATE) != 0) { 1300 sb.append("default"); 1301 } else if (this.vibrate != null) { 1302 int N = this.vibrate.length-1; 1303 sb.append("["); 1304 for (int i=0; i<N; i++) { 1305 sb.append(this.vibrate[i]); 1306 sb.append(','); 1307 } 1308 if (N != -1) { 1309 sb.append(this.vibrate[N]); 1310 } 1311 sb.append("]"); 1312 } else { 1313 sb.append("null"); 1314 } 1315 sb.append(" sound="); 1316 if ((this.defaults & DEFAULT_SOUND) != 0) { 1317 sb.append("default"); 1318 } else if (this.sound != null) { 1319 sb.append(this.sound.toString()); 1320 } else { 1321 sb.append("null"); 1322 } 1323 sb.append(" defaults=0x"); 1324 sb.append(Integer.toHexString(this.defaults)); 1325 sb.append(" flags=0x"); 1326 sb.append(Integer.toHexString(this.flags)); 1327 sb.append(String.format(" color=0x%08x", this.color)); 1328 sb.append(" category="); sb.append(this.category); 1329 if (actions != null) { 1330 sb.append(" "); 1331 sb.append(actions.length); 1332 sb.append(" action"); 1333 if (actions.length > 1) sb.append("s"); 1334 } 1335 sb.append(")"); 1336 return sb.toString(); 1337 } 1338 1339 /** {@hide} */ 1340 public void setUser(UserHandle user) { 1341 if (user.getIdentifier() == UserHandle.USER_ALL) { 1342 user = UserHandle.OWNER; 1343 } 1344 if (tickerView != null) { 1345 tickerView.setUser(user); 1346 } 1347 if (contentView != null) { 1348 contentView.setUser(user); 1349 } 1350 if (bigContentView != null) { 1351 bigContentView.setUser(user); 1352 } 1353 if (headsUpContentView != null) { 1354 headsUpContentView.setUser(user); 1355 } 1356 } 1357 1358 /** 1359 * Builder class for {@link Notification} objects. 1360 * 1361 * Provides a convenient way to set the various fields of a {@link Notification} and generate 1362 * content views using the platform's notification layout template. If your app supports 1363 * versions of Android as old as API level 4, you can instead use 1364 * {@link android.support.v4.app.NotificationCompat.Builder NotificationCompat.Builder}, 1365 * available in the <a href="{@docRoot}tools/extras/support-library.html">Android Support 1366 * library</a>. 1367 * 1368 * <p>Example: 1369 * 1370 * <pre class="prettyprint"> 1371 * Notification noti = new Notification.Builder(mContext) 1372 * .setContentTitle("New mail from " + sender.toString()) 1373 * .setContentText(subject) 1374 * .setSmallIcon(R.drawable.new_mail) 1375 * .setLargeIcon(aBitmap) 1376 * .build(); 1377 * </pre> 1378 */ 1379 public static class Builder { 1380 private static final int MAX_ACTION_BUTTONS = 3; 1381 1382 private Context mContext; 1383 1384 private long mWhen; 1385 private int mSmallIcon; 1386 private int mSmallIconLevel; 1387 private int mNumber; 1388 private CharSequence mContentTitle; 1389 private CharSequence mContentText; 1390 private CharSequence mContentInfo; 1391 private CharSequence mSubText; 1392 private PendingIntent mContentIntent; 1393 private RemoteViews mContentView; 1394 private PendingIntent mDeleteIntent; 1395 private PendingIntent mFullScreenIntent; 1396 private CharSequence mTickerText; 1397 private RemoteViews mTickerView; 1398 private Bitmap mLargeIcon; 1399 private Uri mSound; 1400 private int mAudioStreamType; 1401 private long[] mVibrate; 1402 private int mLedArgb; 1403 private int mLedOnMs; 1404 private int mLedOffMs; 1405 private int mDefaults; 1406 private int mFlags; 1407 private int mProgressMax; 1408 private int mProgress; 1409 private boolean mProgressIndeterminate; 1410 private String mCategory; 1411 private Bundle mExtras; 1412 private int mPriority; 1413 private ArrayList<Action> mActions = new ArrayList<Action>(MAX_ACTION_BUTTONS); 1414 private boolean mUseChronometer; 1415 private Style mStyle; 1416 private boolean mShowWhen = true; 1417 private int mVisibility = VISIBILITY_PRIVATE; 1418 private Notification mPublicVersion = null; 1419 private final NotificationColorUtil mColorUtil; 1420 private ArrayList<String> mPeople; 1421 private boolean mPreQuantum; 1422 private int mColor = COLOR_DEFAULT; 1423 1424 /** 1425 * Constructs a new Builder with the defaults: 1426 * 1427 1428 * <table> 1429 * <tr><th align=right>priority</th> 1430 * <td>{@link #PRIORITY_DEFAULT}</td></tr> 1431 * <tr><th align=right>when</th> 1432 * <td>now ({@link System#currentTimeMillis()})</td></tr> 1433 * <tr><th align=right>audio stream</th> 1434 * <td>{@link #STREAM_DEFAULT}</td></tr> 1435 * </table> 1436 * 1437 1438 * @param context 1439 * A {@link Context} that will be used by the Builder to construct the 1440 * RemoteViews. The Context will not be held past the lifetime of this Builder 1441 * object. 1442 */ 1443 public Builder(Context context) { 1444 mContext = context; 1445 1446 // Set defaults to match the defaults of a Notification 1447 mWhen = System.currentTimeMillis(); 1448 mAudioStreamType = STREAM_DEFAULT; 1449 mPriority = PRIORITY_DEFAULT; 1450 mPeople = new ArrayList<String>(); 1451 1452 mPreQuantum = context.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.L; 1453 mColorUtil = NotificationColorUtil.getInstance(); 1454 } 1455 1456 /** 1457 * Add a timestamp pertaining to the notification (usually the time the event occurred). 1458 * It will be shown in the notification content view by default; use 1459 * {@link #setShowWhen(boolean) setShowWhen} to control this. 1460 * 1461 * @see Notification#when 1462 */ 1463 public Builder setWhen(long when) { 1464 mWhen = when; 1465 return this; 1466 } 1467 1468 /** 1469 * Control whether the timestamp set with {@link #setWhen(long) setWhen} is shown 1470 * in the content view. 1471 */ 1472 public Builder setShowWhen(boolean show) { 1473 mShowWhen = show; 1474 return this; 1475 } 1476 1477 /** 1478 * Show the {@link Notification#when} field as a stopwatch. 1479 * 1480 * Instead of presenting <code>when</code> as a timestamp, the notification will show an 1481 * automatically updating display of the minutes and seconds since <code>when</code>. 1482 * 1483 * Useful when showing an elapsed time (like an ongoing phone call). 1484 * 1485 * @see android.widget.Chronometer 1486 * @see Notification#when 1487 */ 1488 public Builder setUsesChronometer(boolean b) { 1489 mUseChronometer = b; 1490 return this; 1491 } 1492 1493 /** 1494 * Set the small icon resource, which will be used to represent the notification in the 1495 * status bar. 1496 * 1497 1498 * The platform template for the expanded view will draw this icon in the left, unless a 1499 * {@link #setLargeIcon(Bitmap) large icon} has also been specified, in which case the small 1500 * icon will be moved to the right-hand side. 1501 * 1502 1503 * @param icon 1504 * A resource ID in the application's package of the drawable to use. 1505 * @see Notification#icon 1506 */ 1507 public Builder setSmallIcon(int icon) { 1508 mSmallIcon = icon; 1509 return this; 1510 } 1511 1512 /** 1513 * A variant of {@link #setSmallIcon(int) setSmallIcon(int)} that takes an additional 1514 * level parameter for when the icon is a {@link android.graphics.drawable.LevelListDrawable 1515 * LevelListDrawable}. 1516 * 1517 * @param icon A resource ID in the application's package of the drawable to use. 1518 * @param level The level to use for the icon. 1519 * 1520 * @see Notification#icon 1521 * @see Notification#iconLevel 1522 */ 1523 public Builder setSmallIcon(int icon, int level) { 1524 mSmallIcon = icon; 1525 mSmallIconLevel = level; 1526 return this; 1527 } 1528 1529 /** 1530 * Set the first line of text in the platform notification template. 1531 */ 1532 public Builder setContentTitle(CharSequence title) { 1533 mContentTitle = safeCharSequence(title); 1534 return this; 1535 } 1536 1537 /** 1538 * Set the second line of text in the platform notification template. 1539 */ 1540 public Builder setContentText(CharSequence text) { 1541 mContentText = safeCharSequence(text); 1542 return this; 1543 } 1544 1545 /** 1546 * Set the third line of text in the platform notification template. 1547 * Don't use if you're also using {@link #setProgress(int, int, boolean)}; they occupy the 1548 * same location in the standard template. 1549 */ 1550 public Builder setSubText(CharSequence text) { 1551 mSubText = safeCharSequence(text); 1552 return this; 1553 } 1554 1555 /** 1556 * Set the large number at the right-hand side of the notification. This is 1557 * equivalent to setContentInfo, although it might show the number in a different 1558 * font size for readability. 1559 */ 1560 public Builder setNumber(int number) { 1561 mNumber = number; 1562 return this; 1563 } 1564 1565 /** 1566 * A small piece of additional information pertaining to this notification. 1567 * 1568 * The platform template will draw this on the last line of the notification, at the far 1569 * right (to the right of a smallIcon if it has been placed there). 1570 */ 1571 public Builder setContentInfo(CharSequence info) { 1572 mContentInfo = safeCharSequence(info); 1573 return this; 1574 } 1575 1576 /** 1577 * Set the progress this notification represents. 1578 * 1579 * The platform template will represent this using a {@link ProgressBar}. 1580 */ 1581 public Builder setProgress(int max, int progress, boolean indeterminate) { 1582 mProgressMax = max; 1583 mProgress = progress; 1584 mProgressIndeterminate = indeterminate; 1585 return this; 1586 } 1587 1588 /** 1589 * Supply a custom RemoteViews to use instead of the platform template. 1590 * 1591 * @see Notification#contentView 1592 */ 1593 public Builder setContent(RemoteViews views) { 1594 mContentView = views; 1595 return this; 1596 } 1597 1598 /** 1599 * Supply a {@link PendingIntent} to be sent when the notification is clicked. 1600 * 1601 * As of {@link android.os.Build.VERSION_CODES#HONEYCOMB}, if this field is unset and you 1602 * have specified a custom RemoteViews with {@link #setContent(RemoteViews)}, you can use 1603 * {@link RemoteViews#setOnClickPendingIntent RemoteViews.setOnClickPendingIntent(int,PendingIntent)} 1604 * to assign PendingIntents to individual views in that custom layout (i.e., to create 1605 * clickable buttons inside the notification view). 1606 * 1607 * @see Notification#contentIntent Notification.contentIntent 1608 */ 1609 public Builder setContentIntent(PendingIntent intent) { 1610 mContentIntent = intent; 1611 return this; 1612 } 1613 1614 /** 1615 * Supply a {@link PendingIntent} to send when the notification is cleared explicitly by the user. 1616 * 1617 * @see Notification#deleteIntent 1618 */ 1619 public Builder setDeleteIntent(PendingIntent intent) { 1620 mDeleteIntent = intent; 1621 return this; 1622 } 1623 1624 /** 1625 * An intent to launch instead of posting the notification to the status bar. 1626 * Only for use with extremely high-priority notifications demanding the user's 1627 * <strong>immediate</strong> attention, such as an incoming phone call or 1628 * alarm clock that the user has explicitly set to a particular time. 1629 * If this facility is used for something else, please give the user an option 1630 * to turn it off and use a normal notification, as this can be extremely 1631 * disruptive. 1632 * 1633 * @param intent The pending intent to launch. 1634 * @param highPriority Passing true will cause this notification to be sent 1635 * even if other notifications are suppressed. 1636 * 1637 * @see Notification#fullScreenIntent 1638 */ 1639 public Builder setFullScreenIntent(PendingIntent intent, boolean highPriority) { 1640 mFullScreenIntent = intent; 1641 setFlag(FLAG_HIGH_PRIORITY, highPriority); 1642 return this; 1643 } 1644 1645 /** 1646 * Set the "ticker" text which is displayed in the status bar when the notification first 1647 * arrives. 1648 * 1649 * @see Notification#tickerText 1650 */ 1651 public Builder setTicker(CharSequence tickerText) { 1652 mTickerText = safeCharSequence(tickerText); 1653 return this; 1654 } 1655 1656 /** 1657 * Set the text that is displayed in the status bar when the notification first 1658 * arrives, and also a RemoteViews object that may be displayed instead on some 1659 * devices. 1660 * 1661 * @see Notification#tickerText 1662 * @see Notification#tickerView 1663 */ 1664 public Builder setTicker(CharSequence tickerText, RemoteViews views) { 1665 mTickerText = safeCharSequence(tickerText); 1666 mTickerView = views; 1667 return this; 1668 } 1669 1670 /** 1671 * Add a large icon to the notification (and the ticker on some devices). 1672 * 1673 * In the platform template, this image will be shown on the left of the notification view 1674 * in place of the {@link #setSmallIcon(int) small icon} (which will move to the right side). 1675 * 1676 * @see Notification#largeIcon 1677 */ 1678 public Builder setLargeIcon(Bitmap icon) { 1679 mLargeIcon = icon; 1680 return this; 1681 } 1682 1683 /** 1684 * Set the sound to play. 1685 * 1686 * It will be played on the {@link #STREAM_DEFAULT default stream} for notifications. 1687 * 1688 * @see Notification#sound 1689 */ 1690 public Builder setSound(Uri sound) { 1691 mSound = sound; 1692 mAudioStreamType = STREAM_DEFAULT; 1693 return this; 1694 } 1695 1696 /** 1697 * Set the sound to play, along with a specific stream on which to play it. 1698 * 1699 * See {@link android.media.AudioManager} for the <code>STREAM_</code> constants. 1700 * 1701 * @see Notification#sound 1702 */ 1703 public Builder setSound(Uri sound, int streamType) { 1704 mSound = sound; 1705 mAudioStreamType = streamType; 1706 return this; 1707 } 1708 1709 /** 1710 * Set the vibration pattern to use. 1711 * 1712 1713 * See {@link android.os.Vibrator#vibrate(long[], int)} for a discussion of the 1714 * <code>pattern</code> parameter. 1715 * 1716 1717 * @see Notification#vibrate 1718 */ 1719 public Builder setVibrate(long[] pattern) { 1720 mVibrate = pattern; 1721 return this; 1722 } 1723 1724 /** 1725 * Set the desired color for the indicator LED on the device, as well as the 1726 * blink duty cycle (specified in milliseconds). 1727 * 1728 1729 * Not all devices will honor all (or even any) of these values. 1730 * 1731 1732 * @see Notification#ledARGB 1733 * @see Notification#ledOnMS 1734 * @see Notification#ledOffMS 1735 */ 1736 public Builder setLights(int argb, int onMs, int offMs) { 1737 mLedArgb = argb; 1738 mLedOnMs = onMs; 1739 mLedOffMs = offMs; 1740 return this; 1741 } 1742 1743 /** 1744 * Set whether this is an "ongoing" notification. 1745 * 1746 1747 * Ongoing notifications cannot be dismissed by the user, so your application or service 1748 * must take care of canceling them. 1749 * 1750 1751 * They are typically used to indicate a background task that the user is actively engaged 1752 * with (e.g., playing music) or is pending in some way and therefore occupying the device 1753 * (e.g., a file download, sync operation, active network connection). 1754 * 1755 1756 * @see Notification#FLAG_ONGOING_EVENT 1757 * @see Service#setForeground(boolean) 1758 */ 1759 public Builder setOngoing(boolean ongoing) { 1760 setFlag(FLAG_ONGOING_EVENT, ongoing); 1761 return this; 1762 } 1763 1764 /** 1765 * Set this flag if you would only like the sound, vibrate 1766 * and ticker to be played if the notification is not already showing. 1767 * 1768 * @see Notification#FLAG_ONLY_ALERT_ONCE 1769 */ 1770 public Builder setOnlyAlertOnce(boolean onlyAlertOnce) { 1771 setFlag(FLAG_ONLY_ALERT_ONCE, onlyAlertOnce); 1772 return this; 1773 } 1774 1775 /** 1776 * Make this notification automatically dismissed when the user touches it. The 1777 * PendingIntent set with {@link #setDeleteIntent} will be sent when this happens. 1778 * 1779 * @see Notification#FLAG_AUTO_CANCEL 1780 */ 1781 public Builder setAutoCancel(boolean autoCancel) { 1782 setFlag(FLAG_AUTO_CANCEL, autoCancel); 1783 return this; 1784 } 1785 1786 /** 1787 * Set whether or not this notification should not bridge to other devices. 1788 * 1789 * <p>Some notifications can be bridged to other devices for remote display. 1790 * This hint can be set to recommend this notification not be bridged. 1791 */ 1792 public Builder setLocalOnly(boolean localOnly) { 1793 setFlag(FLAG_LOCAL_ONLY, localOnly); 1794 return this; 1795 } 1796 1797 /** 1798 * Set which notification properties will be inherited from system defaults. 1799 * <p> 1800 * The value should be one or more of the following fields combined with 1801 * bitwise-or: 1802 * {@link #DEFAULT_SOUND}, {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}. 1803 * <p> 1804 * For all default values, use {@link #DEFAULT_ALL}. 1805 */ 1806 public Builder setDefaults(int defaults) { 1807 mDefaults = defaults; 1808 return this; 1809 } 1810 1811 /** 1812 * Set the priority of this notification. 1813 * 1814 * @see Notification#priority 1815 */ 1816 public Builder setPriority(@Priority int pri) { 1817 mPriority = pri; 1818 return this; 1819 } 1820 1821 /** 1822 * Set the notification category. 1823 * 1824 * @see Notification#category 1825 */ 1826 public Builder setCategory(String category) { 1827 mCategory = category; 1828 return this; 1829 } 1830 1831 /** 1832 * Add a person that is relevant to this notification. 1833 * 1834 * @see Notification#EXTRA_PEOPLE 1835 */ 1836 public Builder addPerson(String handle) { 1837 mPeople.add(handle); 1838 return this; 1839 } 1840 1841 /** 1842 * Merge additional metadata into this notification. 1843 * 1844 * <p>Values within the Bundle will replace existing extras values in this Builder. 1845 * 1846 * @see Notification#extras 1847 */ 1848 public Builder addExtras(Bundle extras) { 1849 if (extras != null) { 1850 if (mExtras == null) { 1851 mExtras = new Bundle(extras); 1852 } else { 1853 mExtras.putAll(extras); 1854 } 1855 } 1856 return this; 1857 } 1858 1859 /** 1860 * Set metadata for this notification. 1861 * 1862 * <p>A reference to the Bundle is held for the lifetime of this Builder, and the Bundle's 1863 * current contents are copied into the Notification each time {@link #build()} is 1864 * called. 1865 * 1866 * <p>Replaces any existing extras values with those from the provided Bundle. 1867 * Use {@link #addExtras} to merge in metadata instead. 1868 * 1869 * @see Notification#extras 1870 */ 1871 public Builder setExtras(Bundle extras) { 1872 mExtras = extras; 1873 return this; 1874 } 1875 1876 /** 1877 * Get the current metadata Bundle used by this notification Builder. 1878 * 1879 * <p>The returned Bundle is shared with this Builder. 1880 * 1881 * <p>The current contents of this Bundle are copied into the Notification each time 1882 * {@link #build()} is called. 1883 * 1884 * @see Notification#extras 1885 */ 1886 public Bundle getExtras() { 1887 if (mExtras == null) { 1888 mExtras = new Bundle(); 1889 } 1890 return mExtras; 1891 } 1892 1893 /** 1894 * Add an action to this notification. Actions are typically displayed by 1895 * the system as a button adjacent to the notification content. 1896 * <p> 1897 * Every action must have an icon (32dp square and matching the 1898 * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo 1899 * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}. 1900 * <p> 1901 * A notification in its expanded form can display up to 3 actions, from left to right in 1902 * the order they were added. Actions will not be displayed when the notification is 1903 * collapsed, however, so be sure that any essential functions may be accessed by the user 1904 * in some other way (for example, in the Activity pointed to by {@link #contentIntent}). 1905 * 1906 * @param icon Resource ID of a drawable that represents the action. 1907 * @param title Text describing the action. 1908 * @param intent PendingIntent to be fired when the action is invoked. 1909 */ 1910 public Builder addAction(int icon, CharSequence title, PendingIntent intent) { 1911 mActions.add(new Action(icon, safeCharSequence(title), intent)); 1912 return this; 1913 } 1914 1915 /** 1916 * Add an action to this notification. Actions are typically displayed by 1917 * the system as a button adjacent to the notification content. 1918 * <p> 1919 * Every action must have an icon (32dp square and matching the 1920 * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo 1921 * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}. 1922 * <p> 1923 * A notification in its expanded form can display up to 3 actions, from left to right in 1924 * the order they were added. Actions will not be displayed when the notification is 1925 * collapsed, however, so be sure that any essential functions may be accessed by the user 1926 * in some other way (for example, in the Activity pointed to by {@link #contentIntent}). 1927 * 1928 * @param action The action to add. 1929 */ 1930 public Builder addAction(Action action) { 1931 mActions.add(action); 1932 return this; 1933 } 1934 1935 /** 1936 * Add a rich notification style to be applied at build time. 1937 * 1938 * @param style Object responsible for modifying the notification style. 1939 */ 1940 public Builder setStyle(Style style) { 1941 if (mStyle != style) { 1942 mStyle = style; 1943 if (mStyle != null) { 1944 mStyle.setBuilder(this); 1945 } 1946 } 1947 return this; 1948 } 1949 1950 /** 1951 * Specify the value of {@link #visibility}. 1952 1953 * @param visibility One of {@link #VISIBILITY_PRIVATE} (the default), 1954 * {@link #VISIBILITY_SECRET}, or {@link #VISIBILITY_PUBLIC}. 1955 * 1956 * @return The same Builder. 1957 */ 1958 public Builder setVisibility(int visibility) { 1959 mVisibility = visibility; 1960 return this; 1961 } 1962 1963 /** 1964 * Supply a replacement Notification whose contents should be shown in insecure contexts 1965 * (i.e. atop the secure lockscreen). See {@link #visibility} and {@link #VISIBILITY_PUBLIC}. 1966 * @param n A replacement notification, presumably with some or all info redacted. 1967 * @return The same Builder. 1968 */ 1969 public Builder setPublicVersion(Notification n) { 1970 mPublicVersion = n; 1971 return this; 1972 } 1973 1974 private void setFlag(int mask, boolean value) { 1975 if (value) { 1976 mFlags |= mask; 1977 } else { 1978 mFlags &= ~mask; 1979 } 1980 } 1981 1982 /** 1983 * Sets {@link Notification#color}. 1984 * 1985 * @param argb The accent color to use 1986 * 1987 * @return The same Builder. 1988 */ 1989 public Builder setColor(int argb) { 1990 mColor = argb; 1991 return this; 1992 } 1993 1994 private RemoteViews applyStandardTemplate(int resId, boolean fitIn1U) { 1995 RemoteViews contentView = new RemoteViews(mContext.getPackageName(), resId); 1996 boolean showLine3 = false; 1997 boolean showLine2 = false; 1998 1999 if (mPriority < PRIORITY_LOW) { 2000 // TODO: Low priority presentation 2001 } 2002 if (mLargeIcon != null) { 2003 contentView.setImageViewBitmap(R.id.icon, mLargeIcon); 2004 processLargeIcon(mLargeIcon, contentView); 2005 contentView.setImageViewResource(R.id.right_icon, mSmallIcon); 2006 contentView.setViewVisibility(R.id.right_icon, View.VISIBLE); 2007 processSmallRightIcon(mSmallIcon, contentView); 2008 } else { // small icon at left 2009 contentView.setImageViewResource(R.id.icon, mSmallIcon); 2010 contentView.setViewVisibility(R.id.icon, View.VISIBLE); 2011 processSmallIconAsLarge(mSmallIcon, contentView); 2012 } 2013 if (mContentTitle != null) { 2014 contentView.setTextViewText(R.id.title, processLegacyText(mContentTitle)); 2015 } 2016 if (mContentText != null) { 2017 contentView.setTextViewText(R.id.text, processLegacyText(mContentText)); 2018 showLine3 = true; 2019 } 2020 if (mContentInfo != null) { 2021 contentView.setTextViewText(R.id.info, processLegacyText(mContentInfo)); 2022 contentView.setViewVisibility(R.id.info, View.VISIBLE); 2023 showLine3 = true; 2024 } else if (mNumber > 0) { 2025 final int tooBig = mContext.getResources().getInteger( 2026 R.integer.status_bar_notification_info_maxnum); 2027 if (mNumber > tooBig) { 2028 contentView.setTextViewText(R.id.info, processLegacyText( 2029 mContext.getResources().getString( 2030 R.string.status_bar_notification_info_overflow))); 2031 } else { 2032 NumberFormat f = NumberFormat.getIntegerInstance(); 2033 contentView.setTextViewText(R.id.info, processLegacyText(f.format(mNumber))); 2034 } 2035 contentView.setViewVisibility(R.id.info, View.VISIBLE); 2036 showLine3 = true; 2037 } else { 2038 contentView.setViewVisibility(R.id.info, View.GONE); 2039 } 2040 2041 // Need to show three lines? 2042 if (mSubText != null) { 2043 contentView.setTextViewText(R.id.text, processLegacyText(mSubText)); 2044 if (mContentText != null) { 2045 contentView.setTextViewText(R.id.text2, processLegacyText(mContentText)); 2046 contentView.setViewVisibility(R.id.text2, View.VISIBLE); 2047 showLine2 = true; 2048 } else { 2049 contentView.setViewVisibility(R.id.text2, View.GONE); 2050 } 2051 } else { 2052 contentView.setViewVisibility(R.id.text2, View.GONE); 2053 if (mProgressMax != 0 || mProgressIndeterminate) { 2054 contentView.setProgressBar( 2055 R.id.progress, mProgressMax, mProgress, mProgressIndeterminate); 2056 contentView.setViewVisibility(R.id.progress, View.VISIBLE); 2057 showLine2 = true; 2058 } else { 2059 contentView.setViewVisibility(R.id.progress, View.GONE); 2060 } 2061 } 2062 if (showLine2) { 2063 if (fitIn1U) { 2064 // need to shrink all the type to make sure everything fits 2065 final Resources res = mContext.getResources(); 2066 final float subTextSize = res.getDimensionPixelSize( 2067 R.dimen.notification_subtext_size); 2068 contentView.setTextViewTextSize(R.id.text, TypedValue.COMPLEX_UNIT_PX, subTextSize); 2069 } 2070 // vertical centering 2071 contentView.setViewPadding(R.id.line1, 0, 0, 0, 0); 2072 } 2073 2074 if (mWhen != 0 && mShowWhen) { 2075 if (mUseChronometer) { 2076 contentView.setViewVisibility(R.id.chronometer, View.VISIBLE); 2077 contentView.setLong(R.id.chronometer, "setBase", 2078 mWhen + (SystemClock.elapsedRealtime() - System.currentTimeMillis())); 2079 contentView.setBoolean(R.id.chronometer, "setStarted", true); 2080 } else { 2081 contentView.setViewVisibility(R.id.time, View.VISIBLE); 2082 contentView.setLong(R.id.time, "setTime", mWhen); 2083 } 2084 } else { 2085 contentView.setViewVisibility(R.id.time, View.GONE); 2086 } 2087 2088 contentView.setViewVisibility(R.id.line3, showLine3 ? View.VISIBLE : View.GONE); 2089 contentView.setViewVisibility(R.id.overflow_divider, showLine3 ? View.VISIBLE : View.GONE); 2090 return contentView; 2091 } 2092 2093 private RemoteViews applyStandardTemplateWithActions(int layoutId) { 2094 RemoteViews big = applyStandardTemplate(layoutId, false); 2095 2096 int N = mActions.size(); 2097 if (N > 0) { 2098 // Log.d("Notification", "has actions: " + mContentText); 2099 big.setViewVisibility(R.id.actions, View.VISIBLE); 2100 big.setViewVisibility(R.id.action_divider, View.VISIBLE); 2101 if (N>MAX_ACTION_BUTTONS) N=MAX_ACTION_BUTTONS; 2102 big.removeAllViews(R.id.actions); 2103 for (int i=0; i<N; i++) { 2104 final RemoteViews button = generateActionButton(mActions.get(i)); 2105 //Log.d("Notification", "adding action " + i + ": " + mActions.get(i).title); 2106 big.addView(R.id.actions, button); 2107 } 2108 } 2109 return big; 2110 } 2111 2112 private RemoteViews makeContentView() { 2113 if (mContentView != null) { 2114 return mContentView; 2115 } else { 2116 return applyStandardTemplate(getBaseLayoutResource(), true); // no more special large_icon flavor 2117 } 2118 } 2119 2120 private RemoteViews makeTickerView() { 2121 if (mTickerView != null) { 2122 return mTickerView; 2123 } else { 2124 if (mContentView == null) { 2125 return applyStandardTemplate(mLargeIcon == null 2126 ? R.layout.status_bar_latest_event_ticker 2127 : R.layout.status_bar_latest_event_ticker_large_icon, true); 2128 } else { 2129 return null; 2130 } 2131 } 2132 } 2133 2134 private RemoteViews makeBigContentView() { 2135 if (mActions.size() == 0) return null; 2136 2137 return applyStandardTemplateWithActions(getBigBaseLayoutResource()); 2138 } 2139 2140 private RemoteViews makeHeadsUpContentView() { 2141 if (mActions.size() == 0) return null; 2142 2143 return applyStandardTemplateWithActions(getBigBaseLayoutResource()); 2144 } 2145 2146 2147 private RemoteViews generateActionButton(Action action) { 2148 final boolean tombstone = (action.actionIntent == null); 2149 RemoteViews button = new RemoteViews(mContext.getPackageName(), 2150 tombstone ? getActionTombstoneLayoutResource() 2151 : getActionLayoutResource()); 2152 button.setTextViewCompoundDrawablesRelative(R.id.action0, action.icon, 0, 0, 0); 2153 button.setTextViewText(R.id.action0, processLegacyText(action.title)); 2154 if (!tombstone) { 2155 button.setOnClickPendingIntent(R.id.action0, action.actionIntent); 2156 } 2157 button.setContentDescription(R.id.action0, action.title); 2158 processLegacyAction(action, button); 2159 return button; 2160 } 2161 2162 /** 2163 * @return Whether we are currently building a notification from a legacy (an app that 2164 * doesn't create quantum notifications by itself) app. 2165 */ 2166 private boolean isLegacy() { 2167 return mColorUtil != null; 2168 } 2169 2170 private void processLegacyAction(Action action, RemoteViews button) { 2171 if (isLegacy()) { 2172 if (mColorUtil.isGrayscale(mContext, action.icon)) { 2173 button.setTextViewCompoundDrawablesRelativeColorFilter(R.id.action0, 0, 2174 mContext.getResources().getColor( 2175 R.color.notification_action_legacy_color_filter), 2176 PorterDuff.Mode.MULTIPLY); 2177 } 2178 } 2179 } 2180 2181 private CharSequence processLegacyText(CharSequence charSequence) { 2182 if (isLegacy()) { 2183 return mColorUtil.invertCharSequenceColors(charSequence); 2184 } else { 2185 return charSequence; 2186 } 2187 } 2188 2189 /** 2190 * Apply any necessary background to smallIcons being used in the largeIcon spot. 2191 */ 2192 private void processSmallIconAsLarge(int largeIconId, RemoteViews contentView) { 2193 if (!isLegacy() || mColorUtil.isGrayscale(mContext, largeIconId)) { 2194 applyLargeIconBackground(contentView); 2195 } 2196 } 2197 2198 /** 2199 * Apply any necessary background to a largeIcon if it's a fake smallIcon (that is, 2200 * if it's grayscale). 2201 */ 2202 // TODO: also check bounds, transparency, that sort of thing. 2203 private void processLargeIcon(Bitmap largeIcon, RemoteViews contentView) { 2204 if (!isLegacy() || mColorUtil.isGrayscale(largeIcon)) { 2205 applyLargeIconBackground(contentView); 2206 } else { 2207 removeLargeIconBackground(contentView); 2208 } 2209 } 2210 2211 /** 2212 * Add a colored circle behind the largeIcon slot. 2213 */ 2214 private void applyLargeIconBackground(RemoteViews contentView) { 2215 contentView.setInt(R.id.icon, "setBackgroundResource", 2216 R.drawable.notification_icon_legacy_bg_inset); 2217 2218 contentView.setDrawableParameters( 2219 R.id.icon, 2220 true, 2221 -1, 2222 mColor, 2223 PorterDuff.Mode.SRC_ATOP, 2224 -1); 2225 } 2226 2227 private void removeLargeIconBackground(RemoteViews contentView) { 2228 contentView.setInt(R.id.icon, "setBackgroundResource", 0); 2229 } 2230 2231 /** 2232 * Recolor small icons when used in the R.id.right_icon slot. 2233 */ 2234 private void processSmallRightIcon(int smallIconDrawableId, 2235 RemoteViews contentView) { 2236 if (!isLegacy() || mColorUtil.isGrayscale(mContext, smallIconDrawableId)) { 2237 contentView.setDrawableParameters(R.id.right_icon, false, -1, 2238 0xFFFFFFFF, 2239 PorterDuff.Mode.SRC_ATOP, -1); 2240 2241 contentView.setInt(R.id.right_icon, 2242 "setBackgroundResource", 2243 R.drawable.notification_icon_legacy_bg); 2244 2245 contentView.setDrawableParameters( 2246 R.id.right_icon, 2247 true, 2248 -1, 2249 mColor, 2250 PorterDuff.Mode.SRC_ATOP, 2251 -1); 2252 } 2253 } 2254 2255 private int resolveColor() { 2256 if (mColor == COLOR_DEFAULT) { 2257 mColor = mContext.getResources().getColor(R.color.notification_icon_bg_color); 2258 } else { 2259 mColor |= 0xFF000000; // no alpha for custom colors 2260 } 2261 return mColor; 2262 } 2263 2264 /** 2265 * Apply the unstyled operations and return a new {@link Notification} object. 2266 * @hide 2267 */ 2268 public Notification buildUnstyled() { 2269 Notification n = new Notification(); 2270 n.when = mWhen; 2271 n.icon = mSmallIcon; 2272 n.iconLevel = mSmallIconLevel; 2273 n.number = mNumber; 2274 2275 n.color = resolveColor(); 2276 2277 n.contentView = makeContentView(); 2278 n.contentIntent = mContentIntent; 2279 n.deleteIntent = mDeleteIntent; 2280 n.fullScreenIntent = mFullScreenIntent; 2281 n.tickerText = mTickerText; 2282 n.tickerView = makeTickerView(); 2283 n.largeIcon = mLargeIcon; 2284 n.sound = mSound; 2285 n.audioStreamType = mAudioStreamType; 2286 n.vibrate = mVibrate; 2287 n.ledARGB = mLedArgb; 2288 n.ledOnMS = mLedOnMs; 2289 n.ledOffMS = mLedOffMs; 2290 n.defaults = mDefaults; 2291 n.flags = mFlags; 2292 n.bigContentView = makeBigContentView(); 2293 n.headsUpContentView = makeHeadsUpContentView(); 2294 if (mLedOnMs != 0 || mLedOffMs != 0) { 2295 n.flags |= FLAG_SHOW_LIGHTS; 2296 } 2297 if ((mDefaults & DEFAULT_LIGHTS) != 0) { 2298 n.flags |= FLAG_SHOW_LIGHTS; 2299 } 2300 n.category = mCategory; 2301 n.priority = mPriority; 2302 if (mActions.size() > 0) { 2303 n.actions = new Action[mActions.size()]; 2304 mActions.toArray(n.actions); 2305 } 2306 n.visibility = mVisibility; 2307 2308 if (mPublicVersion != null) { 2309 n.publicVersion = new Notification(); 2310 mPublicVersion.cloneInto(n.publicVersion, true); 2311 } 2312 2313 return n; 2314 } 2315 2316 /** 2317 * Capture, in the provided bundle, semantic information used in the construction of 2318 * this Notification object. 2319 * @hide 2320 */ 2321 public void populateExtras(Bundle extras) { 2322 // Store original information used in the construction of this object 2323 extras.putCharSequence(EXTRA_TITLE, mContentTitle); 2324 extras.putCharSequence(EXTRA_TEXT, mContentText); 2325 extras.putCharSequence(EXTRA_SUB_TEXT, mSubText); 2326 extras.putCharSequence(EXTRA_INFO_TEXT, mContentInfo); 2327 extras.putInt(EXTRA_SMALL_ICON, mSmallIcon); 2328 extras.putInt(EXTRA_PROGRESS, mProgress); 2329 extras.putInt(EXTRA_PROGRESS_MAX, mProgressMax); 2330 extras.putBoolean(EXTRA_PROGRESS_INDETERMINATE, mProgressIndeterminate); 2331 extras.putBoolean(EXTRA_SHOW_CHRONOMETER, mUseChronometer); 2332 extras.putBoolean(EXTRA_SHOW_WHEN, mShowWhen); 2333 if (mLargeIcon != null) { 2334 extras.putParcelable(EXTRA_LARGE_ICON, mLargeIcon); 2335 } 2336 if (!mPeople.isEmpty()) { 2337 extras.putStringArray(EXTRA_PEOPLE, mPeople.toArray(new String[mPeople.size()])); 2338 } 2339 } 2340 2341 /** 2342 * @deprecated Use {@link #build()} instead. 2343 */ 2344 @Deprecated 2345 public Notification getNotification() { 2346 return build(); 2347 } 2348 2349 /** 2350 * Combine all of the options that have been set and return a new {@link Notification} 2351 * object. 2352 */ 2353 public Notification build() { 2354 Notification n = buildUnstyled(); 2355 2356 if (mStyle != null) { 2357 n = mStyle.buildStyled(n); 2358 } 2359 2360 n.extras = mExtras != null ? new Bundle(mExtras) : new Bundle(); 2361 2362 populateExtras(n.extras); 2363 if (mStyle != null) { 2364 mStyle.addExtras(n.extras); 2365 } 2366 2367 return n; 2368 } 2369 2370 /** 2371 * Apply this Builder to an existing {@link Notification} object. 2372 * 2373 * @hide 2374 */ 2375 public Notification buildInto(Notification n) { 2376 build().cloneInto(n, true); 2377 return n; 2378 } 2379 2380 2381 private int getBaseLayoutResource() { 2382 return R.layout.notification_template_quantum_base; 2383 } 2384 2385 private int getBigBaseLayoutResource() { 2386 return R.layout.notification_template_quantum_big_base; 2387 } 2388 2389 private int getBigPictureLayoutResource() { 2390 return R.layout.notification_template_quantum_big_picture; 2391 } 2392 2393 private int getBigTextLayoutResource() { 2394 return R.layout.notification_template_quantum_big_text; 2395 } 2396 2397 private int getInboxLayoutResource() { 2398 return R.layout.notification_template_quantum_inbox; 2399 } 2400 2401 private int getActionLayoutResource() { 2402 return R.layout.notification_quantum_action; 2403 } 2404 2405 private int getActionTombstoneLayoutResource() { 2406 return R.layout.notification_quantum_action_tombstone; 2407 } 2408 } 2409 2410 /** 2411 * An object that can apply a rich notification style to a {@link Notification.Builder} 2412 * object. 2413 */ 2414 public static abstract class Style { 2415 private CharSequence mBigContentTitle; 2416 private CharSequence mSummaryText = null; 2417 private boolean mSummaryTextSet = false; 2418 2419 protected Builder mBuilder; 2420 2421 /** 2422 * Overrides ContentTitle in the big form of the template. 2423 * This defaults to the value passed to setContentTitle(). 2424 */ 2425 protected void internalSetBigContentTitle(CharSequence title) { 2426 mBigContentTitle = title; 2427 } 2428 2429 /** 2430 * Set the first line of text after the detail section in the big form of the template. 2431 */ 2432 protected void internalSetSummaryText(CharSequence cs) { 2433 mSummaryText = cs; 2434 mSummaryTextSet = true; 2435 } 2436 2437 public void setBuilder(Builder builder) { 2438 if (mBuilder != builder) { 2439 mBuilder = builder; 2440 if (mBuilder != null) { 2441 mBuilder.setStyle(this); 2442 } 2443 } 2444 } 2445 2446 protected void checkBuilder() { 2447 if (mBuilder == null) { 2448 throw new IllegalArgumentException("Style requires a valid Builder object"); 2449 } 2450 } 2451 2452 protected RemoteViews getStandardView(int layoutId) { 2453 checkBuilder(); 2454 2455 if (mBigContentTitle != null) { 2456 mBuilder.setContentTitle(mBigContentTitle); 2457 } 2458 2459 RemoteViews contentView = mBuilder.applyStandardTemplateWithActions(layoutId); 2460 2461 if (mBigContentTitle != null && mBigContentTitle.equals("")) { 2462 contentView.setViewVisibility(R.id.line1, View.GONE); 2463 } else { 2464 contentView.setViewVisibility(R.id.line1, View.VISIBLE); 2465 } 2466 2467 // The last line defaults to the subtext, but can be replaced by mSummaryText 2468 final CharSequence overflowText = 2469 mSummaryTextSet ? mSummaryText 2470 : mBuilder.mSubText; 2471 if (overflowText != null) { 2472 contentView.setTextViewText(R.id.text, mBuilder.processLegacyText(overflowText)); 2473 contentView.setViewVisibility(R.id.overflow_divider, View.VISIBLE); 2474 contentView.setViewVisibility(R.id.line3, View.VISIBLE); 2475 } else { 2476 contentView.setViewVisibility(R.id.overflow_divider, View.GONE); 2477 contentView.setViewVisibility(R.id.line3, View.GONE); 2478 } 2479 2480 return contentView; 2481 } 2482 2483 /** 2484 * @hide 2485 */ 2486 public void addExtras(Bundle extras) { 2487 if (mSummaryTextSet) { 2488 extras.putCharSequence(EXTRA_SUMMARY_TEXT, mSummaryText); 2489 } 2490 if (mBigContentTitle != null) { 2491 extras.putCharSequence(EXTRA_TITLE_BIG, mBigContentTitle); 2492 } 2493 extras.putString(EXTRA_TEMPLATE, this.getClass().getName()); 2494 } 2495 2496 /** 2497 * @hide 2498 */ 2499 public abstract Notification buildStyled(Notification wip); 2500 2501 /** 2502 * Calls {@link android.app.Notification.Builder#build()} on the Builder this Style is 2503 * attached to. 2504 * 2505 * @return the fully constructed Notification. 2506 */ 2507 public Notification build() { 2508 checkBuilder(); 2509 return mBuilder.build(); 2510 } 2511 } 2512 2513 /** 2514 * Helper class for generating large-format notifications that include a large image attachment. 2515 * 2516 * This class is a "rebuilder": It consumes a Builder object and modifies its behavior, like so: 2517 * <pre class="prettyprint"> 2518 * Notification noti = new Notification.BigPictureStyle( 2519 * new Notification.Builder() 2520 * .setContentTitle("New photo from " + sender.toString()) 2521 * .setContentText(subject) 2522 * .setSmallIcon(R.drawable.new_post) 2523 * .setLargeIcon(aBitmap)) 2524 * .bigPicture(aBigBitmap) 2525 * .build(); 2526 * </pre> 2527 * 2528 * @see Notification#bigContentView 2529 */ 2530 public static class BigPictureStyle extends Style { 2531 private Bitmap mPicture; 2532 private Bitmap mBigLargeIcon; 2533 private boolean mBigLargeIconSet = false; 2534 2535 public BigPictureStyle() { 2536 } 2537 2538 public BigPictureStyle(Builder builder) { 2539 setBuilder(builder); 2540 } 2541 2542 /** 2543 * Overrides ContentTitle in the big form of the template. 2544 * This defaults to the value passed to setContentTitle(). 2545 */ 2546 public BigPictureStyle setBigContentTitle(CharSequence title) { 2547 internalSetBigContentTitle(safeCharSequence(title)); 2548 return this; 2549 } 2550 2551 /** 2552 * Set the first line of text after the detail section in the big form of the template. 2553 */ 2554 public BigPictureStyle setSummaryText(CharSequence cs) { 2555 internalSetSummaryText(safeCharSequence(cs)); 2556 return this; 2557 } 2558 2559 /** 2560 * Provide the bitmap to be used as the payload for the BigPicture notification. 2561 */ 2562 public BigPictureStyle bigPicture(Bitmap b) { 2563 mPicture = b; 2564 return this; 2565 } 2566 2567 /** 2568 * Override the large icon when the big notification is shown. 2569 */ 2570 public BigPictureStyle bigLargeIcon(Bitmap b) { 2571 mBigLargeIconSet = true; 2572 mBigLargeIcon = b; 2573 return this; 2574 } 2575 2576 private RemoteViews makeBigContentView() { 2577 RemoteViews contentView = getStandardView(mBuilder.getBigPictureLayoutResource()); 2578 2579 contentView.setImageViewBitmap(R.id.big_picture, mPicture); 2580 2581 return contentView; 2582 } 2583 2584 /** 2585 * @hide 2586 */ 2587 public void addExtras(Bundle extras) { 2588 super.addExtras(extras); 2589 2590 if (mBigLargeIconSet) { 2591 extras.putParcelable(EXTRA_LARGE_ICON_BIG, mBigLargeIcon); 2592 } 2593 extras.putParcelable(EXTRA_PICTURE, mPicture); 2594 } 2595 2596 /** 2597 * @hide 2598 */ 2599 @Override 2600 public Notification buildStyled(Notification wip) { 2601 if (mBigLargeIconSet ) { 2602 mBuilder.mLargeIcon = mBigLargeIcon; 2603 } 2604 wip.bigContentView = makeBigContentView(); 2605 return wip; 2606 } 2607 } 2608 2609 /** 2610 * Helper class for generating large-format notifications that include a lot of text. 2611 * 2612 * This class is a "rebuilder": It consumes a Builder object and modifies its behavior, like so: 2613 * <pre class="prettyprint"> 2614 * Notification noti = new Notification.BigTextStyle( 2615 * new Notification.Builder() 2616 * .setContentTitle("New mail from " + sender.toString()) 2617 * .setContentText(subject) 2618 * .setSmallIcon(R.drawable.new_mail) 2619 * .setLargeIcon(aBitmap)) 2620 * .bigText(aVeryLongString) 2621 * .build(); 2622 * </pre> 2623 * 2624 * @see Notification#bigContentView 2625 */ 2626 public static class BigTextStyle extends Style { 2627 private CharSequence mBigText; 2628 2629 public BigTextStyle() { 2630 } 2631 2632 public BigTextStyle(Builder builder) { 2633 setBuilder(builder); 2634 } 2635 2636 /** 2637 * Overrides ContentTitle in the big form of the template. 2638 * This defaults to the value passed to setContentTitle(). 2639 */ 2640 public BigTextStyle setBigContentTitle(CharSequence title) { 2641 internalSetBigContentTitle(safeCharSequence(title)); 2642 return this; 2643 } 2644 2645 /** 2646 * Set the first line of text after the detail section in the big form of the template. 2647 */ 2648 public BigTextStyle setSummaryText(CharSequence cs) { 2649 internalSetSummaryText(safeCharSequence(cs)); 2650 return this; 2651 } 2652 2653 /** 2654 * Provide the longer text to be displayed in the big form of the 2655 * template in place of the content text. 2656 */ 2657 public BigTextStyle bigText(CharSequence cs) { 2658 mBigText = safeCharSequence(cs); 2659 return this; 2660 } 2661 2662 /** 2663 * @hide 2664 */ 2665 public void addExtras(Bundle extras) { 2666 super.addExtras(extras); 2667 2668 extras.putCharSequence(EXTRA_TEXT, mBigText); 2669 } 2670 2671 private RemoteViews makeBigContentView() { 2672 // Remove the content text so line3 only shows if you have a summary 2673 final boolean hadThreeLines = (mBuilder.mContentText != null && mBuilder.mSubText != null); 2674 mBuilder.mContentText = null; 2675 2676 RemoteViews contentView = getStandardView(mBuilder.getBigTextLayoutResource()); 2677 2678 if (hadThreeLines) { 2679 // vertical centering 2680 contentView.setViewPadding(R.id.line1, 0, 0, 0, 0); 2681 } 2682 2683 contentView.setTextViewText(R.id.big_text, mBuilder.processLegacyText(mBigText)); 2684 contentView.setViewVisibility(R.id.big_text, View.VISIBLE); 2685 contentView.setViewVisibility(R.id.text2, View.GONE); 2686 2687 return contentView; 2688 } 2689 2690 /** 2691 * @hide 2692 */ 2693 @Override 2694 public Notification buildStyled(Notification wip) { 2695 wip.bigContentView = makeBigContentView(); 2696 2697 wip.extras.putCharSequence(EXTRA_TEXT, mBigText); 2698 2699 return wip; 2700 } 2701 } 2702 2703 /** 2704 * Helper class for generating large-format notifications that include a list of (up to 5) strings. 2705 * 2706 * This class is a "rebuilder": It consumes a Builder object and modifies its behavior, like so: 2707 * <pre class="prettyprint"> 2708 * Notification noti = new Notification.InboxStyle( 2709 * new Notification.Builder() 2710 * .setContentTitle("5 New mails from " + sender.toString()) 2711 * .setContentText(subject) 2712 * .setSmallIcon(R.drawable.new_mail) 2713 * .setLargeIcon(aBitmap)) 2714 * .addLine(str1) 2715 * .addLine(str2) 2716 * .setContentTitle("") 2717 * .setSummaryText("+3 more") 2718 * .build(); 2719 * </pre> 2720 * 2721 * @see Notification#bigContentView 2722 */ 2723 public static class InboxStyle extends Style { 2724 private ArrayList<CharSequence> mTexts = new ArrayList<CharSequence>(5); 2725 2726 public InboxStyle() { 2727 } 2728 2729 public InboxStyle(Builder builder) { 2730 setBuilder(builder); 2731 } 2732 2733 /** 2734 * Overrides ContentTitle in the big form of the template. 2735 * This defaults to the value passed to setContentTitle(). 2736 */ 2737 public InboxStyle setBigContentTitle(CharSequence title) { 2738 internalSetBigContentTitle(safeCharSequence(title)); 2739 return this; 2740 } 2741 2742 /** 2743 * Set the first line of text after the detail section in the big form of the template. 2744 */ 2745 public InboxStyle setSummaryText(CharSequence cs) { 2746 internalSetSummaryText(safeCharSequence(cs)); 2747 return this; 2748 } 2749 2750 /** 2751 * Append a line to the digest section of the Inbox notification. 2752 */ 2753 public InboxStyle addLine(CharSequence cs) { 2754 mTexts.add(safeCharSequence(cs)); 2755 return this; 2756 } 2757 2758 /** 2759 * @hide 2760 */ 2761 public void addExtras(Bundle extras) { 2762 super.addExtras(extras); 2763 CharSequence[] a = new CharSequence[mTexts.size()]; 2764 extras.putCharSequenceArray(EXTRA_TEXT_LINES, mTexts.toArray(a)); 2765 } 2766 2767 private RemoteViews makeBigContentView() { 2768 // Remove the content text so line3 disappears unless you have a summary 2769 mBuilder.mContentText = null; 2770 RemoteViews contentView = getStandardView(mBuilder.getInboxLayoutResource()); 2771 2772 contentView.setViewVisibility(R.id.text2, View.GONE); 2773 2774 int[] rowIds = {R.id.inbox_text0, R.id.inbox_text1, R.id.inbox_text2, R.id.inbox_text3, 2775 R.id.inbox_text4, R.id.inbox_text5, R.id.inbox_text6}; 2776 2777 // Make sure all rows are gone in case we reuse a view. 2778 for (int rowId : rowIds) { 2779 contentView.setViewVisibility(rowId, View.GONE); 2780 } 2781 2782 2783 int i=0; 2784 while (i < mTexts.size() && i < rowIds.length) { 2785 CharSequence str = mTexts.get(i); 2786 if (str != null && !str.equals("")) { 2787 contentView.setViewVisibility(rowIds[i], View.VISIBLE); 2788 contentView.setTextViewText(rowIds[i], mBuilder.processLegacyText(str)); 2789 } 2790 i++; 2791 } 2792 2793 contentView.setViewVisibility(R.id.inbox_end_pad, 2794 mTexts.size() > 0 ? View.VISIBLE : View.GONE); 2795 2796 contentView.setViewVisibility(R.id.inbox_more, 2797 mTexts.size() > rowIds.length ? View.VISIBLE : View.GONE); 2798 2799 return contentView; 2800 } 2801 2802 /** 2803 * @hide 2804 */ 2805 @Override 2806 public Notification buildStyled(Notification wip) { 2807 wip.bigContentView = makeBigContentView(); 2808 2809 return wip; 2810 } 2811 } 2812} 2813