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