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