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