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