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