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