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