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