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