Notification.java revision 0c69a3e5e8f949e601ed9dac631f26287cfaea47
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.res.Resources; 25import android.graphics.Bitmap; 26import android.graphics.Canvas; 27import android.graphics.PorterDuff; 28import android.graphics.drawable.Drawable; 29import android.media.AudioManager; 30import android.media.session.MediaSession; 31import android.net.Uri; 32import android.os.BadParcelableException; 33import android.os.Bundle; 34import android.os.Parcel; 35import android.os.Parcelable; 36import android.os.SystemClock; 37import android.os.UserHandle; 38import android.os.UserManager; 39import android.text.TextUtils; 40import android.util.Log; 41import android.util.TypedValue; 42import android.view.Gravity; 43import android.view.View; 44import android.widget.ProgressBar; 45import android.widget.RemoteViews; 46 47import com.android.internal.R; 48import com.android.internal.util.NotificationColorUtil; 49 50import java.lang.annotation.Retention; 51import java.lang.annotation.RetentionPolicy; 52import java.text.NumberFormat; 53import java.util.ArrayList; 54import java.util.Arrays; 55import java.util.Collections; 56import java.util.List; 57 58/** 59 * A class that represents how a persistent notification is to be presented to 60 * the user using the {@link android.app.NotificationManager}. 61 * 62 * <p>The {@link Notification.Builder Notification.Builder} has been added to make it 63 * easier to construct Notifications.</p> 64 * 65 * <div class="special reference"> 66 * <h3>Developer Guides</h3> 67 * <p>For a guide to creating notifications, read the 68 * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a> 69 * developer guide.</p> 70 * </div> 71 */ 72public class Notification implements Parcelable 73{ 74 private static final String TAG = "Notification"; 75 76 /** 77 * An activity that provides a user interface for adjusting notification preferences for its 78 * containing application. Optional but recommended for apps that post 79 * {@link android.app.Notification Notifications}. 80 */ 81 @SdkConstant(SdkConstantType.INTENT_CATEGORY) 82 public static final String INTENT_CATEGORY_NOTIFICATION_PREFERENCES 83 = "android.intent.category.NOTIFICATION_PREFERENCES"; 84 85 /** 86 * Use all default values (where applicable). 87 */ 88 public static final int DEFAULT_ALL = ~0; 89 90 /** 91 * Use the default notification sound. This will ignore any given 92 * {@link #sound}. 93 * 94 * <p> 95 * A notification that is noisy is more likely to be presented as a heads-up notification. 96 * </p> 97 * 98 * @see #defaults 99 */ 100 101 public static final int DEFAULT_SOUND = 1; 102 103 /** 104 * Use the default notification vibrate. This will ignore any given 105 * {@link #vibrate}. Using phone vibration requires the 106 * {@link android.Manifest.permission#VIBRATE VIBRATE} permission. 107 * 108 * <p> 109 * A notification that vibrates is more likely to be presented as a heads-up notification. 110 * </p> 111 * 112 * @see #defaults 113 */ 114 115 public static final int DEFAULT_VIBRATE = 2; 116 117 /** 118 * Use the default notification lights. This will ignore the 119 * {@link #FLAG_SHOW_LIGHTS} bit, and {@link #ledARGB}, {@link #ledOffMS}, or 120 * {@link #ledOnMS}. 121 * 122 * @see #defaults 123 */ 124 125 public static final int DEFAULT_LIGHTS = 4; 126 127 /** 128 * A timestamp related to this notification, in milliseconds since the epoch. 129 * 130 * Default value: {@link System#currentTimeMillis() Now}. 131 * 132 * Choose a timestamp that will be most relevant to the user. For most finite events, this 133 * corresponds to the time the event happened (or will happen, in the case of events that have 134 * yet to occur but about which the user is being informed). Indefinite events should be 135 * timestamped according to when the activity began. 136 * 137 * Some examples: 138 * 139 * <ul> 140 * <li>Notification of a new chat message should be stamped when the message was received.</li> 141 * <li>Notification of an ongoing file download (with a progress bar, for example) should be stamped when the download started.</li> 142 * <li>Notification of a completed file download should be stamped when the download finished.</li> 143 * <li>Notification of an upcoming meeting should be stamped with the time the meeting will begin (that is, in the future).</li> 144 * <li>Notification of an ongoing stopwatch (increasing timer) should be stamped with the watch's start time. 145 * <li>Notification of an ongoing countdown timer should be stamped with the timer's end time. 146 * </ul> 147 * 148 */ 149 public long when; 150 151 /** 152 * The resource id of a drawable to use as the icon in the status bar. 153 * This is required; notifications with an invalid icon resource will not be shown. 154 */ 155 public int icon; 156 157 /** 158 * If the icon in the status bar is to have more than one level, you can set this. Otherwise, 159 * leave it at its default value of 0. 160 * 161 * @see android.widget.ImageView#setImageLevel 162 * @see android.graphics.drawable.Drawable#setLevel 163 */ 164 public int iconLevel; 165 166 /** 167 * The number of events that this notification represents. For example, in a new mail 168 * notification, this could be the number of unread messages. 169 * 170 * The system may or may not use this field to modify the appearance of the notification. For 171 * example, before {@link android.os.Build.VERSION_CODES#HONEYCOMB}, this number was 172 * superimposed over the icon in the status bar. Starting with 173 * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, the template used by 174 * {@link Notification.Builder} has displayed the number in the expanded notification view. 175 * 176 * If the number is 0 or negative, it is never shown. 177 */ 178 public int number; 179 180 /** 181 * The intent to execute when the expanded status entry is clicked. If 182 * this is an activity, it must include the 183 * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires 184 * that you take care of task management as described in the 185 * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back 186 * Stack</a> document. In particular, make sure to read the notification section 187 * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html#HandlingNotifications">Handling 188 * Notifications</a> for the correct ways to launch an application from a 189 * notification. 190 */ 191 public PendingIntent contentIntent; 192 193 /** 194 * The intent to execute when the notification is explicitly dismissed by the user, either with 195 * the "Clear All" button or by swiping it away individually. 196 * 197 * This probably shouldn't be launching an activity since several of those will be sent 198 * at the same time. 199 */ 200 public PendingIntent deleteIntent; 201 202 /** 203 * An intent to launch instead of posting the notification to the status bar. 204 * 205 * <p> 206 * The system UI may choose to display a heads-up notification, instead of 207 * launching this intent, while the user is using the device. 208 * </p> 209 * 210 * @see Notification.Builder#setFullScreenIntent 211 */ 212 public PendingIntent fullScreenIntent; 213 214 /** 215 * Text to scroll across the screen when this item is added to 216 * the status bar on large and smaller devices. 217 * 218 * @see #tickerView 219 */ 220 public CharSequence tickerText; 221 222 /** 223 * The view to show as the ticker in the status bar when the notification 224 * is posted. 225 */ 226 public RemoteViews tickerView; 227 228 /** 229 * The view that will represent this notification in the expanded status bar. 230 */ 231 public RemoteViews contentView; 232 233 /** 234 * A large-format version of {@link #contentView}, giving the Notification an 235 * opportunity to show more detail. The system UI may choose to show this 236 * instead of the normal content view at its discretion. 237 */ 238 public RemoteViews bigContentView; 239 240 241 /** 242 * @hide 243 * A medium-format version of {@link #contentView}, providing the Notification an 244 * opportunity to add action buttons to contentView. At its discretion, the system UI may 245 * choose to show this as a heads-up notification, which will pop up so the user can see 246 * it without leaving their current activity. 247 */ 248 public RemoteViews headsUpContentView; 249 250 /** 251 * The bitmap that may escape the bounds of the panel and bar. 252 */ 253 public Bitmap largeIcon; 254 255 /** 256 * The sound to play. 257 * 258 * <p> 259 * A notification that is noisy is more likely to be presented as a heads-up notification. 260 * </p> 261 * 262 * <p> 263 * To play the default notification sound, see {@link #defaults}. 264 * </p> 265 */ 266 public Uri sound; 267 268 /** 269 * Use this constant as the value for audioStreamType to request that 270 * the default stream type for notifications be used. Currently the 271 * default stream type is {@link AudioManager#STREAM_NOTIFICATION}. 272 */ 273 public static final int STREAM_DEFAULT = -1; 274 275 /** 276 * The audio stream type to use when playing the sound. 277 * Should be one of the STREAM_ constants from 278 * {@link android.media.AudioManager}. 279 */ 280 public int audioStreamType = STREAM_DEFAULT; 281 282 /** 283 * The pattern with which to vibrate. 284 * 285 * <p> 286 * To vibrate the default pattern, see {@link #defaults}. 287 * </p> 288 * 289 * <p> 290 * A notification that vibrates is more likely to be presented as a heads-up notification. 291 * </p> 292 * 293 * @see android.os.Vibrator#vibrate(long[],int) 294 */ 295 public long[] vibrate; 296 297 /** 298 * The color of the led. The hardware will do its best approximation. 299 * 300 * @see #FLAG_SHOW_LIGHTS 301 * @see #flags 302 */ 303 public int ledARGB; 304 305 /** 306 * The number of milliseconds for the LED to be on while it's flashing. 307 * The hardware will do its best approximation. 308 * 309 * @see #FLAG_SHOW_LIGHTS 310 * @see #flags 311 */ 312 public int ledOnMS; 313 314 /** 315 * The number of milliseconds for the LED to be off while it's flashing. 316 * The hardware will do its best approximation. 317 * 318 * @see #FLAG_SHOW_LIGHTS 319 * @see #flags 320 */ 321 public int ledOffMS; 322 323 /** 324 * Specifies which values should be taken from the defaults. 325 * <p> 326 * To set, OR the desired from {@link #DEFAULT_SOUND}, 327 * {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}. For all default 328 * values, use {@link #DEFAULT_ALL}. 329 * </p> 330 */ 331 public int defaults; 332 333 /** 334 * Bit to be bitwise-ored into the {@link #flags} field that should be 335 * set if you want the LED on for this notification. 336 * <ul> 337 * <li>To turn the LED off, pass 0 in the alpha channel for colorARGB 338 * or 0 for both ledOnMS and ledOffMS.</li> 339 * <li>To turn the LED on, pass 1 for ledOnMS and 0 for ledOffMS.</li> 340 * <li>To flash the LED, pass the number of milliseconds that it should 341 * be on and off to ledOnMS and ledOffMS.</li> 342 * </ul> 343 * <p> 344 * Since hardware varies, you are not guaranteed that any of the values 345 * you pass are honored exactly. Use the system defaults (TODO) if possible 346 * because they will be set to values that work on any given hardware. 347 * <p> 348 * The alpha channel must be set for forward compatibility. 349 * 350 */ 351 public static final int FLAG_SHOW_LIGHTS = 0x00000001; 352 353 /** 354 * Bit to be bitwise-ored into the {@link #flags} field that should be 355 * set if this notification is in reference to something that is ongoing, 356 * like a phone call. It should not be set if this notification is in 357 * reference to something that happened at a particular point in time, 358 * like a missed phone call. 359 */ 360 public static final int FLAG_ONGOING_EVENT = 0x00000002; 361 362 /** 363 * Bit to be bitwise-ored into the {@link #flags} field that if set, 364 * the audio will be repeated until the notification is 365 * cancelled or the notification window is opened. 366 */ 367 public static final int FLAG_INSISTENT = 0x00000004; 368 369 /** 370 * Bit to be bitwise-ored into the {@link #flags} field that should be 371 * set if you would only like the sound, vibrate and ticker to be played 372 * if the notification was not already showing. 373 */ 374 public static final int FLAG_ONLY_ALERT_ONCE = 0x00000008; 375 376 /** 377 * Bit to be bitwise-ored into the {@link #flags} field that should be 378 * set if the notification should be canceled when it is clicked by the 379 * user. 380 381 */ 382 public static final int FLAG_AUTO_CANCEL = 0x00000010; 383 384 /** 385 * Bit to be bitwise-ored into the {@link #flags} field that should be 386 * set if the notification should not be canceled when the user clicks 387 * the Clear all button. 388 */ 389 public static final int FLAG_NO_CLEAR = 0x00000020; 390 391 /** 392 * Bit to be bitwise-ored into the {@link #flags} field that should be 393 * set if this notification represents a currently running service. This 394 * will normally be set for you by {@link Service#startForeground}. 395 */ 396 public static final int FLAG_FOREGROUND_SERVICE = 0x00000040; 397 398 /** 399 * Obsolete flag indicating high-priority notifications; use the priority field instead. 400 * 401 * @deprecated Use {@link #priority} with a positive value. 402 */ 403 public static final int FLAG_HIGH_PRIORITY = 0x00000080; 404 405 /** 406 * Bit to be bitswise-ored into the {@link #flags} field that should be 407 * set if this notification is relevant to the current device only 408 * and it is not recommended that it bridge to other devices. 409 */ 410 public static final int FLAG_LOCAL_ONLY = 0x00000100; 411 412 /** 413 * Bit to be bitswise-ored into the {@link #flags} field that should be 414 * set if this notification is the group summary for a group of notifications. 415 * Grouped notifications may display in a cluster or stack on devices which 416 * support such rendering. Requires a group key also be set using {@link Builder#setGroup}. 417 */ 418 public static final int FLAG_GROUP_SUMMARY = 0x00000200; 419 420 public int flags; 421 422 /** @hide */ 423 @IntDef({PRIORITY_DEFAULT,PRIORITY_LOW,PRIORITY_MIN,PRIORITY_HIGH,PRIORITY_MAX}) 424 @Retention(RetentionPolicy.SOURCE) 425 public @interface Priority {} 426 427 /** 428 * Default notification {@link #priority}. If your application does not prioritize its own 429 * notifications, use this value for all notifications. 430 */ 431 public static final int PRIORITY_DEFAULT = 0; 432 433 /** 434 * Lower {@link #priority}, for items that are less important. The UI may choose to show these 435 * items smaller, or at a different position in the list, compared with your app's 436 * {@link #PRIORITY_DEFAULT} items. 437 */ 438 public static final int PRIORITY_LOW = -1; 439 440 /** 441 * Lowest {@link #priority}; these items might not be shown to the user except under special 442 * circumstances, such as detailed notification logs. 443 */ 444 public static final int PRIORITY_MIN = -2; 445 446 /** 447 * Higher {@link #priority}, for more important notifications or alerts. The UI may choose to 448 * show these items larger, or at a different position in notification lists, compared with 449 * your app's {@link #PRIORITY_DEFAULT} items. 450 */ 451 public static final int PRIORITY_HIGH = 1; 452 453 /** 454 * Highest {@link #priority}, for your application's most important items that require the 455 * user's prompt attention or input. 456 */ 457 public static final int PRIORITY_MAX = 2; 458 459 /** 460 * Relative priority for this notification. 461 * 462 * Priority is an indication of how much of the user's valuable attention should be consumed by 463 * this notification. Low-priority notifications may be hidden from the user in certain 464 * situations, while the user might be interrupted for a higher-priority notification. The 465 * system will make a determination about how to interpret this priority when presenting 466 * the notification. 467 * 468 * <p> 469 * A notification that is at least {@link #PRIORITY_HIGH} is more likely to be presented 470 * as a heads-up notification. 471 * </p> 472 * 473 */ 474 @Priority 475 public int priority; 476 477 /** 478 * Accent color (an ARGB integer like the constants in {@link android.graphics.Color}) 479 * to be applied by the standard Style templates when presenting this notification. 480 * 481 * The current template design constructs a colorful header image by overlaying the 482 * {@link #icon} image (stenciled in white) atop a field of this color. Alpha components are 483 * ignored. 484 */ 485 public int color = COLOR_DEFAULT; 486 487 /** 488 * Special value of {@link #color} telling the system not to decorate this notification with 489 * any special color but instead use default colors when presenting this notification. 490 */ 491 public static final int COLOR_DEFAULT = 0; // AKA Color.TRANSPARENT 492 493 /** 494 * Sphere of visibility of this notification, which affects how and when the SystemUI reveals 495 * the notification's presence and contents in untrusted situations (namely, on the secure 496 * lockscreen). 497 * 498 * The default level, {@link #VISIBILITY_PRIVATE}, behaves exactly as notifications have always 499 * done on Android: The notification's {@link #icon} and {@link #tickerText} (if available) are 500 * shown in all situations, but the contents are only available if the device is unlocked for 501 * the appropriate user. 502 * 503 * A more permissive policy can be expressed by {@link #VISIBILITY_PUBLIC}; such a notification 504 * can be read even in an "insecure" context (that is, above a secure lockscreen). 505 * To modify the public version of this notification—for example, to redact some portions—see 506 * {@link Builder#setPublicVersion(Notification)}. 507 * 508 * Finally, a notification can be made {@link #VISIBILITY_SECRET}, which will suppress its icon 509 * and ticker until the user has bypassed the lockscreen. 510 */ 511 public int visibility; 512 513 public static final int VISIBILITY_PUBLIC = 1; 514 public static final int VISIBILITY_PRIVATE = 0; 515 public static final int VISIBILITY_SECRET = -1; 516 517 /** 518 * Notification category: incoming call (voice or video) or similar synchronous communication request. 519 */ 520 public static final String CATEGORY_CALL = "call"; 521 522 /** 523 * Notification category: incoming direct message (SMS, instant message, etc.). 524 */ 525 public static final String CATEGORY_MESSAGE = "msg"; 526 527 /** 528 * Notification category: asynchronous bulk message (email). 529 */ 530 public static final String CATEGORY_EMAIL = "email"; 531 532 /** 533 * Notification category: calendar event. 534 */ 535 public static final String CATEGORY_EVENT = "event"; 536 537 /** 538 * Notification category: promotion or advertisement. 539 */ 540 public static final String CATEGORY_PROMO = "promo"; 541 542 /** 543 * Notification category: alarm or timer. 544 */ 545 public static final String CATEGORY_ALARM = "alarm"; 546 547 /** 548 * Notification category: progress of a long-running background operation. 549 */ 550 public static final String CATEGORY_PROGRESS = "progress"; 551 552 /** 553 * Notification category: social network or sharing update. 554 */ 555 public static final String CATEGORY_SOCIAL = "social"; 556 557 /** 558 * Notification category: error in background operation or authentication status. 559 */ 560 public static final String CATEGORY_ERROR = "err"; 561 562 /** 563 * Notification category: media transport control for playback. 564 */ 565 public static final String CATEGORY_TRANSPORT = "transport"; 566 567 /** 568 * Notification category: system or device status update. Reserved for system use. 569 */ 570 public static final String CATEGORY_SYSTEM = "sys"; 571 572 /** 573 * Notification category: indication of running background service. 574 */ 575 public static final String CATEGORY_SERVICE = "service"; 576 577 /** 578 * Notification category: a specific, timely recommendation for a single thing. 579 * For example, a news app might want to recommend a news story it believes the user will 580 * want to read next. 581 */ 582 public static final String CATEGORY_RECOMMENDATION = "recommendation"; 583 584 /** 585 * Notification category: ongoing information about device or contextual status. 586 */ 587 public static final String CATEGORY_STATUS = "status"; 588 589 /** 590 * One of the predefined notification categories (see the <code>CATEGORY_*</code> constants) 591 * that best describes this Notification. May be used by the system for ranking and filtering. 592 */ 593 public String category; 594 595 private String mGroupKey; 596 597 /** 598 * Get the key used to group this notification into a cluster or stack 599 * with other notifications on devices which support such rendering. 600 */ 601 public String getGroup() { 602 return mGroupKey; 603 } 604 605 private String mSortKey; 606 607 /** 608 * Get a sort key that orders this notification among other notifications from the 609 * same package. This can be useful if an external sort was already applied and an app 610 * would like to preserve this. Notifications will be sorted lexicographically using this 611 * value, although providing different priorities in addition to providing sort key may 612 * cause this value to be ignored. 613 * 614 * <p>This sort key can also be used to order members of a notification group. See 615 * {@link Builder#setGroup}. 616 * 617 * @see String#compareTo(String) 618 */ 619 public String getSortKey() { 620 return mSortKey; 621 } 622 623 /** 624 * Additional semantic data to be carried around with this Notification. 625 * <p> 626 * The extras keys defined here are intended to capture the original inputs to {@link Builder} 627 * APIs, and are intended to be used by 628 * {@link android.service.notification.NotificationListenerService} implementations to extract 629 * detailed information from notification objects. 630 */ 631 public Bundle extras = new Bundle(); 632 633 /** 634 * {@link #extras} key: this is the title of the notification, 635 * as supplied to {@link Builder#setContentTitle(CharSequence)}. 636 */ 637 public static final String EXTRA_TITLE = "android.title"; 638 639 /** 640 * {@link #extras} key: this is the title of the notification when shown in expanded form, 641 * e.g. as supplied to {@link BigTextStyle#setBigContentTitle(CharSequence)}. 642 */ 643 public static final String EXTRA_TITLE_BIG = EXTRA_TITLE + ".big"; 644 645 /** 646 * {@link #extras} key: this is the main text payload, as supplied to 647 * {@link Builder#setContentText(CharSequence)}. 648 */ 649 public static final String EXTRA_TEXT = "android.text"; 650 651 /** 652 * {@link #extras} key: this is a third line of text, as supplied to 653 * {@link Builder#setSubText(CharSequence)}. 654 */ 655 public static final String EXTRA_SUB_TEXT = "android.subText"; 656 657 /** 658 * {@link #extras} key: this is a small piece of additional text as supplied to 659 * {@link Builder#setContentInfo(CharSequence)}. 660 */ 661 public static final String EXTRA_INFO_TEXT = "android.infoText"; 662 663 /** 664 * {@link #extras} key: this is a line of summary information intended to be shown 665 * alongside expanded notifications, as supplied to (e.g.) 666 * {@link BigTextStyle#setSummaryText(CharSequence)}. 667 */ 668 public static final String EXTRA_SUMMARY_TEXT = "android.summaryText"; 669 670 /** 671 * {@link #extras} key: this is the resource ID of the notification's main small icon, as 672 * supplied to {@link Builder#setSmallIcon(int)}. 673 */ 674 public static final String EXTRA_SMALL_ICON = "android.icon"; 675 676 /** 677 * {@link #extras} key: this is a bitmap to be used instead of the small icon when showing the 678 * notification payload, as 679 * supplied to {@link Builder#setLargeIcon(android.graphics.Bitmap)}. 680 */ 681 public static final String EXTRA_LARGE_ICON = "android.largeIcon"; 682 683 /** 684 * {@link #extras} key: this is a bitmap to be used instead of the one from 685 * {@link Builder#setLargeIcon(android.graphics.Bitmap)} when the notification is 686 * shown in its expanded form, as supplied to 687 * {@link BigPictureStyle#bigLargeIcon(android.graphics.Bitmap)}. 688 */ 689 public static final String EXTRA_LARGE_ICON_BIG = EXTRA_LARGE_ICON + ".big"; 690 691 /** 692 * {@link #extras} key: this is the progress value supplied to 693 * {@link Builder#setProgress(int, int, boolean)}. 694 */ 695 public static final String EXTRA_PROGRESS = "android.progress"; 696 697 /** 698 * {@link #extras} key: this is the maximum value supplied to 699 * {@link Builder#setProgress(int, int, boolean)}. 700 */ 701 public static final String EXTRA_PROGRESS_MAX = "android.progressMax"; 702 703 /** 704 * {@link #extras} key: whether the progress bar is indeterminate, supplied to 705 * {@link Builder#setProgress(int, int, boolean)}. 706 */ 707 public static final String EXTRA_PROGRESS_INDETERMINATE = "android.progressIndeterminate"; 708 709 /** 710 * {@link #extras} key: whether {@link #when} should be shown as a count-up timer (specifically 711 * a {@link android.widget.Chronometer}) instead of a timestamp, as supplied to 712 * {@link Builder#setUsesChronometer(boolean)}. 713 */ 714 public static final String EXTRA_SHOW_CHRONOMETER = "android.showChronometer"; 715 716 /** 717 * {@link #extras} key: whether {@link #when} should be shown, 718 * as supplied to {@link Builder#setShowWhen(boolean)}. 719 */ 720 public static final String EXTRA_SHOW_WHEN = "android.showWhen"; 721 722 /** 723 * {@link #extras} key: this is a bitmap to be shown in {@link BigPictureStyle} expanded 724 * notifications, supplied to {@link BigPictureStyle#bigPicture(android.graphics.Bitmap)}. 725 */ 726 public static final String EXTRA_PICTURE = "android.picture"; 727 728 /** 729 * {@link #extras} key: An array of CharSequences to show in {@link InboxStyle} expanded 730 * notifications, each of which was supplied to {@link InboxStyle#addLine(CharSequence)}. 731 */ 732 public static final String EXTRA_TEXT_LINES = "android.textLines"; 733 734 /** 735 * {@link #extras} key: A string representing the name of the specific 736 * {@link android.app.Notification.Style} used to create this notification. 737 */ 738 public static final String EXTRA_TEMPLATE = "android.template"; 739 740 /** 741 * {@link #extras} key: An array of people that this notification relates to, specified 742 * by contacts provider contact URI. 743 */ 744 public static final String EXTRA_PEOPLE = "android.people"; 745 746 /** 747 * {@link #extras} key: used to provide hints about the appropriateness of 748 * displaying this notification as a heads-up notification. 749 * @hide 750 */ 751 public static final String EXTRA_AS_HEADS_UP = "headsup"; 752 753 /** 754 * Allow certain system-generated notifications to appear before the device is provisioned. 755 * Only available to notifications coming from the android package. 756 * @hide 757 */ 758 public static final String EXTRA_ALLOW_DURING_SETUP = "android.allowDuringSetup"; 759 760 /** 761 * {@link #extras} key: A 762 * {@link android.content.ContentUris content URI} pointing to an image that can be displayed 763 * in the background when the notification is selected. The URI must point to an image stream 764 * suitable for passing into 765 * {@link android.graphics.BitmapFactory#decodeStream(java.io.InputStream) 766 * BitmapFactory.decodeStream}; all other content types will be ignored. The content provider 767 * URI used for this purpose must require no permissions to read the image data. 768 */ 769 public static final String EXTRA_BACKGROUND_IMAGE_URI = "android.backgroundImageUri"; 770 771 /** 772 * {@link #extras} key: A 773 * {@link android.media.session.MediaSession.Token} associated with a 774 * {@link android.app.Notification.MediaStyle} notification. 775 */ 776 public static final String EXTRA_MEDIA_SESSION = "android.mediaSession"; 777 778 /** 779 * Value for {@link #EXTRA_AS_HEADS_UP} that indicates this notification should not be 780 * displayed in the heads up space. 781 * 782 * <p> 783 * If this notification has a {@link #fullScreenIntent}, then it will always launch the 784 * full-screen intent when posted. 785 * </p> 786 * @hide 787 */ 788 public static final int HEADS_UP_NEVER = 0; 789 790 /** 791 * Default value for {@link #EXTRA_AS_HEADS_UP} that indicates this notification may be 792 * displayed as a heads up. 793 * @hide 794 */ 795 public static final int HEADS_UP_ALLOWED = 1; 796 797 /** 798 * Value for {@link #EXTRA_AS_HEADS_UP} that indicates this notification is a 799 * good candidate for display as a heads up. 800 * @hide 801 */ 802 public static final int HEADS_UP_REQUESTED = 2; 803 804 /** 805 * Structure to encapsulate a named action that can be shown as part of this notification. 806 * It must include an icon, a label, and a {@link PendingIntent} to be fired when the action is 807 * selected by the user. 808 * <p> 809 * Apps should use {@link Notification.Builder#addAction(int, CharSequence, PendingIntent)} 810 * or {@link Notification.Builder#addAction(Notification.Action)} 811 * to attach actions. 812 */ 813 public static class Action implements Parcelable { 814 private final Bundle mExtras; 815 private final RemoteInput[] mRemoteInputs; 816 817 /** 818 * Small icon representing the action. 819 */ 820 public int icon; 821 822 /** 823 * Title of the action. 824 */ 825 public CharSequence title; 826 827 /** 828 * Intent to send when the user invokes this action. May be null, in which case the action 829 * may be rendered in a disabled presentation by the system UI. 830 */ 831 public PendingIntent actionIntent; 832 833 private Action(Parcel in) { 834 icon = in.readInt(); 835 title = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); 836 if (in.readInt() == 1) { 837 actionIntent = PendingIntent.CREATOR.createFromParcel(in); 838 } 839 mExtras = in.readBundle(); 840 mRemoteInputs = in.createTypedArray(RemoteInput.CREATOR); 841 } 842 843 /** 844 * Use {@link Notification.Builder#addAction(int, CharSequence, PendingIntent)}. 845 */ 846 public Action(int icon, CharSequence title, PendingIntent intent) { 847 this(icon, title, intent, new Bundle(), null); 848 } 849 850 private Action(int icon, CharSequence title, PendingIntent intent, Bundle extras, 851 RemoteInput[] remoteInputs) { 852 this.icon = icon; 853 this.title = title; 854 this.actionIntent = intent; 855 this.mExtras = extras != null ? extras : new Bundle(); 856 this.mRemoteInputs = remoteInputs; 857 } 858 859 /** 860 * Get additional metadata carried around with this Action. 861 */ 862 public Bundle getExtras() { 863 return mExtras; 864 } 865 866 /** 867 * Get the list of inputs to be collected from the user when this action is sent. 868 * May return null if no remote inputs were added. 869 */ 870 public RemoteInput[] getRemoteInputs() { 871 return mRemoteInputs; 872 } 873 874 /** 875 * Builder class for {@link Action} objects. 876 */ 877 public static final class Builder { 878 private final int mIcon; 879 private final CharSequence mTitle; 880 private final PendingIntent mIntent; 881 private final Bundle mExtras; 882 private ArrayList<RemoteInput> mRemoteInputs; 883 884 /** 885 * Construct a new builder for {@link Action} object. 886 * @param icon icon to show for this action 887 * @param title the title of the action 888 * @param intent the {@link PendingIntent} to fire when users trigger this action 889 */ 890 public Builder(int icon, CharSequence title, PendingIntent intent) { 891 this(icon, title, intent, new Bundle(), null); 892 } 893 894 /** 895 * Construct a new builder for {@link Action} object using the fields from an 896 * {@link Action}. 897 * @param action the action to read fields from. 898 */ 899 public Builder(Action action) { 900 this(action.icon, action.title, action.actionIntent, new Bundle(action.mExtras), 901 action.getRemoteInputs()); 902 } 903 904 private Builder(int icon, CharSequence title, PendingIntent intent, Bundle extras, 905 RemoteInput[] remoteInputs) { 906 mIcon = icon; 907 mTitle = title; 908 mIntent = intent; 909 mExtras = extras; 910 if (remoteInputs != null) { 911 mRemoteInputs = new ArrayList<RemoteInput>(remoteInputs.length); 912 Collections.addAll(mRemoteInputs, remoteInputs); 913 } 914 } 915 916 /** 917 * Merge additional metadata into this builder. 918 * 919 * <p>Values within the Bundle will replace existing extras values in this Builder. 920 * 921 * @see Notification.Action#extras 922 */ 923 public Builder addExtras(Bundle extras) { 924 if (extras != null) { 925 mExtras.putAll(extras); 926 } 927 return this; 928 } 929 930 /** 931 * Get the metadata Bundle used by this Builder. 932 * 933 * <p>The returned Bundle is shared with this Builder. 934 */ 935 public Bundle getExtras() { 936 return mExtras; 937 } 938 939 /** 940 * Add an input to be collected from the user when this action is sent. 941 * Response values can be retrieved from the fired intent by using the 942 * {@link RemoteInput#getResultsFromIntent} function. 943 * @param remoteInput a {@link RemoteInput} to add to the action 944 * @return this object for method chaining 945 */ 946 public Builder addRemoteInput(RemoteInput remoteInput) { 947 if (mRemoteInputs == null) { 948 mRemoteInputs = new ArrayList<RemoteInput>(); 949 } 950 mRemoteInputs.add(remoteInput); 951 return this; 952 } 953 954 /** 955 * Apply an extender to this action builder. Extenders may be used to add 956 * metadata or change options on this builder. 957 */ 958 public Builder extend(Extender extender) { 959 extender.extend(this); 960 return this; 961 } 962 963 /** 964 * Combine all of the options that have been set and return a new {@link Action} 965 * object. 966 * @return the built action 967 */ 968 public Action build() { 969 RemoteInput[] remoteInputs = mRemoteInputs != null 970 ? mRemoteInputs.toArray(new RemoteInput[mRemoteInputs.size()]) : null; 971 return new Action(mIcon, mTitle, mIntent, mExtras, remoteInputs); 972 } 973 } 974 975 @Override 976 public Action clone() { 977 return new Action( 978 icon, 979 title, 980 actionIntent, // safe to alias 981 new Bundle(mExtras), 982 getRemoteInputs()); 983 } 984 @Override 985 public int describeContents() { 986 return 0; 987 } 988 @Override 989 public void writeToParcel(Parcel out, int flags) { 990 out.writeInt(icon); 991 TextUtils.writeToParcel(title, out, flags); 992 if (actionIntent != null) { 993 out.writeInt(1); 994 actionIntent.writeToParcel(out, flags); 995 } else { 996 out.writeInt(0); 997 } 998 out.writeBundle(mExtras); 999 out.writeTypedArray(mRemoteInputs, flags); 1000 } 1001 public static final Parcelable.Creator<Action> CREATOR = 1002 new Parcelable.Creator<Action>() { 1003 public Action createFromParcel(Parcel in) { 1004 return new Action(in); 1005 } 1006 public Action[] newArray(int size) { 1007 return new Action[size]; 1008 } 1009 }; 1010 1011 /** 1012 * Extender interface for use with {@link Builder#extend}. Extenders may be used to add 1013 * metadata or change options on an action builder. 1014 */ 1015 public interface Extender { 1016 /** 1017 * Apply this extender to a notification action builder. 1018 * @param builder the builder to be modified. 1019 * @return the build object for chaining. 1020 */ 1021 public Builder extend(Builder builder); 1022 } 1023 1024 /** 1025 * Wearable extender for notification actions. To add extensions to an action, 1026 * create a new {@link android.app.Notification.Action.WearableExtender} object using 1027 * the {@code WearableExtender()} constructor and apply it to a 1028 * {@link android.app.Notification.Action.Builder} using 1029 * {@link android.app.Notification.Action.Builder#extend}. 1030 * 1031 * <pre class="prettyprint"> 1032 * Notification.Action action = new Notification.Action.Builder( 1033 * R.drawable.archive_all, "Archive all", actionIntent) 1034 * .extend(new Notification.Action.WearableExtender() 1035 * .setAvailableOffline(false)) 1036 * .build();</pre> 1037 */ 1038 public static final class WearableExtender implements Extender { 1039 /** Notification action extra which contains wearable extensions */ 1040 private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS"; 1041 1042 private static final String KEY_FLAGS = "flags"; 1043 1044 // Flags bitwise-ored to mFlags 1045 private static final int FLAG_AVAILABLE_OFFLINE = 0x1; 1046 1047 // Default value for flags integer 1048 private static final int DEFAULT_FLAGS = FLAG_AVAILABLE_OFFLINE; 1049 1050 private int mFlags = DEFAULT_FLAGS; 1051 1052 /** 1053 * Create a {@link android.app.Notification.Action.WearableExtender} with default 1054 * options. 1055 */ 1056 public WearableExtender() { 1057 } 1058 1059 /** 1060 * Create a {@link android.app.Notification.Action.WearableExtender} by reading 1061 * wearable options present in an existing notification action. 1062 * @param action the notification action to inspect. 1063 */ 1064 public WearableExtender(Action action) { 1065 Bundle wearableBundle = action.getExtras().getBundle(EXTRA_WEARABLE_EXTENSIONS); 1066 if (wearableBundle != null) { 1067 mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS); 1068 } 1069 } 1070 1071 /** 1072 * Apply wearable extensions to a notification action that is being built. This is 1073 * typically called by the {@link android.app.Notification.Action.Builder#extend} 1074 * method of {@link android.app.Notification.Action.Builder}. 1075 */ 1076 @Override 1077 public Action.Builder extend(Action.Builder builder) { 1078 Bundle wearableBundle = new Bundle(); 1079 1080 if (mFlags != DEFAULT_FLAGS) { 1081 wearableBundle.putInt(KEY_FLAGS, mFlags); 1082 } 1083 1084 builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle); 1085 return builder; 1086 } 1087 1088 @Override 1089 public WearableExtender clone() { 1090 WearableExtender that = new WearableExtender(); 1091 that.mFlags = this.mFlags; 1092 return that; 1093 } 1094 1095 /** 1096 * Set whether this action is available when the wearable device is not connected to 1097 * a companion device. The user can still trigger this action when the wearable device is 1098 * offline, but a visual hint will indicate that the action may not be available. 1099 * Defaults to true. 1100 */ 1101 public WearableExtender setAvailableOffline(boolean availableOffline) { 1102 setFlag(FLAG_AVAILABLE_OFFLINE, availableOffline); 1103 return this; 1104 } 1105 1106 /** 1107 * Get whether this action is available when the wearable device is not connected to 1108 * a companion device. The user can still trigger this action when the wearable device is 1109 * offline, but a visual hint will indicate that the action may not be available. 1110 * Defaults to true. 1111 */ 1112 public boolean isAvailableOffline() { 1113 return (mFlags & FLAG_AVAILABLE_OFFLINE) != 0; 1114 } 1115 1116 private void setFlag(int mask, boolean value) { 1117 if (value) { 1118 mFlags |= mask; 1119 } else { 1120 mFlags &= ~mask; 1121 } 1122 } 1123 } 1124 } 1125 1126 /** 1127 * Array of all {@link Action} structures attached to this notification by 1128 * {@link Builder#addAction(int, CharSequence, PendingIntent)}. Mostly useful for instances of 1129 * {@link android.service.notification.NotificationListenerService} that provide an alternative 1130 * interface for invoking actions. 1131 */ 1132 public Action[] actions; 1133 1134 /** 1135 * Replacement version of this notification whose content will be shown 1136 * in an insecure context such as atop a secure keyguard. See {@link #visibility} 1137 * and {@link #VISIBILITY_PUBLIC}. 1138 */ 1139 public Notification publicVersion; 1140 1141 /** 1142 * Constructs a Notification object with default values. 1143 * You might want to consider using {@link Builder} instead. 1144 */ 1145 public Notification() 1146 { 1147 this.when = System.currentTimeMillis(); 1148 this.priority = PRIORITY_DEFAULT; 1149 } 1150 1151 /** 1152 * @hide 1153 */ 1154 public Notification(Context context, int icon, CharSequence tickerText, long when, 1155 CharSequence contentTitle, CharSequence contentText, Intent contentIntent) 1156 { 1157 this.when = when; 1158 this.icon = icon; 1159 this.tickerText = tickerText; 1160 setLatestEventInfo(context, contentTitle, contentText, 1161 PendingIntent.getActivity(context, 0, contentIntent, 0)); 1162 } 1163 1164 /** 1165 * Constructs a Notification object with the information needed to 1166 * have a status bar icon without the standard expanded view. 1167 * 1168 * @param icon The resource id of the icon to put in the status bar. 1169 * @param tickerText The text that flows by in the status bar when the notification first 1170 * activates. 1171 * @param when The time to show in the time field. In the System.currentTimeMillis 1172 * timebase. 1173 * 1174 * @deprecated Use {@link Builder} instead. 1175 */ 1176 @Deprecated 1177 public Notification(int icon, CharSequence tickerText, long when) 1178 { 1179 this.icon = icon; 1180 this.tickerText = tickerText; 1181 this.when = when; 1182 } 1183 1184 /** 1185 * Unflatten the notification from a parcel. 1186 */ 1187 public Notification(Parcel parcel) 1188 { 1189 int version = parcel.readInt(); 1190 1191 when = parcel.readLong(); 1192 icon = parcel.readInt(); 1193 number = parcel.readInt(); 1194 if (parcel.readInt() != 0) { 1195 contentIntent = PendingIntent.CREATOR.createFromParcel(parcel); 1196 } 1197 if (parcel.readInt() != 0) { 1198 deleteIntent = PendingIntent.CREATOR.createFromParcel(parcel); 1199 } 1200 if (parcel.readInt() != 0) { 1201 tickerText = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(parcel); 1202 } 1203 if (parcel.readInt() != 0) { 1204 tickerView = RemoteViews.CREATOR.createFromParcel(parcel); 1205 } 1206 if (parcel.readInt() != 0) { 1207 contentView = RemoteViews.CREATOR.createFromParcel(parcel); 1208 } 1209 if (parcel.readInt() != 0) { 1210 largeIcon = Bitmap.CREATOR.createFromParcel(parcel); 1211 } 1212 defaults = parcel.readInt(); 1213 flags = parcel.readInt(); 1214 if (parcel.readInt() != 0) { 1215 sound = Uri.CREATOR.createFromParcel(parcel); 1216 } 1217 1218 audioStreamType = parcel.readInt(); 1219 vibrate = parcel.createLongArray(); 1220 ledARGB = parcel.readInt(); 1221 ledOnMS = parcel.readInt(); 1222 ledOffMS = parcel.readInt(); 1223 iconLevel = parcel.readInt(); 1224 1225 if (parcel.readInt() != 0) { 1226 fullScreenIntent = PendingIntent.CREATOR.createFromParcel(parcel); 1227 } 1228 1229 priority = parcel.readInt(); 1230 1231 category = parcel.readString(); 1232 1233 mGroupKey = parcel.readString(); 1234 1235 mSortKey = parcel.readString(); 1236 1237 extras = parcel.readBundle(); // may be null 1238 1239 actions = parcel.createTypedArray(Action.CREATOR); // may be null 1240 1241 if (parcel.readInt() != 0) { 1242 bigContentView = RemoteViews.CREATOR.createFromParcel(parcel); 1243 } 1244 1245 if (parcel.readInt() != 0) { 1246 headsUpContentView = RemoteViews.CREATOR.createFromParcel(parcel); 1247 } 1248 1249 visibility = parcel.readInt(); 1250 1251 if (parcel.readInt() != 0) { 1252 publicVersion = Notification.CREATOR.createFromParcel(parcel); 1253 } 1254 1255 color = parcel.readInt(); 1256 } 1257 1258 @Override 1259 public Notification clone() { 1260 Notification that = new Notification(); 1261 cloneInto(that, true); 1262 return that; 1263 } 1264 1265 /** 1266 * Copy all (or if heavy is false, all except Bitmaps and RemoteViews) members 1267 * of this into that. 1268 * @hide 1269 */ 1270 public void cloneInto(Notification that, boolean heavy) { 1271 that.when = this.when; 1272 that.icon = this.icon; 1273 that.number = this.number; 1274 1275 // PendingIntents are global, so there's no reason (or way) to clone them. 1276 that.contentIntent = this.contentIntent; 1277 that.deleteIntent = this.deleteIntent; 1278 that.fullScreenIntent = this.fullScreenIntent; 1279 1280 if (this.tickerText != null) { 1281 that.tickerText = this.tickerText.toString(); 1282 } 1283 if (heavy && this.tickerView != null) { 1284 that.tickerView = this.tickerView.clone(); 1285 } 1286 if (heavy && this.contentView != null) { 1287 that.contentView = this.contentView.clone(); 1288 } 1289 if (heavy && this.largeIcon != null) { 1290 that.largeIcon = Bitmap.createBitmap(this.largeIcon); 1291 } 1292 that.iconLevel = this.iconLevel; 1293 that.sound = this.sound; // android.net.Uri is immutable 1294 that.audioStreamType = this.audioStreamType; 1295 1296 final long[] vibrate = this.vibrate; 1297 if (vibrate != null) { 1298 final int N = vibrate.length; 1299 final long[] vib = that.vibrate = new long[N]; 1300 System.arraycopy(vibrate, 0, vib, 0, N); 1301 } 1302 1303 that.ledARGB = this.ledARGB; 1304 that.ledOnMS = this.ledOnMS; 1305 that.ledOffMS = this.ledOffMS; 1306 that.defaults = this.defaults; 1307 1308 that.flags = this.flags; 1309 1310 that.priority = this.priority; 1311 1312 that.category = this.category; 1313 1314 that.mGroupKey = this.mGroupKey; 1315 1316 that.mSortKey = this.mSortKey; 1317 1318 if (this.extras != null) { 1319 try { 1320 that.extras = new Bundle(this.extras); 1321 // will unparcel 1322 that.extras.size(); 1323 } catch (BadParcelableException e) { 1324 Log.e(TAG, "could not unparcel extras from notification: " + this, e); 1325 that.extras = null; 1326 } 1327 } 1328 1329 if (this.actions != null) { 1330 that.actions = new Action[this.actions.length]; 1331 for(int i=0; i<this.actions.length; i++) { 1332 that.actions[i] = this.actions[i].clone(); 1333 } 1334 } 1335 1336 if (heavy && this.bigContentView != null) { 1337 that.bigContentView = this.bigContentView.clone(); 1338 } 1339 1340 if (heavy && this.headsUpContentView != null) { 1341 that.headsUpContentView = this.headsUpContentView.clone(); 1342 } 1343 1344 that.visibility = this.visibility; 1345 1346 if (this.publicVersion != null) { 1347 that.publicVersion = new Notification(); 1348 this.publicVersion.cloneInto(that.publicVersion, heavy); 1349 } 1350 1351 that.color = this.color; 1352 1353 if (!heavy) { 1354 that.lightenPayload(); // will clean out extras 1355 } 1356 } 1357 1358 /** 1359 * Removes heavyweight parts of the Notification object for archival or for sending to 1360 * listeners when the full contents are not necessary. 1361 * @hide 1362 */ 1363 public final void lightenPayload() { 1364 tickerView = null; 1365 contentView = null; 1366 bigContentView = null; 1367 headsUpContentView = null; 1368 largeIcon = null; 1369 if (extras != null) { 1370 extras.remove(Notification.EXTRA_LARGE_ICON); 1371 extras.remove(Notification.EXTRA_LARGE_ICON_BIG); 1372 extras.remove(Notification.EXTRA_PICTURE); 1373 } 1374 } 1375 1376 /** 1377 * Make sure this CharSequence is safe to put into a bundle, which basically 1378 * means it had better not be some custom Parcelable implementation. 1379 * @hide 1380 */ 1381 public static CharSequence safeCharSequence(CharSequence cs) { 1382 if (cs instanceof Parcelable) { 1383 Log.e(TAG, "warning: " + cs.getClass().getCanonicalName() 1384 + " instance is a custom Parcelable and not allowed in Notification"); 1385 return cs.toString(); 1386 } 1387 1388 return cs; 1389 } 1390 1391 public int describeContents() { 1392 return 0; 1393 } 1394 1395 /** 1396 * Flatten this notification from a parcel. 1397 */ 1398 public void writeToParcel(Parcel parcel, int flags) 1399 { 1400 parcel.writeInt(1); 1401 1402 parcel.writeLong(when); 1403 parcel.writeInt(icon); 1404 parcel.writeInt(number); 1405 if (contentIntent != null) { 1406 parcel.writeInt(1); 1407 contentIntent.writeToParcel(parcel, 0); 1408 } else { 1409 parcel.writeInt(0); 1410 } 1411 if (deleteIntent != null) { 1412 parcel.writeInt(1); 1413 deleteIntent.writeToParcel(parcel, 0); 1414 } else { 1415 parcel.writeInt(0); 1416 } 1417 if (tickerText != null) { 1418 parcel.writeInt(1); 1419 TextUtils.writeToParcel(tickerText, parcel, flags); 1420 } else { 1421 parcel.writeInt(0); 1422 } 1423 if (tickerView != null) { 1424 parcel.writeInt(1); 1425 tickerView.writeToParcel(parcel, 0); 1426 } else { 1427 parcel.writeInt(0); 1428 } 1429 if (contentView != null) { 1430 parcel.writeInt(1); 1431 contentView.writeToParcel(parcel, 0); 1432 } else { 1433 parcel.writeInt(0); 1434 } 1435 if (largeIcon != null) { 1436 parcel.writeInt(1); 1437 largeIcon.writeToParcel(parcel, 0); 1438 } else { 1439 parcel.writeInt(0); 1440 } 1441 1442 parcel.writeInt(defaults); 1443 parcel.writeInt(this.flags); 1444 1445 if (sound != null) { 1446 parcel.writeInt(1); 1447 sound.writeToParcel(parcel, 0); 1448 } else { 1449 parcel.writeInt(0); 1450 } 1451 parcel.writeInt(audioStreamType); 1452 parcel.writeLongArray(vibrate); 1453 parcel.writeInt(ledARGB); 1454 parcel.writeInt(ledOnMS); 1455 parcel.writeInt(ledOffMS); 1456 parcel.writeInt(iconLevel); 1457 1458 if (fullScreenIntent != null) { 1459 parcel.writeInt(1); 1460 fullScreenIntent.writeToParcel(parcel, 0); 1461 } else { 1462 parcel.writeInt(0); 1463 } 1464 1465 parcel.writeInt(priority); 1466 1467 parcel.writeString(category); 1468 1469 parcel.writeString(mGroupKey); 1470 1471 parcel.writeString(mSortKey); 1472 1473 parcel.writeBundle(extras); // null ok 1474 1475 parcel.writeTypedArray(actions, 0); // null ok 1476 1477 if (bigContentView != null) { 1478 parcel.writeInt(1); 1479 bigContentView.writeToParcel(parcel, 0); 1480 } else { 1481 parcel.writeInt(0); 1482 } 1483 1484 if (headsUpContentView != null) { 1485 parcel.writeInt(1); 1486 headsUpContentView.writeToParcel(parcel, 0); 1487 } else { 1488 parcel.writeInt(0); 1489 } 1490 1491 parcel.writeInt(visibility); 1492 1493 if (publicVersion != null) { 1494 parcel.writeInt(1); 1495 publicVersion.writeToParcel(parcel, 0); 1496 } else { 1497 parcel.writeInt(0); 1498 } 1499 1500 parcel.writeInt(color); 1501 } 1502 1503 /** 1504 * Parcelable.Creator that instantiates Notification objects 1505 */ 1506 public static final Parcelable.Creator<Notification> CREATOR 1507 = new Parcelable.Creator<Notification>() 1508 { 1509 public Notification createFromParcel(Parcel parcel) 1510 { 1511 return new Notification(parcel); 1512 } 1513 1514 public Notification[] newArray(int size) 1515 { 1516 return new Notification[size]; 1517 } 1518 }; 1519 1520 /** 1521 * Sets the {@link #contentView} field to be a view with the standard "Latest Event" 1522 * layout. 1523 * 1524 * <p>Uses the {@link #icon} and {@link #when} fields to set the icon and time fields 1525 * in the view.</p> 1526 * @param context The context for your application / activity. 1527 * @param contentTitle The title that goes in the expanded entry. 1528 * @param contentText The text that goes in the expanded entry. 1529 * @param contentIntent The intent to launch when the user clicks the expanded notification. 1530 * If this is an activity, it must include the 1531 * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires 1532 * that you take care of task management as described in the 1533 * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back 1534 * Stack</a> document. 1535 * 1536 * @deprecated Use {@link Builder} instead. 1537 */ 1538 @Deprecated 1539 public void setLatestEventInfo(Context context, 1540 CharSequence contentTitle, CharSequence contentText, PendingIntent contentIntent) { 1541 Notification.Builder builder = new Notification.Builder(context); 1542 1543 // First, ensure that key pieces of information that may have been set directly 1544 // are preserved 1545 builder.setWhen(this.when); 1546 builder.setSmallIcon(this.icon); 1547 builder.setPriority(this.priority); 1548 builder.setTicker(this.tickerText); 1549 builder.setNumber(this.number); 1550 builder.mFlags = this.flags; 1551 builder.setSound(this.sound, this.audioStreamType); 1552 builder.setDefaults(this.defaults); 1553 builder.setVibrate(this.vibrate); 1554 1555 // now apply the latestEventInfo fields 1556 if (contentTitle != null) { 1557 builder.setContentTitle(contentTitle); 1558 } 1559 if (contentText != null) { 1560 builder.setContentText(contentText); 1561 } 1562 builder.setContentIntent(contentIntent); 1563 builder.buildInto(this); 1564 } 1565 1566 @Override 1567 public String toString() { 1568 StringBuilder sb = new StringBuilder(); 1569 sb.append("Notification(pri="); 1570 sb.append(priority); 1571 sb.append(" contentView="); 1572 if (contentView != null) { 1573 sb.append(contentView.getPackage()); 1574 sb.append("/0x"); 1575 sb.append(Integer.toHexString(contentView.getLayoutId())); 1576 } else { 1577 sb.append("null"); 1578 } 1579 // TODO(dsandler): defaults take precedence over local values, so reorder the branches below 1580 sb.append(" vibrate="); 1581 if ((this.defaults & DEFAULT_VIBRATE) != 0) { 1582 sb.append("default"); 1583 } else if (this.vibrate != null) { 1584 int N = this.vibrate.length-1; 1585 sb.append("["); 1586 for (int i=0; i<N; i++) { 1587 sb.append(this.vibrate[i]); 1588 sb.append(','); 1589 } 1590 if (N != -1) { 1591 sb.append(this.vibrate[N]); 1592 } 1593 sb.append("]"); 1594 } else { 1595 sb.append("null"); 1596 } 1597 sb.append(" sound="); 1598 if ((this.defaults & DEFAULT_SOUND) != 0) { 1599 sb.append("default"); 1600 } else if (this.sound != null) { 1601 sb.append(this.sound.toString()); 1602 } else { 1603 sb.append("null"); 1604 } 1605 sb.append(" defaults=0x"); 1606 sb.append(Integer.toHexString(this.defaults)); 1607 sb.append(" flags=0x"); 1608 sb.append(Integer.toHexString(this.flags)); 1609 sb.append(String.format(" color=0x%08x", this.color)); 1610 if (this.category != null) { 1611 sb.append(" category="); 1612 sb.append(this.category); 1613 } 1614 if (this.mGroupKey != null) { 1615 sb.append(" groupKey="); 1616 sb.append(this.mGroupKey); 1617 } 1618 if (this.mSortKey != null) { 1619 sb.append(" sortKey="); 1620 sb.append(this.mSortKey); 1621 } 1622 if (actions != null) { 1623 sb.append(" "); 1624 sb.append(actions.length); 1625 sb.append(" action"); 1626 if (actions.length > 1) sb.append("s"); 1627 } 1628 sb.append(")"); 1629 return sb.toString(); 1630 } 1631 1632 /** {@hide} */ 1633 public void setUser(UserHandle user) { 1634 if (user.getIdentifier() == UserHandle.USER_ALL) { 1635 user = UserHandle.OWNER; 1636 } 1637 if (tickerView != null) { 1638 tickerView.setUser(user); 1639 } 1640 if (contentView != null) { 1641 contentView.setUser(user); 1642 } 1643 if (bigContentView != null) { 1644 bigContentView.setUser(user); 1645 } 1646 if (headsUpContentView != null) { 1647 headsUpContentView.setUser(user); 1648 } 1649 } 1650 1651 /** 1652 * Builder class for {@link Notification} objects. 1653 * 1654 * Provides a convenient way to set the various fields of a {@link Notification} and generate 1655 * content views using the platform's notification layout template. If your app supports 1656 * versions of Android as old as API level 4, you can instead use 1657 * {@link android.support.v4.app.NotificationCompat.Builder NotificationCompat.Builder}, 1658 * available in the <a href="{@docRoot}tools/extras/support-library.html">Android Support 1659 * library</a>. 1660 * 1661 * <p>Example: 1662 * 1663 * <pre class="prettyprint"> 1664 * Notification noti = new Notification.Builder(mContext) 1665 * .setContentTitle("New mail from " + sender.toString()) 1666 * .setContentText(subject) 1667 * .setSmallIcon(R.drawable.new_mail) 1668 * .setLargeIcon(aBitmap) 1669 * .build(); 1670 * </pre> 1671 */ 1672 public static class Builder { 1673 private static final int MAX_ACTION_BUTTONS = 3; 1674 1675 private Context mContext; 1676 1677 private long mWhen; 1678 private int mSmallIcon; 1679 private int mSmallIconLevel; 1680 private int mNumber; 1681 private CharSequence mContentTitle; 1682 private CharSequence mContentText; 1683 private CharSequence mContentInfo; 1684 private CharSequence mSubText; 1685 private PendingIntent mContentIntent; 1686 private RemoteViews mContentView; 1687 private PendingIntent mDeleteIntent; 1688 private PendingIntent mFullScreenIntent; 1689 private CharSequence mTickerText; 1690 private RemoteViews mTickerView; 1691 private Bitmap mLargeIcon; 1692 private Uri mSound; 1693 private int mAudioStreamType; 1694 private long[] mVibrate; 1695 private int mLedArgb; 1696 private int mLedOnMs; 1697 private int mLedOffMs; 1698 private int mDefaults; 1699 private int mFlags; 1700 private int mProgressMax; 1701 private int mProgress; 1702 private boolean mProgressIndeterminate; 1703 private String mCategory; 1704 private String mGroupKey; 1705 private String mSortKey; 1706 private Bundle mExtras; 1707 private int mPriority; 1708 private ArrayList<Action> mActions = new ArrayList<Action>(MAX_ACTION_BUTTONS); 1709 private boolean mUseChronometer; 1710 private Style mStyle; 1711 private boolean mShowWhen = true; 1712 private int mVisibility = VISIBILITY_PRIVATE; 1713 private Notification mPublicVersion = null; 1714 private final NotificationColorUtil mColorUtil; 1715 private ArrayList<String> mPeople; 1716 private int mColor = COLOR_DEFAULT; 1717 1718 /** 1719 * Constructs a new Builder with the defaults: 1720 * 1721 1722 * <table> 1723 * <tr><th align=right>priority</th> 1724 * <td>{@link #PRIORITY_DEFAULT}</td></tr> 1725 * <tr><th align=right>when</th> 1726 * <td>now ({@link System#currentTimeMillis()})</td></tr> 1727 * <tr><th align=right>audio stream</th> 1728 * <td>{@link #STREAM_DEFAULT}</td></tr> 1729 * </table> 1730 * 1731 1732 * @param context 1733 * A {@link Context} that will be used by the Builder to construct the 1734 * RemoteViews. The Context will not be held past the lifetime of this Builder 1735 * object. 1736 */ 1737 public Builder(Context context) { 1738 /* 1739 * Important compatibility note! 1740 * Some apps out in the wild create a Notification.Builder in their Activity subclass 1741 * constructor for later use. At this point Activities - themselves subclasses of 1742 * ContextWrapper - do not have their inner Context populated yet. This means that 1743 * any calls to Context methods from within this constructor can cause NPEs in existing 1744 * apps. Any data populated from mContext should therefore be populated lazily to 1745 * preserve compatibility. 1746 */ 1747 mContext = context; 1748 1749 // Set defaults to match the defaults of a Notification 1750 mWhen = System.currentTimeMillis(); 1751 mAudioStreamType = STREAM_DEFAULT; 1752 mPriority = PRIORITY_DEFAULT; 1753 mPeople = new ArrayList<String>(); 1754 1755 mColorUtil = NotificationColorUtil.getInstance(); 1756 } 1757 1758 /** 1759 * Add a timestamp pertaining to the notification (usually the time the event occurred). 1760 * It will be shown in the notification content view by default; use 1761 * {@link #setShowWhen(boolean) setShowWhen} to control this. 1762 * 1763 * @see Notification#when 1764 */ 1765 public Builder setWhen(long when) { 1766 mWhen = when; 1767 return this; 1768 } 1769 1770 /** 1771 * Control whether the timestamp set with {@link #setWhen(long) setWhen} is shown 1772 * in the content view. 1773 */ 1774 public Builder setShowWhen(boolean show) { 1775 mShowWhen = show; 1776 return this; 1777 } 1778 1779 /** 1780 * Show the {@link Notification#when} field as a stopwatch. 1781 * 1782 * Instead of presenting <code>when</code> as a timestamp, the notification will show an 1783 * automatically updating display of the minutes and seconds since <code>when</code>. 1784 * 1785 * Useful when showing an elapsed time (like an ongoing phone call). 1786 * 1787 * @see android.widget.Chronometer 1788 * @see Notification#when 1789 */ 1790 public Builder setUsesChronometer(boolean b) { 1791 mUseChronometer = b; 1792 return this; 1793 } 1794 1795 /** 1796 * Set the small icon resource, which will be used to represent the notification in the 1797 * status bar. 1798 * 1799 1800 * The platform template for the expanded view will draw this icon in the left, unless a 1801 * {@link #setLargeIcon(Bitmap) large icon} has also been specified, in which case the small 1802 * icon will be moved to the right-hand side. 1803 * 1804 1805 * @param icon 1806 * A resource ID in the application's package of the drawable to use. 1807 * @see Notification#icon 1808 */ 1809 public Builder setSmallIcon(int icon) { 1810 mSmallIcon = icon; 1811 return this; 1812 } 1813 1814 /** 1815 * A variant of {@link #setSmallIcon(int) setSmallIcon(int)} that takes an additional 1816 * level parameter for when the icon is a {@link android.graphics.drawable.LevelListDrawable 1817 * LevelListDrawable}. 1818 * 1819 * @param icon A resource ID in the application's package of the drawable to use. 1820 * @param level The level to use for the icon. 1821 * 1822 * @see Notification#icon 1823 * @see Notification#iconLevel 1824 */ 1825 public Builder setSmallIcon(int icon, int level) { 1826 mSmallIcon = icon; 1827 mSmallIconLevel = level; 1828 return this; 1829 } 1830 1831 /** 1832 * Set the first line of text in the platform notification template. 1833 */ 1834 public Builder setContentTitle(CharSequence title) { 1835 mContentTitle = safeCharSequence(title); 1836 return this; 1837 } 1838 1839 /** 1840 * Set the second line of text in the platform notification template. 1841 */ 1842 public Builder setContentText(CharSequence text) { 1843 mContentText = safeCharSequence(text); 1844 return this; 1845 } 1846 1847 /** 1848 * Set the third line of text in the platform notification template. 1849 * Don't use if you're also using {@link #setProgress(int, int, boolean)}; they occupy the 1850 * same location in the standard template. 1851 */ 1852 public Builder setSubText(CharSequence text) { 1853 mSubText = safeCharSequence(text); 1854 return this; 1855 } 1856 1857 /** 1858 * Set the large number at the right-hand side of the notification. This is 1859 * equivalent to setContentInfo, although it might show the number in a different 1860 * font size for readability. 1861 */ 1862 public Builder setNumber(int number) { 1863 mNumber = number; 1864 return this; 1865 } 1866 1867 /** 1868 * A small piece of additional information pertaining to this notification. 1869 * 1870 * The platform template will draw this on the last line of the notification, at the far 1871 * right (to the right of a smallIcon if it has been placed there). 1872 */ 1873 public Builder setContentInfo(CharSequence info) { 1874 mContentInfo = safeCharSequence(info); 1875 return this; 1876 } 1877 1878 /** 1879 * Set the progress this notification represents. 1880 * 1881 * The platform template will represent this using a {@link ProgressBar}. 1882 */ 1883 public Builder setProgress(int max, int progress, boolean indeterminate) { 1884 mProgressMax = max; 1885 mProgress = progress; 1886 mProgressIndeterminate = indeterminate; 1887 return this; 1888 } 1889 1890 /** 1891 * Supply a custom RemoteViews to use instead of the platform template. 1892 * 1893 * @see Notification#contentView 1894 */ 1895 public Builder setContent(RemoteViews views) { 1896 mContentView = views; 1897 return this; 1898 } 1899 1900 /** 1901 * Supply a {@link PendingIntent} to be sent when the notification is clicked. 1902 * 1903 * As of {@link android.os.Build.VERSION_CODES#HONEYCOMB}, if this field is unset and you 1904 * have specified a custom RemoteViews with {@link #setContent(RemoteViews)}, you can use 1905 * {@link RemoteViews#setOnClickPendingIntent RemoteViews.setOnClickPendingIntent(int,PendingIntent)} 1906 * to assign PendingIntents to individual views in that custom layout (i.e., to create 1907 * clickable buttons inside the notification view). 1908 * 1909 * @see Notification#contentIntent Notification.contentIntent 1910 */ 1911 public Builder setContentIntent(PendingIntent intent) { 1912 mContentIntent = intent; 1913 return this; 1914 } 1915 1916 /** 1917 * Supply a {@link PendingIntent} to send when the notification is cleared explicitly by the user. 1918 * 1919 * @see Notification#deleteIntent 1920 */ 1921 public Builder setDeleteIntent(PendingIntent intent) { 1922 mDeleteIntent = intent; 1923 return this; 1924 } 1925 1926 /** 1927 * An intent to launch instead of posting the notification to the status bar. 1928 * Only for use with extremely high-priority notifications demanding the user's 1929 * <strong>immediate</strong> attention, such as an incoming phone call or 1930 * alarm clock that the user has explicitly set to a particular time. 1931 * If this facility is used for something else, please give the user an option 1932 * to turn it off and use a normal notification, as this can be extremely 1933 * disruptive. 1934 * 1935 * <p> 1936 * The system UI may choose to display a heads-up notification, instead of 1937 * launching this intent, while the user is using the device. 1938 * </p> 1939 * 1940 * @param intent The pending intent to launch. 1941 * @param highPriority Passing true will cause this notification to be sent 1942 * even if other notifications are suppressed. 1943 * 1944 * @see Notification#fullScreenIntent 1945 */ 1946 public Builder setFullScreenIntent(PendingIntent intent, boolean highPriority) { 1947 mFullScreenIntent = intent; 1948 setFlag(FLAG_HIGH_PRIORITY, highPriority); 1949 return this; 1950 } 1951 1952 /** 1953 * Set the "ticker" text which is displayed in the status bar when the notification first 1954 * arrives. 1955 * 1956 * @see Notification#tickerText 1957 */ 1958 public Builder setTicker(CharSequence tickerText) { 1959 mTickerText = safeCharSequence(tickerText); 1960 return this; 1961 } 1962 1963 /** 1964 * Set the text that is displayed in the status bar when the notification first 1965 * arrives, and also a RemoteViews object that may be displayed instead on some 1966 * devices. 1967 * 1968 * @see Notification#tickerText 1969 * @see Notification#tickerView 1970 */ 1971 public Builder setTicker(CharSequence tickerText, RemoteViews views) { 1972 mTickerText = safeCharSequence(tickerText); 1973 mTickerView = views; 1974 return this; 1975 } 1976 1977 /** 1978 * Add a large icon to the notification (and the ticker on some devices). 1979 * 1980 * In the platform template, this image will be shown on the left of the notification view 1981 * in place of the {@link #setSmallIcon(int) small icon} (which will move to the right side). 1982 * 1983 * @see Notification#largeIcon 1984 */ 1985 public Builder setLargeIcon(Bitmap icon) { 1986 mLargeIcon = icon; 1987 return this; 1988 } 1989 1990 /** 1991 * Set the sound to play. 1992 * 1993 * It will be played on the {@link #STREAM_DEFAULT default stream} for notifications. 1994 * 1995 * <p> 1996 * A notification that is noisy is more likely to be presented as a heads-up notification. 1997 * </p> 1998 * 1999 * @see Notification#sound 2000 */ 2001 public Builder setSound(Uri sound) { 2002 mSound = sound; 2003 mAudioStreamType = STREAM_DEFAULT; 2004 return this; 2005 } 2006 2007 /** 2008 * Set the sound to play, along with a specific stream on which to play it. 2009 * 2010 * See {@link android.media.AudioManager} for the <code>STREAM_</code> constants. 2011 * 2012 * <p> 2013 * A notification that is noisy is more likely to be presented as a heads-up notification. 2014 * </p> 2015 * 2016 * @see Notification#sound 2017 */ 2018 public Builder setSound(Uri sound, int streamType) { 2019 mSound = sound; 2020 mAudioStreamType = streamType; 2021 return this; 2022 } 2023 2024 /** 2025 * Set the vibration pattern to use. 2026 * 2027 * See {@link android.os.Vibrator#vibrate(long[], int)} for a discussion of the 2028 * <code>pattern</code> parameter. 2029 * 2030 * <p> 2031 * A notification that vibrates is more likely to be presented as a heads-up notification. 2032 * </p> 2033 * 2034 * @see Notification#vibrate 2035 */ 2036 public Builder setVibrate(long[] pattern) { 2037 mVibrate = pattern; 2038 return this; 2039 } 2040 2041 /** 2042 * Set the desired color for the indicator LED on the device, as well as the 2043 * blink duty cycle (specified in milliseconds). 2044 * 2045 2046 * Not all devices will honor all (or even any) of these values. 2047 * 2048 2049 * @see Notification#ledARGB 2050 * @see Notification#ledOnMS 2051 * @see Notification#ledOffMS 2052 */ 2053 public Builder setLights(int argb, int onMs, int offMs) { 2054 mLedArgb = argb; 2055 mLedOnMs = onMs; 2056 mLedOffMs = offMs; 2057 return this; 2058 } 2059 2060 /** 2061 * Set whether this is an "ongoing" notification. 2062 * 2063 2064 * Ongoing notifications cannot be dismissed by the user, so your application or service 2065 * must take care of canceling them. 2066 * 2067 2068 * They are typically used to indicate a background task that the user is actively engaged 2069 * with (e.g., playing music) or is pending in some way and therefore occupying the device 2070 * (e.g., a file download, sync operation, active network connection). 2071 * 2072 2073 * @see Notification#FLAG_ONGOING_EVENT 2074 * @see Service#setForeground(boolean) 2075 */ 2076 public Builder setOngoing(boolean ongoing) { 2077 setFlag(FLAG_ONGOING_EVENT, ongoing); 2078 return this; 2079 } 2080 2081 /** 2082 * Set this flag if you would only like the sound, vibrate 2083 * and ticker to be played if the notification is not already showing. 2084 * 2085 * @see Notification#FLAG_ONLY_ALERT_ONCE 2086 */ 2087 public Builder setOnlyAlertOnce(boolean onlyAlertOnce) { 2088 setFlag(FLAG_ONLY_ALERT_ONCE, onlyAlertOnce); 2089 return this; 2090 } 2091 2092 /** 2093 * Make this notification automatically dismissed when the user touches it. The 2094 * PendingIntent set with {@link #setDeleteIntent} will be sent when this happens. 2095 * 2096 * @see Notification#FLAG_AUTO_CANCEL 2097 */ 2098 public Builder setAutoCancel(boolean autoCancel) { 2099 setFlag(FLAG_AUTO_CANCEL, autoCancel); 2100 return this; 2101 } 2102 2103 /** 2104 * Set whether or not this notification should not bridge to other devices. 2105 * 2106 * <p>Some notifications can be bridged to other devices for remote display. 2107 * This hint can be set to recommend this notification not be bridged. 2108 */ 2109 public Builder setLocalOnly(boolean localOnly) { 2110 setFlag(FLAG_LOCAL_ONLY, localOnly); 2111 return this; 2112 } 2113 2114 /** 2115 * Set which notification properties will be inherited from system defaults. 2116 * <p> 2117 * The value should be one or more of the following fields combined with 2118 * bitwise-or: 2119 * {@link #DEFAULT_SOUND}, {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}. 2120 * <p> 2121 * For all default values, use {@link #DEFAULT_ALL}. 2122 */ 2123 public Builder setDefaults(int defaults) { 2124 mDefaults = defaults; 2125 return this; 2126 } 2127 2128 /** 2129 * Set the priority of this notification. 2130 * 2131 * @see Notification#priority 2132 */ 2133 public Builder setPriority(@Priority int pri) { 2134 mPriority = pri; 2135 return this; 2136 } 2137 2138 /** 2139 * Set the notification category. 2140 * 2141 * @see Notification#category 2142 */ 2143 public Builder setCategory(String category) { 2144 mCategory = category; 2145 return this; 2146 } 2147 2148 /** 2149 * Add a person that is relevant to this notification. 2150 * 2151 * @see Notification#EXTRA_PEOPLE 2152 */ 2153 public Builder addPerson(String handle) { 2154 mPeople.add(handle); 2155 return this; 2156 } 2157 2158 /** 2159 * Set this notification to be part of a group of notifications sharing the same key. 2160 * Grouped notifications may display in a cluster or stack on devices which 2161 * support such rendering. 2162 * 2163 * <p>To make this notification the summary for its group, also call 2164 * {@link #setGroupSummary}. A sort order can be specified for group members by using 2165 * {@link #setSortKey}. 2166 * @param groupKey The group key of the group. 2167 * @return this object for method chaining 2168 */ 2169 public Builder setGroup(String groupKey) { 2170 mGroupKey = groupKey; 2171 return this; 2172 } 2173 2174 /** 2175 * Set this notification to be the group summary for a group of notifications. 2176 * Grouped notifications may display in a cluster or stack on devices which 2177 * support such rendering. Requires a group key also be set using {@link #setGroup}. 2178 * @param isGroupSummary Whether this notification should be a group summary. 2179 * @return this object for method chaining 2180 */ 2181 public Builder setGroupSummary(boolean isGroupSummary) { 2182 setFlag(FLAG_GROUP_SUMMARY, isGroupSummary); 2183 return this; 2184 } 2185 2186 /** 2187 * Set a sort key that orders this notification among other notifications from the 2188 * same package. This can be useful if an external sort was already applied and an app 2189 * would like to preserve this. Notifications will be sorted lexicographically using this 2190 * value, although providing different priorities in addition to providing sort key may 2191 * cause this value to be ignored. 2192 * 2193 * <p>This sort key can also be used to order members of a notification group. See 2194 * {@link #setGroup}. 2195 * 2196 * @see String#compareTo(String) 2197 */ 2198 public Builder setSortKey(String sortKey) { 2199 mSortKey = sortKey; 2200 return this; 2201 } 2202 2203 /** 2204 * Merge additional metadata into this notification. 2205 * 2206 * <p>Values within the Bundle will replace existing extras values in this Builder. 2207 * 2208 * @see Notification#extras 2209 */ 2210 public Builder addExtras(Bundle extras) { 2211 if (extras != null) { 2212 if (mExtras == null) { 2213 mExtras = new Bundle(extras); 2214 } else { 2215 mExtras.putAll(extras); 2216 } 2217 } 2218 return this; 2219 } 2220 2221 /** 2222 * Set metadata for this notification. 2223 * 2224 * <p>A reference to the Bundle is held for the lifetime of this Builder, and the Bundle's 2225 * current contents are copied into the Notification each time {@link #build()} is 2226 * called. 2227 * 2228 * <p>Replaces any existing extras values with those from the provided Bundle. 2229 * Use {@link #addExtras} to merge in metadata instead. 2230 * 2231 * @see Notification#extras 2232 */ 2233 public Builder setExtras(Bundle extras) { 2234 mExtras = extras; 2235 return this; 2236 } 2237 2238 /** 2239 * Get the current metadata Bundle used by this notification Builder. 2240 * 2241 * <p>The returned Bundle is shared with this Builder. 2242 * 2243 * <p>The current contents of this Bundle are copied into the Notification each time 2244 * {@link #build()} is called. 2245 * 2246 * @see Notification#extras 2247 */ 2248 public Bundle getExtras() { 2249 if (mExtras == null) { 2250 mExtras = new Bundle(); 2251 } 2252 return mExtras; 2253 } 2254 2255 /** 2256 * Add an action to this notification. Actions are typically displayed by 2257 * the system as a button adjacent to the notification content. 2258 * <p> 2259 * Every action must have an icon (32dp square and matching the 2260 * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo 2261 * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}. 2262 * <p> 2263 * A notification in its expanded form can display up to 3 actions, from left to right in 2264 * the order they were added. Actions will not be displayed when the notification is 2265 * collapsed, however, so be sure that any essential functions may be accessed by the user 2266 * in some other way (for example, in the Activity pointed to by {@link #contentIntent}). 2267 * 2268 * @param icon Resource ID of a drawable that represents the action. 2269 * @param title Text describing the action. 2270 * @param intent PendingIntent to be fired when the action is invoked. 2271 */ 2272 public Builder addAction(int icon, CharSequence title, PendingIntent intent) { 2273 mActions.add(new Action(icon, safeCharSequence(title), intent)); 2274 return this; 2275 } 2276 2277 /** 2278 * Add an action to this notification. Actions are typically displayed by 2279 * the system as a button adjacent to the notification content. 2280 * <p> 2281 * Every action must have an icon (32dp square and matching the 2282 * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo 2283 * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}. 2284 * <p> 2285 * A notification in its expanded form can display up to 3 actions, from left to right in 2286 * the order they were added. Actions will not be displayed when the notification is 2287 * collapsed, however, so be sure that any essential functions may be accessed by the user 2288 * in some other way (for example, in the Activity pointed to by {@link #contentIntent}). 2289 * 2290 * @param action The action to add. 2291 */ 2292 public Builder addAction(Action action) { 2293 mActions.add(action); 2294 return this; 2295 } 2296 2297 /** 2298 * Add a rich notification style to be applied at build time. 2299 * 2300 * @param style Object responsible for modifying the notification style. 2301 */ 2302 public Builder setStyle(Style style) { 2303 if (mStyle != style) { 2304 mStyle = style; 2305 if (mStyle != null) { 2306 mStyle.setBuilder(this); 2307 } 2308 } 2309 return this; 2310 } 2311 2312 /** 2313 * Specify the value of {@link #visibility}. 2314 * 2315 * @param visibility One of {@link #VISIBILITY_PRIVATE} (the default), 2316 * {@link #VISIBILITY_SECRET}, or {@link #VISIBILITY_PUBLIC}. 2317 * 2318 * @return The same Builder. 2319 */ 2320 public Builder setVisibility(int visibility) { 2321 mVisibility = visibility; 2322 return this; 2323 } 2324 2325 /** 2326 * Supply a replacement Notification whose contents should be shown in insecure contexts 2327 * (i.e. atop the secure lockscreen). See {@link #visibility} and {@link #VISIBILITY_PUBLIC}. 2328 * @param n A replacement notification, presumably with some or all info redacted. 2329 * @return The same Builder. 2330 */ 2331 public Builder setPublicVersion(Notification n) { 2332 mPublicVersion = n; 2333 return this; 2334 } 2335 2336 /** 2337 * Apply an extender to this notification builder. Extenders may be used to add 2338 * metadata or change options on this builder. 2339 */ 2340 public Builder extend(Extender extender) { 2341 extender.extend(this); 2342 return this; 2343 } 2344 2345 private void setFlag(int mask, boolean value) { 2346 if (value) { 2347 mFlags |= mask; 2348 } else { 2349 mFlags &= ~mask; 2350 } 2351 } 2352 2353 /** 2354 * Sets {@link Notification#color}. 2355 * 2356 * @param argb The accent color to use 2357 * 2358 * @return The same Builder. 2359 */ 2360 public Builder setColor(int argb) { 2361 mColor = argb; 2362 return this; 2363 } 2364 2365 private Bitmap getProfileBadge() { 2366 UserManager userManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE); 2367 Drawable badge = userManager.getBadgeForUser(android.os.Process.myUserHandle()); 2368 if (badge == null) { 2369 return null; 2370 } 2371 final int width = badge.getIntrinsicWidth(); 2372 final int height = badge.getIntrinsicHeight(); 2373 Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 2374 Canvas canvas = new Canvas(bitmap); 2375 badge.setBounds(0, 0, width, height); 2376 badge.draw(canvas); 2377 return bitmap; 2378 } 2379 2380 private RemoteViews applyStandardTemplate(int resId, boolean fitIn1U) { 2381 Bitmap profileIcon = getProfileBadge(); 2382 RemoteViews contentView = new RemoteViews(mContext.getPackageName(), resId); 2383 boolean showLine3 = false; 2384 boolean showLine2 = false; 2385 2386 if (mPriority < PRIORITY_LOW) { 2387 // TODO: Low priority presentation 2388 } 2389 if (profileIcon != null) { 2390 contentView.setImageViewBitmap(R.id.profile_icon, profileIcon); 2391 contentView.setViewVisibility(R.id.profile_icon, View.VISIBLE); 2392 } else { 2393 contentView.setViewVisibility(R.id.profile_icon, View.GONE); 2394 } 2395 if (mLargeIcon != null) { 2396 contentView.setImageViewBitmap(R.id.icon, mLargeIcon); 2397 processLargeIcon(mLargeIcon, contentView); 2398 contentView.setImageViewResource(R.id.right_icon, mSmallIcon); 2399 contentView.setViewVisibility(R.id.right_icon, View.VISIBLE); 2400 processSmallRightIcon(mSmallIcon, contentView); 2401 } else { // small icon at left 2402 contentView.setImageViewResource(R.id.icon, mSmallIcon); 2403 contentView.setViewVisibility(R.id.icon, View.VISIBLE); 2404 processSmallIconAsLarge(mSmallIcon, contentView); 2405 } 2406 if (mContentTitle != null) { 2407 contentView.setTextViewText(R.id.title, processLegacyText(mContentTitle)); 2408 } 2409 if (mContentText != null) { 2410 contentView.setTextViewText(R.id.text, processLegacyText(mContentText)); 2411 showLine3 = true; 2412 } 2413 if (mContentInfo != null) { 2414 contentView.setTextViewText(R.id.info, processLegacyText(mContentInfo)); 2415 contentView.setViewVisibility(R.id.info, View.VISIBLE); 2416 showLine3 = true; 2417 } else if (mNumber > 0) { 2418 final int tooBig = mContext.getResources().getInteger( 2419 R.integer.status_bar_notification_info_maxnum); 2420 if (mNumber > tooBig) { 2421 contentView.setTextViewText(R.id.info, processLegacyText( 2422 mContext.getResources().getString( 2423 R.string.status_bar_notification_info_overflow))); 2424 } else { 2425 NumberFormat f = NumberFormat.getIntegerInstance(); 2426 contentView.setTextViewText(R.id.info, processLegacyText(f.format(mNumber))); 2427 } 2428 contentView.setViewVisibility(R.id.info, View.VISIBLE); 2429 showLine3 = true; 2430 } else { 2431 contentView.setViewVisibility(R.id.info, View.GONE); 2432 } 2433 2434 // Need to show three lines? 2435 if (mSubText != null) { 2436 contentView.setTextViewText(R.id.text, processLegacyText(mSubText)); 2437 if (mContentText != null) { 2438 contentView.setTextViewText(R.id.text2, processLegacyText(mContentText)); 2439 contentView.setViewVisibility(R.id.text2, View.VISIBLE); 2440 showLine2 = true; 2441 } else { 2442 contentView.setViewVisibility(R.id.text2, View.GONE); 2443 } 2444 } else { 2445 contentView.setViewVisibility(R.id.text2, View.GONE); 2446 if (mProgressMax != 0 || mProgressIndeterminate) { 2447 contentView.setProgressBar( 2448 R.id.progress, mProgressMax, mProgress, mProgressIndeterminate); 2449 contentView.setViewVisibility(R.id.progress, View.VISIBLE); 2450 showLine2 = true; 2451 } else { 2452 contentView.setViewVisibility(R.id.progress, View.GONE); 2453 } 2454 } 2455 if (showLine2) { 2456 if (fitIn1U) { 2457 // need to shrink all the type to make sure everything fits 2458 final Resources res = mContext.getResources(); 2459 final float subTextSize = res.getDimensionPixelSize( 2460 R.dimen.notification_subtext_size); 2461 contentView.setTextViewTextSize(R.id.text, TypedValue.COMPLEX_UNIT_PX, subTextSize); 2462 } 2463 // vertical centering 2464 contentView.setViewPadding(R.id.line1, 0, 0, 0, 0); 2465 } 2466 2467 if (mWhen != 0 && mShowWhen) { 2468 if (mUseChronometer) { 2469 contentView.setViewVisibility(R.id.chronometer, View.VISIBLE); 2470 contentView.setLong(R.id.chronometer, "setBase", 2471 mWhen + (SystemClock.elapsedRealtime() - System.currentTimeMillis())); 2472 contentView.setBoolean(R.id.chronometer, "setStarted", true); 2473 } else { 2474 contentView.setViewVisibility(R.id.time, View.VISIBLE); 2475 contentView.setLong(R.id.time, "setTime", mWhen); 2476 } 2477 } else { 2478 contentView.setViewVisibility(R.id.time, View.GONE); 2479 } 2480 2481 contentView.setViewVisibility(R.id.line3, showLine3 ? View.VISIBLE : View.GONE); 2482 contentView.setViewVisibility(R.id.overflow_divider, showLine3 ? View.VISIBLE : View.GONE); 2483 return contentView; 2484 } 2485 2486 private RemoteViews applyStandardTemplateWithActions(int layoutId) { 2487 RemoteViews big = applyStandardTemplate(layoutId, false); 2488 2489 int N = mActions.size(); 2490 if (N > 0) { 2491 big.setViewVisibility(R.id.actions, View.VISIBLE); 2492 big.setViewVisibility(R.id.action_divider, View.VISIBLE); 2493 if (N>MAX_ACTION_BUTTONS) N=MAX_ACTION_BUTTONS; 2494 big.removeAllViews(R.id.actions); 2495 for (int i=0; i<N; i++) { 2496 final RemoteViews button = generateActionButton(mActions.get(i)); 2497 big.addView(R.id.actions, button); 2498 } 2499 } 2500 return big; 2501 } 2502 2503 private RemoteViews makeContentView() { 2504 if (mContentView != null) { 2505 return mContentView; 2506 } else { 2507 return applyStandardTemplate(getBaseLayoutResource(), true); // no more special large_icon flavor 2508 } 2509 } 2510 2511 private RemoteViews makeTickerView() { 2512 if (mTickerView != null) { 2513 return mTickerView; 2514 } else { 2515 if (mContentView == null) { 2516 return applyStandardTemplate(mLargeIcon == null 2517 ? R.layout.status_bar_latest_event_ticker 2518 : R.layout.status_bar_latest_event_ticker_large_icon, true); 2519 } else { 2520 return null; 2521 } 2522 } 2523 } 2524 2525 private RemoteViews makeBigContentView() { 2526 if (mActions.size() == 0) return null; 2527 2528 return applyStandardTemplateWithActions(getBigBaseLayoutResource()); 2529 } 2530 2531 private RemoteViews makeHeadsUpContentView() { 2532 if (mActions.size() == 0) return null; 2533 2534 return applyStandardTemplateWithActions(getBigBaseLayoutResource()); 2535 } 2536 2537 2538 private RemoteViews generateActionButton(Action action) { 2539 final boolean tombstone = (action.actionIntent == null); 2540 RemoteViews button = new RemoteViews(mContext.getPackageName(), 2541 tombstone ? getActionTombstoneLayoutResource() 2542 : getActionLayoutResource()); 2543 button.setTextViewCompoundDrawablesRelative(R.id.action0, action.icon, 0, 0, 0); 2544 button.setTextViewText(R.id.action0, processLegacyText(action.title)); 2545 if (!tombstone) { 2546 button.setOnClickPendingIntent(R.id.action0, action.actionIntent); 2547 } 2548 button.setContentDescription(R.id.action0, action.title); 2549 processLegacyAction(action, button); 2550 return button; 2551 } 2552 2553 /** 2554 * @return Whether we are currently building a notification from a legacy (an app that 2555 * doesn't create material notifications by itself) app. 2556 */ 2557 private boolean isLegacy() { 2558 return mColorUtil != null; 2559 } 2560 2561 private void processLegacyAction(Action action, RemoteViews button) { 2562 if (isLegacy()) { 2563 if (mColorUtil.isGrayscale(mContext, action.icon)) { 2564 button.setTextViewCompoundDrawablesRelativeColorFilter(R.id.action0, 0, 2565 mContext.getResources().getColor( 2566 R.color.notification_action_legacy_color_filter), 2567 PorterDuff.Mode.MULTIPLY); 2568 } 2569 } 2570 } 2571 2572 private CharSequence processLegacyText(CharSequence charSequence) { 2573 if (isLegacy()) { 2574 return mColorUtil.invertCharSequenceColors(charSequence); 2575 } else { 2576 return charSequence; 2577 } 2578 } 2579 2580 /** 2581 * Apply any necessary background to smallIcons being used in the largeIcon spot. 2582 */ 2583 private void processSmallIconAsLarge(int largeIconId, RemoteViews contentView) { 2584 if (!isLegacy() || mColorUtil.isGrayscale(mContext, largeIconId)) { 2585 applyLargeIconBackground(contentView); 2586 } 2587 } 2588 2589 /** 2590 * Apply any necessary background to a largeIcon if it's a fake smallIcon (that is, 2591 * if it's grayscale). 2592 */ 2593 // TODO: also check bounds, transparency, that sort of thing. 2594 private void processLargeIcon(Bitmap largeIcon, RemoteViews contentView) { 2595 if (!isLegacy() || mColorUtil.isGrayscale(largeIcon)) { 2596 applyLargeIconBackground(contentView); 2597 } else { 2598 removeLargeIconBackground(contentView); 2599 } 2600 } 2601 2602 /** 2603 * Add a colored circle behind the largeIcon slot. 2604 */ 2605 private void applyLargeIconBackground(RemoteViews contentView) { 2606 contentView.setInt(R.id.icon, "setBackgroundResource", 2607 R.drawable.notification_icon_legacy_bg_inset); 2608 2609 contentView.setDrawableParameters( 2610 R.id.icon, 2611 true, 2612 -1, 2613 resolveColor(), 2614 PorterDuff.Mode.SRC_ATOP, 2615 -1); 2616 } 2617 2618 private void removeLargeIconBackground(RemoteViews contentView) { 2619 contentView.setInt(R.id.icon, "setBackgroundResource", 0); 2620 } 2621 2622 /** 2623 * Recolor small icons when used in the R.id.right_icon slot. 2624 */ 2625 private void processSmallRightIcon(int smallIconDrawableId, 2626 RemoteViews contentView) { 2627 if (!isLegacy() || mColorUtil.isGrayscale(mContext, smallIconDrawableId)) { 2628 contentView.setDrawableParameters(R.id.right_icon, false, -1, 2629 0xFFFFFFFF, 2630 PorterDuff.Mode.SRC_ATOP, -1); 2631 2632 contentView.setInt(R.id.right_icon, 2633 "setBackgroundResource", 2634 R.drawable.notification_icon_legacy_bg); 2635 2636 contentView.setDrawableParameters( 2637 R.id.right_icon, 2638 true, 2639 -1, 2640 resolveColor(), 2641 PorterDuff.Mode.SRC_ATOP, 2642 -1); 2643 } 2644 } 2645 2646 private int sanitizeColor() { 2647 if (mColor != COLOR_DEFAULT) { 2648 mColor |= 0xFF000000; // no alpha for custom colors 2649 } 2650 return mColor; 2651 } 2652 2653 private int resolveColor() { 2654 if (mColor == COLOR_DEFAULT) { 2655 return mContext.getResources().getColor(R.color.notification_icon_bg_color); 2656 } 2657 return mColor; 2658 } 2659 2660 /** 2661 * Apply the unstyled operations and return a new {@link Notification} object. 2662 * @hide 2663 */ 2664 public Notification buildUnstyled() { 2665 Notification n = new Notification(); 2666 n.when = mWhen; 2667 n.icon = mSmallIcon; 2668 n.iconLevel = mSmallIconLevel; 2669 n.number = mNumber; 2670 2671 n.color = sanitizeColor(); 2672 2673 n.contentView = makeContentView(); 2674 n.contentIntent = mContentIntent; 2675 n.deleteIntent = mDeleteIntent; 2676 n.fullScreenIntent = mFullScreenIntent; 2677 n.tickerText = mTickerText; 2678 n.tickerView = makeTickerView(); 2679 n.largeIcon = mLargeIcon; 2680 n.sound = mSound; 2681 n.audioStreamType = mAudioStreamType; 2682 n.vibrate = mVibrate; 2683 n.ledARGB = mLedArgb; 2684 n.ledOnMS = mLedOnMs; 2685 n.ledOffMS = mLedOffMs; 2686 n.defaults = mDefaults; 2687 n.flags = mFlags; 2688 n.bigContentView = makeBigContentView(); 2689 n.headsUpContentView = makeHeadsUpContentView(); 2690 if (mLedOnMs != 0 || mLedOffMs != 0) { 2691 n.flags |= FLAG_SHOW_LIGHTS; 2692 } 2693 if ((mDefaults & DEFAULT_LIGHTS) != 0) { 2694 n.flags |= FLAG_SHOW_LIGHTS; 2695 } 2696 n.category = mCategory; 2697 n.mGroupKey = mGroupKey; 2698 n.mSortKey = mSortKey; 2699 n.priority = mPriority; 2700 if (mActions.size() > 0) { 2701 n.actions = new Action[mActions.size()]; 2702 mActions.toArray(n.actions); 2703 } 2704 n.visibility = mVisibility; 2705 2706 if (mPublicVersion != null) { 2707 n.publicVersion = new Notification(); 2708 mPublicVersion.cloneInto(n.publicVersion, true); 2709 } 2710 2711 return n; 2712 } 2713 2714 /** 2715 * Capture, in the provided bundle, semantic information used in the construction of 2716 * this Notification object. 2717 * @hide 2718 */ 2719 public void populateExtras(Bundle extras) { 2720 // Store original information used in the construction of this object 2721 extras.putCharSequence(EXTRA_TITLE, mContentTitle); 2722 extras.putCharSequence(EXTRA_TEXT, mContentText); 2723 extras.putCharSequence(EXTRA_SUB_TEXT, mSubText); 2724 extras.putCharSequence(EXTRA_INFO_TEXT, mContentInfo); 2725 extras.putInt(EXTRA_SMALL_ICON, mSmallIcon); 2726 extras.putInt(EXTRA_PROGRESS, mProgress); 2727 extras.putInt(EXTRA_PROGRESS_MAX, mProgressMax); 2728 extras.putBoolean(EXTRA_PROGRESS_INDETERMINATE, mProgressIndeterminate); 2729 extras.putBoolean(EXTRA_SHOW_CHRONOMETER, mUseChronometer); 2730 extras.putBoolean(EXTRA_SHOW_WHEN, mShowWhen); 2731 if (mLargeIcon != null) { 2732 extras.putParcelable(EXTRA_LARGE_ICON, mLargeIcon); 2733 } 2734 if (!mPeople.isEmpty()) { 2735 extras.putStringArray(EXTRA_PEOPLE, mPeople.toArray(new String[mPeople.size()])); 2736 } 2737 } 2738 2739 /** 2740 * @deprecated Use {@link #build()} instead. 2741 */ 2742 @Deprecated 2743 public Notification getNotification() { 2744 return build(); 2745 } 2746 2747 /** 2748 * Combine all of the options that have been set and return a new {@link Notification} 2749 * object. 2750 */ 2751 public Notification build() { 2752 Notification n = buildUnstyled(); 2753 2754 if (mStyle != null) { 2755 n = mStyle.buildStyled(n); 2756 } 2757 2758 n.extras = mExtras != null ? new Bundle(mExtras) : new Bundle(); 2759 2760 populateExtras(n.extras); 2761 if (mStyle != null) { 2762 mStyle.addExtras(n.extras); 2763 } 2764 2765 return n; 2766 } 2767 2768 /** 2769 * Apply this Builder to an existing {@link Notification} object. 2770 * 2771 * @hide 2772 */ 2773 public Notification buildInto(Notification n) { 2774 build().cloneInto(n, true); 2775 return n; 2776 } 2777 2778 2779 private int getBaseLayoutResource() { 2780 return R.layout.notification_template_material_base; 2781 } 2782 2783 private int getBigBaseLayoutResource() { 2784 return R.layout.notification_template_material_big_base; 2785 } 2786 2787 private int getBigPictureLayoutResource() { 2788 return R.layout.notification_template_material_big_picture; 2789 } 2790 2791 private int getBigTextLayoutResource() { 2792 return R.layout.notification_template_material_big_text; 2793 } 2794 2795 private int getInboxLayoutResource() { 2796 return R.layout.notification_template_material_inbox; 2797 } 2798 2799 private int getActionLayoutResource() { 2800 return R.layout.notification_material_action; 2801 } 2802 2803 private int getActionTombstoneLayoutResource() { 2804 return R.layout.notification_material_action_tombstone; 2805 } 2806 } 2807 2808 /** 2809 * An object that can apply a rich notification style to a {@link Notification.Builder} 2810 * object. 2811 */ 2812 public static abstract class Style { 2813 private CharSequence mBigContentTitle; 2814 private CharSequence mSummaryText = null; 2815 private boolean mSummaryTextSet = false; 2816 2817 protected Builder mBuilder; 2818 2819 /** 2820 * Overrides ContentTitle in the big form of the template. 2821 * This defaults to the value passed to setContentTitle(). 2822 */ 2823 protected void internalSetBigContentTitle(CharSequence title) { 2824 mBigContentTitle = title; 2825 } 2826 2827 /** 2828 * Set the first line of text after the detail section in the big form of the template. 2829 */ 2830 protected void internalSetSummaryText(CharSequence cs) { 2831 mSummaryText = cs; 2832 mSummaryTextSet = true; 2833 } 2834 2835 public void setBuilder(Builder builder) { 2836 if (mBuilder != builder) { 2837 mBuilder = builder; 2838 if (mBuilder != null) { 2839 mBuilder.setStyle(this); 2840 } 2841 } 2842 } 2843 2844 protected void checkBuilder() { 2845 if (mBuilder == null) { 2846 throw new IllegalArgumentException("Style requires a valid Builder object"); 2847 } 2848 } 2849 2850 protected RemoteViews getStandardView(int layoutId) { 2851 checkBuilder(); 2852 2853 if (mBigContentTitle != null) { 2854 mBuilder.setContentTitle(mBigContentTitle); 2855 } 2856 2857 RemoteViews contentView = mBuilder.applyStandardTemplateWithActions(layoutId); 2858 2859 if (mBigContentTitle != null && mBigContentTitle.equals("")) { 2860 contentView.setViewVisibility(R.id.line1, View.GONE); 2861 } else { 2862 contentView.setViewVisibility(R.id.line1, View.VISIBLE); 2863 } 2864 2865 // The last line defaults to the subtext, but can be replaced by mSummaryText 2866 final CharSequence overflowText = 2867 mSummaryTextSet ? mSummaryText 2868 : mBuilder.mSubText; 2869 if (overflowText != null) { 2870 contentView.setTextViewText(R.id.text, mBuilder.processLegacyText(overflowText)); 2871 contentView.setViewVisibility(R.id.overflow_divider, View.VISIBLE); 2872 contentView.setViewVisibility(R.id.line3, View.VISIBLE); 2873 } else { 2874 contentView.setViewVisibility(R.id.overflow_divider, View.GONE); 2875 contentView.setViewVisibility(R.id.line3, View.GONE); 2876 } 2877 2878 return contentView; 2879 } 2880 2881 /** 2882 * @hide 2883 */ 2884 public void addExtras(Bundle extras) { 2885 if (mSummaryTextSet) { 2886 extras.putCharSequence(EXTRA_SUMMARY_TEXT, mSummaryText); 2887 } 2888 if (mBigContentTitle != null) { 2889 extras.putCharSequence(EXTRA_TITLE_BIG, mBigContentTitle); 2890 } 2891 extras.putString(EXTRA_TEMPLATE, this.getClass().getName()); 2892 } 2893 2894 /** 2895 * @hide 2896 */ 2897 public abstract Notification buildStyled(Notification wip); 2898 2899 /** 2900 * Calls {@link android.app.Notification.Builder#build()} on the Builder this Style is 2901 * attached to. 2902 * 2903 * @return the fully constructed Notification. 2904 */ 2905 public Notification build() { 2906 checkBuilder(); 2907 return mBuilder.build(); 2908 } 2909 } 2910 2911 /** 2912 * Helper class for generating large-format notifications that include a large image attachment. 2913 * 2914 * Here's how you'd set the <code>BigPictureStyle</code> on a notification: 2915 * <pre class="prettyprint"> 2916 * Notification notif = new Notification.Builder(mContext) 2917 * .setContentTitle("New photo from " + sender.toString()) 2918 * .setContentText(subject) 2919 * .setSmallIcon(R.drawable.new_post) 2920 * .setLargeIcon(aBitmap) 2921 * .setStyle(new Notification.BigPictureStyle() 2922 * .bigPicture(aBigBitmap)) 2923 * .build(); 2924 * </pre> 2925 * 2926 * @see Notification#bigContentView 2927 */ 2928 public static class BigPictureStyle extends Style { 2929 private Bitmap mPicture; 2930 private Bitmap mBigLargeIcon; 2931 private boolean mBigLargeIconSet = false; 2932 2933 public BigPictureStyle() { 2934 } 2935 2936 public BigPictureStyle(Builder builder) { 2937 setBuilder(builder); 2938 } 2939 2940 /** 2941 * Overrides ContentTitle in the big form of the template. 2942 * This defaults to the value passed to setContentTitle(). 2943 */ 2944 public BigPictureStyle setBigContentTitle(CharSequence title) { 2945 internalSetBigContentTitle(safeCharSequence(title)); 2946 return this; 2947 } 2948 2949 /** 2950 * Set the first line of text after the detail section in the big form of the template. 2951 */ 2952 public BigPictureStyle setSummaryText(CharSequence cs) { 2953 internalSetSummaryText(safeCharSequence(cs)); 2954 return this; 2955 } 2956 2957 /** 2958 * Provide the bitmap to be used as the payload for the BigPicture notification. 2959 */ 2960 public BigPictureStyle bigPicture(Bitmap b) { 2961 mPicture = b; 2962 return this; 2963 } 2964 2965 /** 2966 * Override the large icon when the big notification is shown. 2967 */ 2968 public BigPictureStyle bigLargeIcon(Bitmap b) { 2969 mBigLargeIconSet = true; 2970 mBigLargeIcon = b; 2971 return this; 2972 } 2973 2974 private RemoteViews makeBigContentView() { 2975 RemoteViews contentView = getStandardView(mBuilder.getBigPictureLayoutResource()); 2976 2977 contentView.setImageViewBitmap(R.id.big_picture, mPicture); 2978 2979 return contentView; 2980 } 2981 2982 /** 2983 * @hide 2984 */ 2985 public void addExtras(Bundle extras) { 2986 super.addExtras(extras); 2987 2988 if (mBigLargeIconSet) { 2989 extras.putParcelable(EXTRA_LARGE_ICON_BIG, mBigLargeIcon); 2990 } 2991 extras.putParcelable(EXTRA_PICTURE, mPicture); 2992 } 2993 2994 /** 2995 * @hide 2996 */ 2997 @Override 2998 public Notification buildStyled(Notification wip) { 2999 if (mBigLargeIconSet ) { 3000 mBuilder.mLargeIcon = mBigLargeIcon; 3001 } 3002 wip.bigContentView = makeBigContentView(); 3003 return wip; 3004 } 3005 } 3006 3007 /** 3008 * Helper class for generating large-format notifications that include a lot of text. 3009 * 3010 * Here's how you'd set the <code>BigTextStyle</code> on a notification: 3011 * <pre class="prettyprint"> 3012 * Notification notif = new Notification.Builder(mContext) 3013 * .setContentTitle("New mail from " + sender.toString()) 3014 * .setContentText(subject) 3015 * .setSmallIcon(R.drawable.new_mail) 3016 * .setLargeIcon(aBitmap) 3017 * .setStyle(new Notification.BigTextStyle() 3018 * .bigText(aVeryLongString)) 3019 * .build(); 3020 * </pre> 3021 * 3022 * @see Notification#bigContentView 3023 */ 3024 public static class BigTextStyle extends Style { 3025 private CharSequence mBigText; 3026 3027 public BigTextStyle() { 3028 } 3029 3030 public BigTextStyle(Builder builder) { 3031 setBuilder(builder); 3032 } 3033 3034 /** 3035 * Overrides ContentTitle in the big form of the template. 3036 * This defaults to the value passed to setContentTitle(). 3037 */ 3038 public BigTextStyle setBigContentTitle(CharSequence title) { 3039 internalSetBigContentTitle(safeCharSequence(title)); 3040 return this; 3041 } 3042 3043 /** 3044 * Set the first line of text after the detail section in the big form of the template. 3045 */ 3046 public BigTextStyle setSummaryText(CharSequence cs) { 3047 internalSetSummaryText(safeCharSequence(cs)); 3048 return this; 3049 } 3050 3051 /** 3052 * Provide the longer text to be displayed in the big form of the 3053 * template in place of the content text. 3054 */ 3055 public BigTextStyle bigText(CharSequence cs) { 3056 mBigText = safeCharSequence(cs); 3057 return this; 3058 } 3059 3060 /** 3061 * @hide 3062 */ 3063 public void addExtras(Bundle extras) { 3064 super.addExtras(extras); 3065 3066 extras.putCharSequence(EXTRA_TEXT, mBigText); 3067 } 3068 3069 private RemoteViews makeBigContentView() { 3070 // Remove the content text so line3 only shows if you have a summary 3071 final boolean hadThreeLines = (mBuilder.mContentText != null && mBuilder.mSubText != null); 3072 mBuilder.mContentText = null; 3073 3074 RemoteViews contentView = getStandardView(mBuilder.getBigTextLayoutResource()); 3075 3076 if (hadThreeLines) { 3077 // vertical centering 3078 contentView.setViewPadding(R.id.line1, 0, 0, 0, 0); 3079 } 3080 3081 contentView.setTextViewText(R.id.big_text, mBuilder.processLegacyText(mBigText)); 3082 contentView.setViewVisibility(R.id.big_text, View.VISIBLE); 3083 contentView.setViewVisibility(R.id.text2, View.GONE); 3084 3085 return contentView; 3086 } 3087 3088 /** 3089 * @hide 3090 */ 3091 @Override 3092 public Notification buildStyled(Notification wip) { 3093 wip.bigContentView = makeBigContentView(); 3094 3095 wip.extras.putCharSequence(EXTRA_TEXT, mBigText); 3096 3097 return wip; 3098 } 3099 } 3100 3101 /** 3102 * Helper class for generating large-format notifications that include a list of (up to 5) strings. 3103 * 3104 * Here's how you'd set the <code>InboxStyle</code> on a notification: 3105 * <pre class="prettyprint"> 3106 * Notification notif = new Notification.Builder(mContext) 3107 * .setContentTitle("5 New mails from " + sender.toString()) 3108 * .setContentText(subject) 3109 * .setSmallIcon(R.drawable.new_mail) 3110 * .setLargeIcon(aBitmap) 3111 * .setStyle(new Notification.InboxStyle() 3112 * .addLine(str1) 3113 * .addLine(str2) 3114 * .setContentTitle("") 3115 * .setSummaryText("+3 more")) 3116 * .build(); 3117 * </pre> 3118 * 3119 * @see Notification#bigContentView 3120 */ 3121 public static class InboxStyle extends Style { 3122 private ArrayList<CharSequence> mTexts = new ArrayList<CharSequence>(5); 3123 3124 public InboxStyle() { 3125 } 3126 3127 public InboxStyle(Builder builder) { 3128 setBuilder(builder); 3129 } 3130 3131 /** 3132 * Overrides ContentTitle in the big form of the template. 3133 * This defaults to the value passed to setContentTitle(). 3134 */ 3135 public InboxStyle setBigContentTitle(CharSequence title) { 3136 internalSetBigContentTitle(safeCharSequence(title)); 3137 return this; 3138 } 3139 3140 /** 3141 * Set the first line of text after the detail section in the big form of the template. 3142 */ 3143 public InboxStyle setSummaryText(CharSequence cs) { 3144 internalSetSummaryText(safeCharSequence(cs)); 3145 return this; 3146 } 3147 3148 /** 3149 * Append a line to the digest section of the Inbox notification. 3150 */ 3151 public InboxStyle addLine(CharSequence cs) { 3152 mTexts.add(safeCharSequence(cs)); 3153 return this; 3154 } 3155 3156 /** 3157 * @hide 3158 */ 3159 public void addExtras(Bundle extras) { 3160 super.addExtras(extras); 3161 CharSequence[] a = new CharSequence[mTexts.size()]; 3162 extras.putCharSequenceArray(EXTRA_TEXT_LINES, mTexts.toArray(a)); 3163 } 3164 3165 private RemoteViews makeBigContentView() { 3166 // Remove the content text so line3 disappears unless you have a summary 3167 mBuilder.mContentText = null; 3168 RemoteViews contentView = getStandardView(mBuilder.getInboxLayoutResource()); 3169 3170 contentView.setViewVisibility(R.id.text2, View.GONE); 3171 3172 int[] rowIds = {R.id.inbox_text0, R.id.inbox_text1, R.id.inbox_text2, R.id.inbox_text3, 3173 R.id.inbox_text4, R.id.inbox_text5, R.id.inbox_text6}; 3174 3175 // Make sure all rows are gone in case we reuse a view. 3176 for (int rowId : rowIds) { 3177 contentView.setViewVisibility(rowId, View.GONE); 3178 } 3179 3180 3181 int i=0; 3182 while (i < mTexts.size() && i < rowIds.length) { 3183 CharSequence str = mTexts.get(i); 3184 if (str != null && !str.equals("")) { 3185 contentView.setViewVisibility(rowIds[i], View.VISIBLE); 3186 contentView.setTextViewText(rowIds[i], mBuilder.processLegacyText(str)); 3187 } 3188 i++; 3189 } 3190 3191 contentView.setViewVisibility(R.id.inbox_end_pad, 3192 mTexts.size() > 0 ? View.VISIBLE : View.GONE); 3193 3194 contentView.setViewVisibility(R.id.inbox_more, 3195 mTexts.size() > rowIds.length ? View.VISIBLE : View.GONE); 3196 3197 return contentView; 3198 } 3199 3200 /** 3201 * @hide 3202 */ 3203 @Override 3204 public Notification buildStyled(Notification wip) { 3205 wip.bigContentView = makeBigContentView(); 3206 3207 return wip; 3208 } 3209 } 3210 3211 /** 3212 * Notification style for media playback notifications. 3213 * 3214 * In the expanded form, {@link Notification#bigContentView}, up to 5 3215 * {@link Notification.Action}s specified with 3216 * {@link Notification.Builder#addAction(int, CharSequence, PendingIntent) addAction} will be 3217 * shown as icon-only pushbuttons, suitable for transport controls. The Bitmap given to 3218 * {@link Notification.Builder#setLargeIcon(android.graphics.Bitmap) setLargeIcon()} will be 3219 * treated as album artwork. 3220 * 3221 * Unlike the other styles provided here, MediaStyle can also modify the standard-size 3222 * {@link Notification#contentView}; by providing action indices to 3223 * {@link #setShowActionsInCompactView(int...)} you can promote up to 2 actions to be displayed 3224 * in the standard view alongside the usual content. 3225 * 3226 * Finally, if you attach a {@link android.media.session.MediaSession.Token} using 3227 * {@link android.app.Notification.MediaStyle#setMediaSession(MediaSession.Token)}, 3228 * the System UI can identify this as a notification representing an active media session 3229 * and respond accordingly (by showing album artwork in the lockscreen, for example). 3230 * 3231 * To use this style with your Notification, feed it to 3232 * {@link Notification.Builder#setStyle(android.app.Notification.Style)} like so: 3233 * <pre class="prettyprint"> 3234 * Notification noti = new Notification.Builder() 3235 * .setSmallIcon(R.drawable.ic_stat_player) 3236 * .setContentTitle("Track title") // these three lines are optional 3237 * .setContentText("Artist - Album") // if you use 3238 * .setLargeIcon(albumArtBitmap)) // setMediaSession(token, true) 3239 * .setMediaSession(mySession, true) 3240 * .setStyle(<b>new Notification.MediaStyle()</b>) 3241 * .build(); 3242 * </pre> 3243 * 3244 * @see Notification#bigContentView 3245 */ 3246 public static class MediaStyle extends Style { 3247 static final int MAX_MEDIA_BUTTONS_IN_COMPACT = 2; 3248 static final int MAX_MEDIA_BUTTONS = 5; 3249 3250 private int[] mActionsToShowInCompact = null; 3251 private MediaSession.Token mToken; 3252 3253 public MediaStyle() { 3254 } 3255 3256 public MediaStyle(Builder builder) { 3257 setBuilder(builder); 3258 } 3259 3260 /** 3261 * Request up to 2 actions (by index in the order of addition) to be shown in the compact 3262 * notification view. 3263 */ 3264 public MediaStyle setShowActionsInCompactView(int...actions) { 3265 mActionsToShowInCompact = actions; 3266 return this; 3267 } 3268 3269 /** 3270 * Attach a {@link android.media.session.MediaSession.Token} to this Notification 3271 * to provide additional playback information and control to the SystemUI. 3272 */ 3273 public MediaStyle setMediaSession(MediaSession.Token token) { 3274 mToken = token; 3275 return this; 3276 } 3277 3278 @Override 3279 public Notification buildStyled(Notification wip) { 3280 wip.contentView = makeMediaContentView(); 3281 wip.bigContentView = makeMediaBigContentView(); 3282 3283 return wip; 3284 } 3285 3286 /** @hide */ 3287 @Override 3288 public void addExtras(Bundle extras) { 3289 super.addExtras(extras); 3290 3291 if (mToken != null) { 3292 extras.putParcelable(EXTRA_MEDIA_SESSION, mToken); 3293 } 3294 } 3295 3296 private RemoteViews generateMediaActionButton(Action action) { 3297 final boolean tombstone = (action.actionIntent == null); 3298 RemoteViews button = new RemoteViews(mBuilder.mContext.getPackageName(), 3299 R.layout.notification_material_media_action); 3300 button.setImageViewResource(R.id.action0, action.icon); 3301 if (!tombstone) { 3302 button.setOnClickPendingIntent(R.id.action0, action.actionIntent); 3303 } 3304 button.setContentDescription(R.id.action0, action.title); 3305 return button; 3306 } 3307 3308 private RemoteViews makeMediaContentView() { 3309 RemoteViews view = mBuilder.applyStandardTemplate( 3310 R.layout.notification_template_material_media, true /* 1U */); 3311 3312 final int numActions = mBuilder.mActions.size(); 3313 final int N = mActionsToShowInCompact == null 3314 ? 0 3315 : Math.min(mActionsToShowInCompact.length, MAX_MEDIA_BUTTONS_IN_COMPACT); 3316 if (N > 0) { 3317 view.removeAllViews(R.id.actions); 3318 for (int i = 0; i < N; i++) { 3319 if (i >= numActions) { 3320 throw new IllegalArgumentException(String.format( 3321 "setShowActionsInCompactView: action %d out of bounds (max %d)", 3322 i, numActions - 1)); 3323 } 3324 3325 final Action action = mBuilder.mActions.get(mActionsToShowInCompact[i]); 3326 final RemoteViews button = generateMediaActionButton(action); 3327 view.addView(R.id.actions, button); 3328 } 3329 } 3330 return view; 3331 } 3332 3333 private RemoteViews makeMediaBigContentView() { 3334 RemoteViews big = mBuilder.applyStandardTemplate( 3335 R.layout.notification_template_material_big_media, false); 3336 3337 final int N = Math.min(mBuilder.mActions.size(), MAX_MEDIA_BUTTONS); 3338 if (N > 0) { 3339 big.removeAllViews(R.id.actions); 3340 for (int i=0; i<N; i++) { 3341 final RemoteViews button = generateMediaActionButton(mBuilder.mActions.get(i)); 3342 big.addView(R.id.actions, button); 3343 } 3344 } 3345 return big; 3346 } 3347 } 3348 3349 /** 3350 * Extender interface for use with {@link Builder#extend}. Extenders may be used to add 3351 * metadata or change options on a notification builder. 3352 */ 3353 public interface Extender { 3354 /** 3355 * Apply this extender to a notification builder. 3356 * @param builder the builder to be modified. 3357 * @return the build object for chaining. 3358 */ 3359 public Builder extend(Builder builder); 3360 } 3361 3362 /** 3363 * Helper class to add wearable extensions to notifications. 3364 * <p class="note"> See 3365 * <a href="{@docRoot}wear/notifications/creating.html">Creating Notifications 3366 * for Android Wear</a> for more information on how to use this class. 3367 * <p> 3368 * To create a notification with wearable extensions: 3369 * <ol> 3370 * <li>Create a {@link android.app.Notification.Builder}, setting any desired 3371 * properties. 3372 * <li>Create a {@link android.app.Notification.WearableExtender}. 3373 * <li>Set wearable-specific properties using the 3374 * {@code add} and {@code set} methods of {@link android.app.Notification.WearableExtender}. 3375 * <li>Call {@link android.app.Notification.Builder#extend} to apply the extensions to a 3376 * notification. 3377 * <li>Post the notification to the notification system with the 3378 * {@code NotificationManager.notify(...)} methods. 3379 * </ol> 3380 * 3381 * <pre class="prettyprint"> 3382 * Notification notif = new Notification.Builder(mContext) 3383 * .setContentTitle("New mail from " + sender.toString()) 3384 * .setContentText(subject) 3385 * .setSmallIcon(R.drawable.new_mail) 3386 * .extend(new Notification.WearableExtender() 3387 * .setContentIcon(R.drawable.new_mail)) 3388 * .build(); 3389 * NotificationManager notificationManger = 3390 * (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 3391 * notificationManger.notify(0, notif);</pre> 3392 * 3393 * <p>Wearable extensions can be accessed on an existing notification by using the 3394 * {@code WearableExtender(Notification)} constructor, 3395 * and then using the {@code get} methods to access values. 3396 * 3397 * <pre class="prettyprint"> 3398 * Notification.WearableExtender wearableExtender = new Notification.WearableExtender( 3399 * notification); 3400 * List<Notification> pages = wearableExtender.getPages();</pre> 3401 */ 3402 public static final class WearableExtender implements Extender { 3403 /** 3404 * Sentinel value for an action index that is unset. 3405 */ 3406 public static final int UNSET_ACTION_INDEX = -1; 3407 3408 /** 3409 * Size value for use with {@link #setCustomSizePreset} to show this notification with 3410 * default sizing. 3411 * <p>For custom display notifications created using {@link #setDisplayIntent}, 3412 * the default is {@link #SIZE_LARGE}. All other notifications size automatically based 3413 * on their content. 3414 */ 3415 public static final int SIZE_DEFAULT = 0; 3416 3417 /** 3418 * Size value for use with {@link #setCustomSizePreset} to show this notification 3419 * with an extra small size. 3420 * <p>This value is only applicable for custom display notifications created using 3421 * {@link #setDisplayIntent}. 3422 */ 3423 public static final int SIZE_XSMALL = 1; 3424 3425 /** 3426 * Size value for use with {@link #setCustomSizePreset} to show this notification 3427 * with a small size. 3428 * <p>This value is only applicable for custom display notifications created using 3429 * {@link #setDisplayIntent}. 3430 */ 3431 public static final int SIZE_SMALL = 2; 3432 3433 /** 3434 * Size value for use with {@link #setCustomSizePreset} to show this notification 3435 * with a medium size. 3436 * <p>This value is only applicable for custom display notifications created using 3437 * {@link #setDisplayIntent}. 3438 */ 3439 public static final int SIZE_MEDIUM = 3; 3440 3441 /** 3442 * Size value for use with {@link #setCustomSizePreset} to show this notification 3443 * with a large size. 3444 * <p>This value is only applicable for custom display notifications created using 3445 * {@link #setDisplayIntent}. 3446 */ 3447 public static final int SIZE_LARGE = 4; 3448 3449 /** 3450 * Size value for use with {@link #setCustomSizePreset} to show this notification 3451 * full screen. 3452 * <p>This value is only applicable for custom display notifications created using 3453 * {@link #setDisplayIntent}. 3454 */ 3455 public static final int SIZE_FULL_SCREEN = 5; 3456 3457 /** Notification extra which contains wearable extensions */ 3458 private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS"; 3459 3460 // Keys within EXTRA_WEARABLE_OPTIONS for wearable options. 3461 private static final String KEY_ACTIONS = "actions"; 3462 private static final String KEY_FLAGS = "flags"; 3463 private static final String KEY_DISPLAY_INTENT = "displayIntent"; 3464 private static final String KEY_PAGES = "pages"; 3465 private static final String KEY_BACKGROUND = "background"; 3466 private static final String KEY_CONTENT_ICON = "contentIcon"; 3467 private static final String KEY_CONTENT_ICON_GRAVITY = "contentIconGravity"; 3468 private static final String KEY_CONTENT_ACTION_INDEX = "contentActionIndex"; 3469 private static final String KEY_CUSTOM_SIZE_PRESET = "customSizePreset"; 3470 private static final String KEY_CUSTOM_CONTENT_HEIGHT = "customContentHeight"; 3471 private static final String KEY_GRAVITY = "gravity"; 3472 3473 // Flags bitwise-ored to mFlags 3474 private static final int FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE = 0x1; 3475 private static final int FLAG_HINT_HIDE_ICON = 1 << 1; 3476 private static final int FLAG_HINT_SHOW_BACKGROUND_ONLY = 1 << 2; 3477 private static final int FLAG_START_SCROLL_BOTTOM = 1 << 3; 3478 3479 // Default value for flags integer 3480 private static final int DEFAULT_FLAGS = FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE; 3481 3482 private static final int DEFAULT_CONTENT_ICON_GRAVITY = Gravity.END; 3483 private static final int DEFAULT_GRAVITY = Gravity.BOTTOM; 3484 3485 private ArrayList<Action> mActions = new ArrayList<Action>(); 3486 private int mFlags = DEFAULT_FLAGS; 3487 private PendingIntent mDisplayIntent; 3488 private ArrayList<Notification> mPages = new ArrayList<Notification>(); 3489 private Bitmap mBackground; 3490 private int mContentIcon; 3491 private int mContentIconGravity = DEFAULT_CONTENT_ICON_GRAVITY; 3492 private int mContentActionIndex = UNSET_ACTION_INDEX; 3493 private int mCustomSizePreset = SIZE_DEFAULT; 3494 private int mCustomContentHeight; 3495 private int mGravity = DEFAULT_GRAVITY; 3496 3497 /** 3498 * Create a {@link android.app.Notification.WearableExtender} with default 3499 * options. 3500 */ 3501 public WearableExtender() { 3502 } 3503 3504 public WearableExtender(Notification notif) { 3505 Bundle wearableBundle = notif.extras.getBundle(EXTRA_WEARABLE_EXTENSIONS); 3506 if (wearableBundle != null) { 3507 List<Action> actions = wearableBundle.getParcelableArrayList(KEY_ACTIONS); 3508 if (actions != null) { 3509 mActions.addAll(actions); 3510 } 3511 3512 mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS); 3513 mDisplayIntent = wearableBundle.getParcelable(KEY_DISPLAY_INTENT); 3514 3515 Notification[] pages = getNotificationArrayFromBundle( 3516 wearableBundle, KEY_PAGES); 3517 if (pages != null) { 3518 Collections.addAll(mPages, pages); 3519 } 3520 3521 mBackground = wearableBundle.getParcelable(KEY_BACKGROUND); 3522 mContentIcon = wearableBundle.getInt(KEY_CONTENT_ICON); 3523 mContentIconGravity = wearableBundle.getInt(KEY_CONTENT_ICON_GRAVITY, 3524 DEFAULT_CONTENT_ICON_GRAVITY); 3525 mContentActionIndex = wearableBundle.getInt(KEY_CONTENT_ACTION_INDEX, 3526 UNSET_ACTION_INDEX); 3527 mCustomSizePreset = wearableBundle.getInt(KEY_CUSTOM_SIZE_PRESET, 3528 SIZE_DEFAULT); 3529 mCustomContentHeight = wearableBundle.getInt(KEY_CUSTOM_CONTENT_HEIGHT); 3530 mGravity = wearableBundle.getInt(KEY_GRAVITY, DEFAULT_GRAVITY); 3531 } 3532 } 3533 3534 /** 3535 * Apply wearable extensions to a notification that is being built. This is typically 3536 * called by the {@link android.app.Notification.Builder#extend} method of 3537 * {@link android.app.Notification.Builder}. 3538 */ 3539 @Override 3540 public Notification.Builder extend(Notification.Builder builder) { 3541 Bundle wearableBundle = new Bundle(); 3542 3543 if (!mActions.isEmpty()) { 3544 wearableBundle.putParcelableArrayList(KEY_ACTIONS, mActions); 3545 } 3546 if (mFlags != DEFAULT_FLAGS) { 3547 wearableBundle.putInt(KEY_FLAGS, mFlags); 3548 } 3549 if (mDisplayIntent != null) { 3550 wearableBundle.putParcelable(KEY_DISPLAY_INTENT, mDisplayIntent); 3551 } 3552 if (!mPages.isEmpty()) { 3553 wearableBundle.putParcelableArray(KEY_PAGES, mPages.toArray( 3554 new Notification[mPages.size()])); 3555 } 3556 if (mBackground != null) { 3557 wearableBundle.putParcelable(KEY_BACKGROUND, mBackground); 3558 } 3559 if (mContentIcon != 0) { 3560 wearableBundle.putInt(KEY_CONTENT_ICON, mContentIcon); 3561 } 3562 if (mContentIconGravity != DEFAULT_CONTENT_ICON_GRAVITY) { 3563 wearableBundle.putInt(KEY_CONTENT_ICON_GRAVITY, mContentIconGravity); 3564 } 3565 if (mContentActionIndex != UNSET_ACTION_INDEX) { 3566 wearableBundle.putInt(KEY_CONTENT_ACTION_INDEX, 3567 mContentActionIndex); 3568 } 3569 if (mCustomSizePreset != SIZE_DEFAULT) { 3570 wearableBundle.putInt(KEY_CUSTOM_SIZE_PRESET, mCustomSizePreset); 3571 } 3572 if (mCustomContentHeight != 0) { 3573 wearableBundle.putInt(KEY_CUSTOM_CONTENT_HEIGHT, mCustomContentHeight); 3574 } 3575 if (mGravity != DEFAULT_GRAVITY) { 3576 wearableBundle.putInt(KEY_GRAVITY, mGravity); 3577 } 3578 3579 builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle); 3580 return builder; 3581 } 3582 3583 @Override 3584 public WearableExtender clone() { 3585 WearableExtender that = new WearableExtender(); 3586 that.mActions = new ArrayList<Action>(this.mActions); 3587 that.mFlags = this.mFlags; 3588 that.mDisplayIntent = this.mDisplayIntent; 3589 that.mPages = new ArrayList<Notification>(this.mPages); 3590 that.mBackground = this.mBackground; 3591 that.mContentIcon = this.mContentIcon; 3592 that.mContentIconGravity = this.mContentIconGravity; 3593 that.mContentActionIndex = this.mContentActionIndex; 3594 that.mCustomSizePreset = this.mCustomSizePreset; 3595 that.mCustomContentHeight = this.mCustomContentHeight; 3596 that.mGravity = this.mGravity; 3597 return that; 3598 } 3599 3600 /** 3601 * Add a wearable action to this notification. 3602 * 3603 * <p>When wearable actions are added using this method, the set of actions that 3604 * show on a wearable device splits from devices that only show actions added 3605 * using {@link android.app.Notification.Builder#addAction}. This allows for customization 3606 * of which actions display on different devices. 3607 * 3608 * @param action the action to add to this notification 3609 * @return this object for method chaining 3610 * @see android.app.Notification.Action 3611 */ 3612 public WearableExtender addAction(Action action) { 3613 mActions.add(action); 3614 return this; 3615 } 3616 3617 /** 3618 * Adds wearable actions to this notification. 3619 * 3620 * <p>When wearable actions are added using this method, the set of actions that 3621 * show on a wearable device splits from devices that only show actions added 3622 * using {@link android.app.Notification.Builder#addAction}. This allows for customization 3623 * of which actions display on different devices. 3624 * 3625 * @param actions the actions to add to this notification 3626 * @return this object for method chaining 3627 * @see android.app.Notification.Action 3628 */ 3629 public WearableExtender addActions(List<Action> actions) { 3630 mActions.addAll(actions); 3631 return this; 3632 } 3633 3634 /** 3635 * Clear all wearable actions present on this builder. 3636 * @return this object for method chaining. 3637 * @see #addAction 3638 */ 3639 public WearableExtender clearActions() { 3640 mActions.clear(); 3641 return this; 3642 } 3643 3644 /** 3645 * Get the wearable actions present on this notification. 3646 */ 3647 public List<Action> getActions() { 3648 return mActions; 3649 } 3650 3651 /** 3652 * Set an intent to launch inside of an activity view when displaying 3653 * this notification. The {@link PendingIntent} provided should be for an activity. 3654 * 3655 * <pre class="prettyprint"> 3656 * Intent displayIntent = new Intent(context, MyDisplayActivity.class); 3657 * PendingIntent displayPendingIntent = PendingIntent.getActivity(context, 3658 * 0, displayIntent, PendingIntent.FLAG_UPDATE_CURRENT); 3659 * Notification notif = new Notification.Builder(context) 3660 * .extend(new Notification.WearableExtender() 3661 * .setDisplayIntent(displayPendingIntent) 3662 * .setCustomSizePreset(Notification.WearableExtender.SIZE_MEDIUM)) 3663 * .build();</pre> 3664 * 3665 * <p>The activity to launch needs to allow embedding, must be exported, and 3666 * should have an empty task affinity. It is also recommended to use the device 3667 * default light theme. 3668 * 3669 * <p>Example AndroidManifest.xml entry: 3670 * <pre class="prettyprint"> 3671 * <activity android:name="com.example.MyDisplayActivity" 3672 * android:exported="true" 3673 * android:allowEmbedded="true" 3674 * android:taskAffinity="" 3675 * android:theme="@android:style/Theme.DeviceDefault.Light" /></pre> 3676 * 3677 * @param intent the {@link PendingIntent} for an activity 3678 * @return this object for method chaining 3679 * @see android.app.Notification.WearableExtender#getDisplayIntent 3680 */ 3681 public WearableExtender setDisplayIntent(PendingIntent intent) { 3682 mDisplayIntent = intent; 3683 return this; 3684 } 3685 3686 /** 3687 * Get the intent to launch inside of an activity view when displaying this 3688 * notification. This {@code PendingIntent} should be for an activity. 3689 */ 3690 public PendingIntent getDisplayIntent() { 3691 return mDisplayIntent; 3692 } 3693 3694 /** 3695 * Add an additional page of content to display with this notification. The current 3696 * notification forms the first page, and pages added using this function form 3697 * subsequent pages. This field can be used to separate a notification into multiple 3698 * sections. 3699 * 3700 * @param page the notification to add as another page 3701 * @return this object for method chaining 3702 * @see android.app.Notification.WearableExtender#getPages 3703 */ 3704 public WearableExtender addPage(Notification page) { 3705 mPages.add(page); 3706 return this; 3707 } 3708 3709 /** 3710 * Add additional pages of content to display with this notification. The current 3711 * notification forms the first page, and pages added using this function form 3712 * subsequent pages. This field can be used to separate a notification into multiple 3713 * sections. 3714 * 3715 * @param pages a list of notifications 3716 * @return this object for method chaining 3717 * @see android.app.Notification.WearableExtender#getPages 3718 */ 3719 public WearableExtender addPages(List<Notification> pages) { 3720 mPages.addAll(pages); 3721 return this; 3722 } 3723 3724 /** 3725 * Clear all additional pages present on this builder. 3726 * @return this object for method chaining. 3727 * @see #addPage 3728 */ 3729 public WearableExtender clearPages() { 3730 mPages.clear(); 3731 return this; 3732 } 3733 3734 /** 3735 * Get the array of additional pages of content for displaying this notification. The 3736 * current notification forms the first page, and elements within this array form 3737 * subsequent pages. This field can be used to separate a notification into multiple 3738 * sections. 3739 * @return the pages for this notification 3740 */ 3741 public List<Notification> getPages() { 3742 return mPages; 3743 } 3744 3745 /** 3746 * Set a background image to be displayed behind the notification content. 3747 * Contrary to the {@link android.app.Notification.BigPictureStyle}, this background 3748 * will work with any notification style. 3749 * 3750 * @param background the background bitmap 3751 * @return this object for method chaining 3752 * @see android.app.Notification.WearableExtender#getBackground 3753 */ 3754 public WearableExtender setBackground(Bitmap background) { 3755 mBackground = background; 3756 return this; 3757 } 3758 3759 /** 3760 * Get a background image to be displayed behind the notification content. 3761 * Contrary to the {@link android.app.Notification.BigPictureStyle}, this background 3762 * will work with any notification style. 3763 * 3764 * @return the background image 3765 * @see android.app.Notification.WearableExtender#setBackground 3766 */ 3767 public Bitmap getBackground() { 3768 return mBackground; 3769 } 3770 3771 /** 3772 * Set an icon that goes with the content of this notification. 3773 */ 3774 public WearableExtender setContentIcon(int icon) { 3775 mContentIcon = icon; 3776 return this; 3777 } 3778 3779 /** 3780 * Get an icon that goes with the content of this notification. 3781 */ 3782 public int getContentIcon() { 3783 return mContentIcon; 3784 } 3785 3786 /** 3787 * Set the gravity that the content icon should have within the notification display. 3788 * Supported values include {@link android.view.Gravity#START} and 3789 * {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}. 3790 * @see #setContentIcon 3791 */ 3792 public WearableExtender setContentIconGravity(int contentIconGravity) { 3793 mContentIconGravity = contentIconGravity; 3794 return this; 3795 } 3796 3797 /** 3798 * Get the gravity that the content icon should have within the notification display. 3799 * Supported values include {@link android.view.Gravity#START} and 3800 * {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}. 3801 * @see #getContentIcon 3802 */ 3803 public int getContentIconGravity() { 3804 return mContentIconGravity; 3805 } 3806 3807 /** 3808 * Set an action from this notification's actions to be clickable with the content of 3809 * this notification. This action will no longer display separately from the 3810 * notification's content. 3811 * 3812 * <p>For notifications with multiple pages, child pages can also have content actions 3813 * set, although the list of available actions comes from the main notification and not 3814 * from the child page's notification. 3815 * 3816 * @param actionIndex The index of the action to hoist onto the current notification page. 3817 * If wearable actions were added to the main notification, this index 3818 * will apply to that list, otherwise it will apply to the regular 3819 * actions list. 3820 */ 3821 public WearableExtender setContentAction(int actionIndex) { 3822 mContentActionIndex = actionIndex; 3823 return this; 3824 } 3825 3826 /** 3827 * Get the index of the notification action, if any, that was specified as being clickable 3828 * with the content of this notification. This action will no longer display separately 3829 * from the notification's content. 3830 * 3831 * <p>For notifications with multiple pages, child pages can also have content actions 3832 * set, although the list of available actions comes from the main notification and not 3833 * from the child page's notification. 3834 * 3835 * <p>If wearable specific actions were added to the main notification, this index will 3836 * apply to that list, otherwise it will apply to the regular actions list. 3837 * 3838 * @return the action index or {@link #UNSET_ACTION_INDEX} if no action was selected. 3839 */ 3840 public int getContentAction() { 3841 return mContentActionIndex; 3842 } 3843 3844 /** 3845 * Set the gravity that this notification should have within the available viewport space. 3846 * Supported values include {@link android.view.Gravity#TOP}, 3847 * {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}. 3848 * The default value is {@link android.view.Gravity#BOTTOM}. 3849 */ 3850 public WearableExtender setGravity(int gravity) { 3851 mGravity = gravity; 3852 return this; 3853 } 3854 3855 /** 3856 * Get the gravity that this notification should have within the available viewport space. 3857 * Supported values include {@link android.view.Gravity#TOP}, 3858 * {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}. 3859 * The default value is {@link android.view.Gravity#BOTTOM}. 3860 */ 3861 public int getGravity() { 3862 return mGravity; 3863 } 3864 3865 /** 3866 * Set the custom size preset for the display of this notification out of the available 3867 * presets found in {@link android.app.Notification.WearableExtender}, e.g. 3868 * {@link #SIZE_LARGE}. 3869 * <p>Some custom size presets are only applicable for custom display notifications created 3870 * using {@link android.app.Notification.WearableExtender#setDisplayIntent}. Check the 3871 * documentation for the preset in question. See also 3872 * {@link #setCustomContentHeight} and {@link #getCustomSizePreset}. 3873 */ 3874 public WearableExtender setCustomSizePreset(int sizePreset) { 3875 mCustomSizePreset = sizePreset; 3876 return this; 3877 } 3878 3879 /** 3880 * Get the custom size preset for the display of this notification out of the available 3881 * presets found in {@link android.app.Notification.WearableExtender}, e.g. 3882 * {@link #SIZE_LARGE}. 3883 * <p>Some custom size presets are only applicable for custom display notifications created 3884 * using {@link #setDisplayIntent}. Check the documentation for the preset in question. 3885 * See also {@link #setCustomContentHeight} and {@link #setCustomSizePreset}. 3886 */ 3887 public int getCustomSizePreset() { 3888 return mCustomSizePreset; 3889 } 3890 3891 /** 3892 * Set the custom height in pixels for the display of this notification's content. 3893 * <p>This option is only available for custom display notifications created 3894 * using {@link android.app.Notification.WearableExtender#setDisplayIntent}. See also 3895 * {@link android.app.Notification.WearableExtender#setCustomSizePreset} and 3896 * {@link #getCustomContentHeight}. 3897 */ 3898 public WearableExtender setCustomContentHeight(int height) { 3899 mCustomContentHeight = height; 3900 return this; 3901 } 3902 3903 /** 3904 * Get the custom height in pixels for the display of this notification's content. 3905 * <p>This option is only available for custom display notifications created 3906 * using {@link #setDisplayIntent}. See also {@link #setCustomSizePreset} and 3907 * {@link #setCustomContentHeight}. 3908 */ 3909 public int getCustomContentHeight() { 3910 return mCustomContentHeight; 3911 } 3912 3913 /** 3914 * Set whether the scrolling position for the contents of this notification should start 3915 * at the bottom of the contents instead of the top when the contents are too long to 3916 * display within the screen. Default is false (start scroll at the top). 3917 */ 3918 public WearableExtender setStartScrollBottom(boolean startScrollBottom) { 3919 setFlag(FLAG_START_SCROLL_BOTTOM, startScrollBottom); 3920 return this; 3921 } 3922 3923 /** 3924 * Get whether the scrolling position for the contents of this notification should start 3925 * at the bottom of the contents instead of the top when the contents are too long to 3926 * display within the screen. Default is false (start scroll at the top). 3927 */ 3928 public boolean getStartScrollBottom() { 3929 return (mFlags & FLAG_START_SCROLL_BOTTOM) != 0; 3930 } 3931 3932 /** 3933 * Set whether the content intent is available when the wearable device is not connected 3934 * to a companion device. The user can still trigger this intent when the wearable device 3935 * is offline, but a visual hint will indicate that the content intent may not be available. 3936 * Defaults to true. 3937 */ 3938 public WearableExtender setContentIntentAvailableOffline( 3939 boolean contentIntentAvailableOffline) { 3940 setFlag(FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE, contentIntentAvailableOffline); 3941 return this; 3942 } 3943 3944 /** 3945 * Get whether the content intent is available when the wearable device is not connected 3946 * to a companion device. The user can still trigger this intent when the wearable device 3947 * is offline, but a visual hint will indicate that the content intent may not be available. 3948 * Defaults to true. 3949 */ 3950 public boolean getContentIntentAvailableOffline() { 3951 return (mFlags & FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE) != 0; 3952 } 3953 3954 /** 3955 * Set a hint that this notification's icon should not be displayed. 3956 * @param hintHideIcon {@code true} to hide the icon, {@code false} otherwise. 3957 * @return this object for method chaining 3958 */ 3959 public WearableExtender setHintHideIcon(boolean hintHideIcon) { 3960 setFlag(FLAG_HINT_HIDE_ICON, hintHideIcon); 3961 return this; 3962 } 3963 3964 /** 3965 * Get a hint that this notification's icon should not be displayed. 3966 * @return {@code true} if this icon should not be displayed, false otherwise. 3967 * The default value is {@code false} if this was never set. 3968 */ 3969 public boolean getHintHideIcon() { 3970 return (mFlags & FLAG_HINT_HIDE_ICON) != 0; 3971 } 3972 3973 /** 3974 * Set a visual hint that only the background image of this notification should be 3975 * displayed, and other semantic content should be hidden. This hint is only applicable 3976 * to sub-pages added using {@link #addPage}. 3977 */ 3978 public WearableExtender setHintShowBackgroundOnly(boolean hintShowBackgroundOnly) { 3979 setFlag(FLAG_HINT_SHOW_BACKGROUND_ONLY, hintShowBackgroundOnly); 3980 return this; 3981 } 3982 3983 /** 3984 * Get a visual hint that only the background image of this notification should be 3985 * displayed, and other semantic content should be hidden. This hint is only applicable 3986 * to sub-pages added using {@link android.app.Notification.WearableExtender#addPage}. 3987 */ 3988 public boolean getHintShowBackgroundOnly() { 3989 return (mFlags & FLAG_HINT_SHOW_BACKGROUND_ONLY) != 0; 3990 } 3991 3992 private void setFlag(int mask, boolean value) { 3993 if (value) { 3994 mFlags |= mask; 3995 } else { 3996 mFlags &= ~mask; 3997 } 3998 } 3999 } 4000 4001 /** 4002 * Get an array of Notification objects from a parcelable array bundle field. 4003 * Update the bundle to have a typed array so fetches in the future don't need 4004 * to do an array copy. 4005 */ 4006 private static Notification[] getNotificationArrayFromBundle(Bundle bundle, String key) { 4007 Parcelable[] array = bundle.getParcelableArray(key); 4008 if (array instanceof Notification[] || array == null) { 4009 return (Notification[]) array; 4010 } 4011 Notification[] typedArray = Arrays.copyOf(array, array.length, 4012 Notification[].class); 4013 bundle.putParcelableArray(key, typedArray); 4014 return typedArray; 4015 } 4016} 4017