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