Notification.java revision ce8794fbbc49baf2777eb9d078890cbf28c890d5
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 static com.android.internal.util.NotificationColorUtil.satisfiesTextContrast; 20 21import android.annotation.ColorInt; 22import android.annotation.DrawableRes; 23import android.annotation.IntDef; 24import android.annotation.NonNull; 25import android.annotation.Nullable; 26import android.annotation.RequiresPermission; 27import android.annotation.SdkConstant; 28import android.annotation.SdkConstant.SdkConstantType; 29import android.annotation.SystemApi; 30import android.content.Context; 31import android.content.Intent; 32import android.content.pm.ApplicationInfo; 33import android.content.pm.PackageManager; 34import android.content.pm.PackageManager.NameNotFoundException; 35import android.content.pm.ShortcutInfo; 36import android.content.res.ColorStateList; 37import android.content.res.Configuration; 38import android.content.res.Resources; 39import android.graphics.Bitmap; 40import android.graphics.Canvas; 41import android.graphics.Color; 42import android.graphics.PorterDuff; 43import android.graphics.drawable.Drawable; 44import android.graphics.drawable.Icon; 45import android.media.AudioAttributes; 46import android.media.AudioManager; 47import android.media.PlayerBase; 48import android.media.session.MediaSession; 49import android.net.Uri; 50import android.os.BadParcelableException; 51import android.os.Build; 52import android.os.Bundle; 53import android.os.IBinder; 54import android.os.Parcel; 55import android.os.Parcelable; 56import android.os.SystemClock; 57import android.os.SystemProperties; 58import android.os.UserHandle; 59import android.text.BidiFormatter; 60import android.text.SpannableStringBuilder; 61import android.text.Spanned; 62import android.text.TextUtils; 63import android.text.style.AbsoluteSizeSpan; 64import android.text.style.CharacterStyle; 65import android.text.style.ForegroundColorSpan; 66import android.text.style.RelativeSizeSpan; 67import android.text.style.TextAppearanceSpan; 68import android.util.ArraySet; 69import android.util.Log; 70import android.util.SparseArray; 71import android.util.proto.ProtoOutputStream; 72import android.view.Gravity; 73import android.view.NotificationHeaderView; 74import android.view.View; 75import android.view.ViewGroup; 76import android.widget.ProgressBar; 77import android.widget.RemoteViews; 78 79import com.android.internal.R; 80import com.android.internal.annotations.VisibleForTesting; 81import com.android.internal.util.ArrayUtils; 82import com.android.internal.util.NotificationColorUtil; 83import com.android.internal.util.Preconditions; 84 85import java.lang.annotation.Retention; 86import java.lang.annotation.RetentionPolicy; 87import java.lang.reflect.Constructor; 88import java.util.ArrayList; 89import java.util.Arrays; 90import java.util.Collections; 91import java.util.List; 92import java.util.Objects; 93import java.util.Set; 94import java.util.function.Consumer; 95 96/** 97 * A class that represents how a persistent notification is to be presented to 98 * the user using the {@link android.app.NotificationManager}. 99 * 100 * <p>The {@link Notification.Builder Notification.Builder} has been added to make it 101 * easier to construct Notifications.</p> 102 * 103 * <div class="special reference"> 104 * <h3>Developer Guides</h3> 105 * <p>For a guide to creating notifications, read the 106 * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a> 107 * developer guide.</p> 108 * </div> 109 */ 110public class Notification implements Parcelable 111{ 112 private static final String TAG = "Notification"; 113 114 /** 115 * An activity that provides a user interface for adjusting notification preferences for its 116 * containing application. 117 */ 118 @SdkConstant(SdkConstantType.INTENT_CATEGORY) 119 public static final String INTENT_CATEGORY_NOTIFICATION_PREFERENCES 120 = "android.intent.category.NOTIFICATION_PREFERENCES"; 121 122 /** 123 * Optional extra for {@link #INTENT_CATEGORY_NOTIFICATION_PREFERENCES}. If provided, will 124 * contain a {@link NotificationChannel#getId() channel id} that can be used to narrow down 125 * what settings should be shown in the target app. 126 */ 127 public static final String EXTRA_CHANNEL_ID = "android.intent.extra.CHANNEL_ID"; 128 129 /** 130 * Optional extra for {@link #INTENT_CATEGORY_NOTIFICATION_PREFERENCES}. If provided, will 131 * contain a {@link NotificationChannelGroup#getId() group id} that can be used to narrow down 132 * what settings should be shown in the target app. 133 */ 134 public static final String EXTRA_CHANNEL_GROUP_ID = "android.intent.extra.CHANNEL_GROUP_ID"; 135 136 /** 137 * Optional extra for {@link #INTENT_CATEGORY_NOTIFICATION_PREFERENCES}. If provided, will 138 * contain the tag provided to {@link NotificationManager#notify(String, int, Notification)} 139 * that can be used to narrow down what settings should be shown in the target app. 140 */ 141 public static final String EXTRA_NOTIFICATION_TAG = "android.intent.extra.NOTIFICATION_TAG"; 142 143 /** 144 * Optional extra for {@link #INTENT_CATEGORY_NOTIFICATION_PREFERENCES}. If provided, will 145 * contain the id provided to {@link NotificationManager#notify(String, int, Notification)} 146 * that can be used to narrow down what settings should be shown in the target app. 147 */ 148 public static final String EXTRA_NOTIFICATION_ID = "android.intent.extra.NOTIFICATION_ID"; 149 150 /** 151 * Use all default values (where applicable). 152 */ 153 public static final int DEFAULT_ALL = ~0; 154 155 /** 156 * Use the default notification sound. This will ignore any given 157 * {@link #sound}. 158 * 159 * <p> 160 * A notification that is noisy is more likely to be presented as a heads-up notification. 161 * </p> 162 * 163 * @see #defaults 164 */ 165 166 public static final int DEFAULT_SOUND = 1; 167 168 /** 169 * Use the default notification vibrate. This will ignore any given 170 * {@link #vibrate}. Using phone vibration requires the 171 * {@link android.Manifest.permission#VIBRATE VIBRATE} permission. 172 * 173 * <p> 174 * A notification that vibrates is more likely to be presented as a heads-up notification. 175 * </p> 176 * 177 * @see #defaults 178 */ 179 180 public static final int DEFAULT_VIBRATE = 2; 181 182 /** 183 * Use the default notification lights. This will ignore the 184 * {@link #FLAG_SHOW_LIGHTS} bit, and {@link #ledARGB}, {@link #ledOffMS}, or 185 * {@link #ledOnMS}. 186 * 187 * @see #defaults 188 */ 189 190 public static final int DEFAULT_LIGHTS = 4; 191 192 /** 193 * Maximum length of CharSequences accepted by Builder and friends. 194 * 195 * <p> 196 * Avoids spamming the system with overly large strings such as full e-mails. 197 */ 198 private static final int MAX_CHARSEQUENCE_LENGTH = 5 * 1024; 199 200 /** 201 * Maximum entries of reply text that are accepted by Builder and friends. 202 */ 203 private static final int MAX_REPLY_HISTORY = 5; 204 205 206 /** 207 * If the notification contained an unsent draft for a RemoteInput when the user clicked on it, 208 * we're adding the draft as a String extra to the {@link #contentIntent} using this key. 209 * 210 * <p>Apps may use this extra to prepopulate text fields in the app, where the user usually 211 * sends messages.</p> 212 */ 213 public static final String EXTRA_REMOTE_INPUT_DRAFT = "android.remoteInputDraft"; 214 215 /** 216 * A timestamp related to this notification, in milliseconds since the epoch. 217 * 218 * Default value: {@link System#currentTimeMillis() Now}. 219 * 220 * Choose a timestamp that will be most relevant to the user. For most finite events, this 221 * corresponds to the time the event happened (or will happen, in the case of events that have 222 * yet to occur but about which the user is being informed). Indefinite events should be 223 * timestamped according to when the activity began. 224 * 225 * Some examples: 226 * 227 * <ul> 228 * <li>Notification of a new chat message should be stamped when the message was received.</li> 229 * <li>Notification of an ongoing file download (with a progress bar, for example) should be stamped when the download started.</li> 230 * <li>Notification of a completed file download should be stamped when the download finished.</li> 231 * <li>Notification of an upcoming meeting should be stamped with the time the meeting will begin (that is, in the future).</li> 232 * <li>Notification of an ongoing stopwatch (increasing timer) should be stamped with the watch's start time. 233 * <li>Notification of an ongoing countdown timer should be stamped with the timer's end time. 234 * </ul> 235 * 236 * For apps targeting {@link android.os.Build.VERSION_CODES#N} and above, this time is not shown 237 * anymore by default and must be opted into by using 238 * {@link android.app.Notification.Builder#setShowWhen(boolean)} 239 */ 240 public long when; 241 242 /** 243 * The creation time of the notification 244 */ 245 private long creationTime; 246 247 /** 248 * The resource id of a drawable to use as the icon in the status bar. 249 * 250 * @deprecated Use {@link Builder#setSmallIcon(Icon)} instead. 251 */ 252 @Deprecated 253 @DrawableRes 254 public int icon; 255 256 /** 257 * If the icon in the status bar is to have more than one level, you can set this. Otherwise, 258 * leave it at its default value of 0. 259 * 260 * @see android.widget.ImageView#setImageLevel 261 * @see android.graphics.drawable.Drawable#setLevel 262 */ 263 public int iconLevel; 264 265 /** 266 * The number of events that this notification represents. For example, in a new mail 267 * notification, this could be the number of unread messages. 268 * 269 * The system may or may not use this field to modify the appearance of the notification. 270 * Starting with {@link android.os.Build.VERSION_CODES#O}, the number may be displayed as a 271 * badge icon in Launchers that support badging. 272 */ 273 public int number = 0; 274 275 /** 276 * The intent to execute when the expanded status entry is clicked. If 277 * this is an activity, it must include the 278 * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires 279 * that you take care of task management as described in the 280 * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back 281 * Stack</a> document. In particular, make sure to read the notification section 282 * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html#HandlingNotifications">Handling 283 * Notifications</a> for the correct ways to launch an application from a 284 * notification. 285 */ 286 public PendingIntent contentIntent; 287 288 /** 289 * The intent to execute when the notification is explicitly dismissed by the user, either with 290 * the "Clear All" button or by swiping it away individually. 291 * 292 * This probably shouldn't be launching an activity since several of those will be sent 293 * at the same time. 294 */ 295 public PendingIntent deleteIntent; 296 297 /** 298 * An intent to launch instead of posting the notification to the status bar. 299 * 300 * <p> 301 * The system UI may choose to display a heads-up notification, instead of 302 * launching this intent, while the user is using the device. 303 * </p> 304 * 305 * @see Notification.Builder#setFullScreenIntent 306 */ 307 public PendingIntent fullScreenIntent; 308 309 /** 310 * Text that summarizes this notification for accessibility services. 311 * 312 * As of the L release, this text is no longer shown on screen, but it is still useful to 313 * accessibility services (where it serves as an audible announcement of the notification's 314 * appearance). 315 * 316 * @see #tickerView 317 */ 318 public CharSequence tickerText; 319 320 /** 321 * Formerly, a view showing the {@link #tickerText}. 322 * 323 * No longer displayed in the status bar as of API 21. 324 */ 325 @Deprecated 326 public RemoteViews tickerView; 327 328 /** 329 * The view that will represent this notification in the notification list (which is pulled 330 * down from the status bar). 331 * 332 * As of N, this field may be null. The notification view is determined by the inputs 333 * to {@link Notification.Builder}; a custom RemoteViews can optionally be 334 * supplied with {@link Notification.Builder#setCustomContentView(RemoteViews)}. 335 */ 336 @Deprecated 337 public RemoteViews contentView; 338 339 /** 340 * A large-format version of {@link #contentView}, giving the Notification an 341 * opportunity to show more detail. The system UI may choose to show this 342 * instead of the normal content view at its discretion. 343 * 344 * As of N, this field may be null. The expanded notification view is determined by the 345 * inputs to {@link Notification.Builder}; a custom RemoteViews can optionally be 346 * supplied with {@link Notification.Builder#setCustomBigContentView(RemoteViews)}. 347 */ 348 @Deprecated 349 public RemoteViews bigContentView; 350 351 352 /** 353 * A medium-format version of {@link #contentView}, providing the Notification an 354 * opportunity to add action buttons to contentView. At its discretion, the system UI may 355 * choose to show this as a heads-up notification, which will pop up so the user can see 356 * it without leaving their current activity. 357 * 358 * As of N, this field may be null. The heads-up notification view is determined by the 359 * inputs to {@link Notification.Builder}; a custom RemoteViews can optionally be 360 * supplied with {@link Notification.Builder#setCustomHeadsUpContentView(RemoteViews)}. 361 */ 362 @Deprecated 363 public RemoteViews headsUpContentView; 364 365 private boolean mUsesStandardHeader; 366 367 private static final ArraySet<Integer> STANDARD_LAYOUTS = new ArraySet<>(); 368 static { 369 STANDARD_LAYOUTS.add(R.layout.notification_template_material_base); 370 STANDARD_LAYOUTS.add(R.layout.notification_template_material_big_base); 371 STANDARD_LAYOUTS.add(R.layout.notification_template_material_big_picture); 372 STANDARD_LAYOUTS.add(R.layout.notification_template_material_big_text); 373 STANDARD_LAYOUTS.add(R.layout.notification_template_material_inbox); 374 STANDARD_LAYOUTS.add(R.layout.notification_template_material_messaging); 375 STANDARD_LAYOUTS.add(R.layout.notification_template_material_media); 376 STANDARD_LAYOUTS.add(R.layout.notification_template_material_big_media); 377 STANDARD_LAYOUTS.add(R.layout.notification_template_ambient_header); 378 STANDARD_LAYOUTS.add(R.layout.notification_template_header); 379 STANDARD_LAYOUTS.add(R.layout.notification_template_material_ambient); 380 } 381 382 /** 383 * A large bitmap to be shown in the notification content area. 384 * 385 * @deprecated Use {@link Builder#setLargeIcon(Icon)} instead. 386 */ 387 @Deprecated 388 public Bitmap largeIcon; 389 390 /** 391 * The sound to play. 392 * 393 * <p> 394 * A notification that is noisy is more likely to be presented as a heads-up notification. 395 * </p> 396 * 397 * <p> 398 * To play the default notification sound, see {@link #defaults}. 399 * </p> 400 * @deprecated use {@link NotificationChannel#getSound()}. 401 */ 402 @Deprecated 403 public Uri sound; 404 405 /** 406 * Use this constant as the value for audioStreamType to request that 407 * the default stream type for notifications be used. Currently the 408 * default stream type is {@link AudioManager#STREAM_NOTIFICATION}. 409 * 410 * @deprecated Use {@link NotificationChannel#getAudioAttributes()} instead. 411 */ 412 @Deprecated 413 public static final int STREAM_DEFAULT = -1; 414 415 /** 416 * The audio stream type to use when playing the sound. 417 * Should be one of the STREAM_ constants from 418 * {@link android.media.AudioManager}. 419 * 420 * @deprecated Use {@link #audioAttributes} instead. 421 */ 422 @Deprecated 423 public int audioStreamType = STREAM_DEFAULT; 424 425 /** 426 * The default value of {@link #audioAttributes}. 427 */ 428 public static final AudioAttributes AUDIO_ATTRIBUTES_DEFAULT = new AudioAttributes.Builder() 429 .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) 430 .setUsage(AudioAttributes.USAGE_NOTIFICATION) 431 .build(); 432 433 /** 434 * The {@link AudioAttributes audio attributes} to use when playing the sound. 435 * 436 * @deprecated use {@link NotificationChannel#getAudioAttributes()} instead. 437 */ 438 @Deprecated 439 public AudioAttributes audioAttributes = AUDIO_ATTRIBUTES_DEFAULT; 440 441 /** 442 * The pattern with which to vibrate. 443 * 444 * <p> 445 * To vibrate the default pattern, see {@link #defaults}. 446 * </p> 447 * 448 * @see android.os.Vibrator#vibrate(long[],int) 449 * @deprecated use {@link NotificationChannel#getVibrationPattern()}. 450 */ 451 @Deprecated 452 public long[] vibrate; 453 454 /** 455 * The color of the led. The hardware will do its best approximation. 456 * 457 * @see #FLAG_SHOW_LIGHTS 458 * @see #flags 459 * @deprecated use {@link NotificationChannel#shouldShowLights()}. 460 */ 461 @ColorInt 462 @Deprecated 463 public int ledARGB; 464 465 /** 466 * The number of milliseconds for the LED to be on while it's flashing. 467 * The hardware will do its best approximation. 468 * 469 * @see #FLAG_SHOW_LIGHTS 470 * @see #flags 471 * @deprecated use {@link NotificationChannel#shouldShowLights()}. 472 */ 473 @Deprecated 474 public int ledOnMS; 475 476 /** 477 * The number of milliseconds for the LED to be off while it's flashing. 478 * The hardware will do its best approximation. 479 * 480 * @see #FLAG_SHOW_LIGHTS 481 * @see #flags 482 * 483 * @deprecated use {@link NotificationChannel#shouldShowLights()}. 484 */ 485 @Deprecated 486 public int ledOffMS; 487 488 /** 489 * Specifies which values should be taken from the defaults. 490 * <p> 491 * To set, OR the desired from {@link #DEFAULT_SOUND}, 492 * {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}. For all default 493 * values, use {@link #DEFAULT_ALL}. 494 * </p> 495 * 496 * @deprecated use {@link NotificationChannel#getSound()} and 497 * {@link NotificationChannel#shouldShowLights()} and 498 * {@link NotificationChannel#shouldVibrate()}. 499 */ 500 @Deprecated 501 public int defaults; 502 503 /** 504 * Bit to be bitwise-ored into the {@link #flags} field that should be 505 * set if you want the LED on for this notification. 506 * <ul> 507 * <li>To turn the LED off, pass 0 in the alpha channel for colorARGB 508 * or 0 for both ledOnMS and ledOffMS.</li> 509 * <li>To turn the LED on, pass 1 for ledOnMS and 0 for ledOffMS.</li> 510 * <li>To flash the LED, pass the number of milliseconds that it should 511 * be on and off to ledOnMS and ledOffMS.</li> 512 * </ul> 513 * <p> 514 * Since hardware varies, you are not guaranteed that any of the values 515 * you pass are honored exactly. Use the system defaults if possible 516 * because they will be set to values that work on any given hardware. 517 * <p> 518 * The alpha channel must be set for forward compatibility. 519 * 520 * @deprecated use {@link NotificationChannel#shouldShowLights()}. 521 */ 522 @Deprecated 523 public static final int FLAG_SHOW_LIGHTS = 0x00000001; 524 525 /** 526 * Bit to be bitwise-ored into the {@link #flags} field that should be 527 * set if this notification is in reference to something that is ongoing, 528 * like a phone call. It should not be set if this notification is in 529 * reference to something that happened at a particular point in time, 530 * like a missed phone call. 531 */ 532 public static final int FLAG_ONGOING_EVENT = 0x00000002; 533 534 /** 535 * Bit to be bitwise-ored into the {@link #flags} field that if set, 536 * the audio will be repeated until the notification is 537 * cancelled or the notification window is opened. 538 */ 539 public static final int FLAG_INSISTENT = 0x00000004; 540 541 /** 542 * Bit to be bitwise-ored into the {@link #flags} field that should be 543 * set if you would only like the sound, vibrate and ticker to be played 544 * if the notification was not already showing. 545 */ 546 public static final int FLAG_ONLY_ALERT_ONCE = 0x00000008; 547 548 /** 549 * Bit to be bitwise-ored into the {@link #flags} field that should be 550 * set if the notification should be canceled when it is clicked by the 551 * user. 552 */ 553 public static final int FLAG_AUTO_CANCEL = 0x00000010; 554 555 /** 556 * Bit to be bitwise-ored into the {@link #flags} field that should be 557 * set if the notification should not be canceled when the user clicks 558 * the Clear all button. 559 */ 560 public static final int FLAG_NO_CLEAR = 0x00000020; 561 562 /** 563 * Bit to be bitwise-ored into the {@link #flags} field that should be 564 * set if this notification represents a currently running service. This 565 * will normally be set for you by {@link Service#startForeground}. 566 */ 567 public static final int FLAG_FOREGROUND_SERVICE = 0x00000040; 568 569 /** 570 * Obsolete flag indicating high-priority notifications; use the priority field instead. 571 * 572 * @deprecated Use {@link #priority} with a positive value. 573 */ 574 @Deprecated 575 public static final int FLAG_HIGH_PRIORITY = 0x00000080; 576 577 /** 578 * Bit to be bitswise-ored into the {@link #flags} field that should be 579 * set if this notification is relevant to the current device only 580 * and it is not recommended that it bridge to other devices. 581 */ 582 public static final int FLAG_LOCAL_ONLY = 0x00000100; 583 584 /** 585 * Bit to be bitswise-ored into the {@link #flags} field that should be 586 * set if this notification is the group summary for a group of notifications. 587 * Grouped notifications may display in a cluster or stack on devices which 588 * support such rendering. Requires a group key also be set using {@link Builder#setGroup}. 589 */ 590 public static final int FLAG_GROUP_SUMMARY = 0x00000200; 591 592 /** 593 * Bit to be bitswise-ored into the {@link #flags} field that should be 594 * set if this notification is the group summary for an auto-group of notifications. 595 * 596 * @hide 597 */ 598 @SystemApi 599 public static final int FLAG_AUTOGROUP_SUMMARY = 0x00000400; 600 601 /** 602 * @hide 603 */ 604 public static final int FLAG_CAN_COLORIZE = 0x00000800; 605 606 public int flags; 607 608 /** @hide */ 609 @IntDef(prefix = { "PRIORITY_" }, value = { 610 PRIORITY_DEFAULT, 611 PRIORITY_LOW, 612 PRIORITY_MIN, 613 PRIORITY_HIGH, 614 PRIORITY_MAX 615 }) 616 @Retention(RetentionPolicy.SOURCE) 617 public @interface Priority {} 618 619 /** 620 * Default notification {@link #priority}. If your application does not prioritize its own 621 * notifications, use this value for all notifications. 622 * 623 * @deprecated use {@link NotificationManager#IMPORTANCE_DEFAULT} instead. 624 */ 625 @Deprecated 626 public static final int PRIORITY_DEFAULT = 0; 627 628 /** 629 * Lower {@link #priority}, for items that are less important. The UI may choose to show these 630 * items smaller, or at a different position in the list, compared with your app's 631 * {@link #PRIORITY_DEFAULT} items. 632 * 633 * @deprecated use {@link NotificationManager#IMPORTANCE_LOW} instead. 634 */ 635 @Deprecated 636 public static final int PRIORITY_LOW = -1; 637 638 /** 639 * Lowest {@link #priority}; these items might not be shown to the user except under special 640 * circumstances, such as detailed notification logs. 641 * 642 * @deprecated use {@link NotificationManager#IMPORTANCE_MIN} instead. 643 */ 644 @Deprecated 645 public static final int PRIORITY_MIN = -2; 646 647 /** 648 * Higher {@link #priority}, for more important notifications or alerts. The UI may choose to 649 * show these items larger, or at a different position in notification lists, compared with 650 * your app's {@link #PRIORITY_DEFAULT} items. 651 * 652 * @deprecated use {@link NotificationManager#IMPORTANCE_HIGH} instead. 653 */ 654 @Deprecated 655 public static final int PRIORITY_HIGH = 1; 656 657 /** 658 * Highest {@link #priority}, for your application's most important items that require the 659 * user's prompt attention or input. 660 * 661 * @deprecated use {@link NotificationManager#IMPORTANCE_HIGH} instead. 662 */ 663 @Deprecated 664 public static final int PRIORITY_MAX = 2; 665 666 /** 667 * Relative priority for this notification. 668 * 669 * Priority is an indication of how much of the user's valuable attention should be consumed by 670 * this notification. Low-priority notifications may be hidden from the user in certain 671 * situations, while the user might be interrupted for a higher-priority notification. The 672 * system will make a determination about how to interpret this priority when presenting 673 * the notification. 674 * 675 * <p> 676 * A notification that is at least {@link #PRIORITY_HIGH} is more likely to be presented 677 * as a heads-up notification. 678 * </p> 679 * 680 * @deprecated use {@link NotificationChannel#getImportance()} instead. 681 */ 682 @Priority 683 @Deprecated 684 public int priority; 685 686 /** 687 * Accent color (an ARGB integer like the constants in {@link android.graphics.Color}) 688 * to be applied by the standard Style templates when presenting this notification. 689 * 690 * The current template design constructs a colorful header image by overlaying the 691 * {@link #icon} image (stenciled in white) atop a field of this color. Alpha components are 692 * ignored. 693 */ 694 @ColorInt 695 public int color = COLOR_DEFAULT; 696 697 /** 698 * Special value of {@link #color} telling the system not to decorate this notification with 699 * any special color but instead use default colors when presenting this notification. 700 */ 701 @ColorInt 702 public static final int COLOR_DEFAULT = 0; // AKA Color.TRANSPARENT 703 704 /** 705 * Special value of {@link #color} used as a place holder for an invalid color. 706 * @hide 707 */ 708 @ColorInt 709 public static final int COLOR_INVALID = 1; 710 711 /** 712 * Sphere of visibility of this notification, which affects how and when the SystemUI reveals 713 * the notification's presence and contents in untrusted situations (namely, on the secure 714 * lockscreen). 715 * 716 * The default level, {@link #VISIBILITY_PRIVATE}, behaves exactly as notifications have always 717 * done on Android: The notification's {@link #icon} and {@link #tickerText} (if available) are 718 * shown in all situations, but the contents are only available if the device is unlocked for 719 * the appropriate user. 720 * 721 * A more permissive policy can be expressed by {@link #VISIBILITY_PUBLIC}; such a notification 722 * can be read even in an "insecure" context (that is, above a secure lockscreen). 723 * To modify the public version of this notification—for example, to redact some portions—see 724 * {@link Builder#setPublicVersion(Notification)}. 725 * 726 * Finally, a notification can be made {@link #VISIBILITY_SECRET}, which will suppress its icon 727 * and ticker until the user has bypassed the lockscreen. 728 */ 729 public @Visibility int visibility; 730 731 /** @hide */ 732 @IntDef(prefix = { "VISIBILITY_" }, value = { 733 VISIBILITY_PUBLIC, 734 VISIBILITY_PRIVATE, 735 VISIBILITY_SECRET, 736 }) 737 @Retention(RetentionPolicy.SOURCE) 738 public @interface Visibility {} 739 740 /** 741 * Notification visibility: Show this notification in its entirety on all lockscreens. 742 * 743 * {@see #visibility} 744 */ 745 public static final int VISIBILITY_PUBLIC = 1; 746 747 /** 748 * Notification visibility: Show this notification on all lockscreens, but conceal sensitive or 749 * private information on secure lockscreens. 750 * 751 * {@see #visibility} 752 */ 753 public static final int VISIBILITY_PRIVATE = 0; 754 755 /** 756 * Notification visibility: Do not reveal any part of this notification on a secure lockscreen. 757 * 758 * {@see #visibility} 759 */ 760 public static final int VISIBILITY_SECRET = -1; 761 762 /** 763 * Notification category: incoming call (voice or video) or similar synchronous communication request. 764 */ 765 public static final String CATEGORY_CALL = "call"; 766 767 /** 768 * Notification category: map turn-by-turn navigation. 769 */ 770 public static final String CATEGORY_NAVIGATION = "navigation"; 771 772 /** 773 * Notification category: incoming direct message (SMS, instant message, etc.). 774 */ 775 public static final String CATEGORY_MESSAGE = "msg"; 776 777 /** 778 * Notification category: asynchronous bulk message (email). 779 */ 780 public static final String CATEGORY_EMAIL = "email"; 781 782 /** 783 * Notification category: calendar event. 784 */ 785 public static final String CATEGORY_EVENT = "event"; 786 787 /** 788 * Notification category: promotion or advertisement. 789 */ 790 public static final String CATEGORY_PROMO = "promo"; 791 792 /** 793 * Notification category: alarm or timer. 794 */ 795 public static final String CATEGORY_ALARM = "alarm"; 796 797 /** 798 * Notification category: progress of a long-running background operation. 799 */ 800 public static final String CATEGORY_PROGRESS = "progress"; 801 802 /** 803 * Notification category: social network or sharing update. 804 */ 805 public static final String CATEGORY_SOCIAL = "social"; 806 807 /** 808 * Notification category: error in background operation or authentication status. 809 */ 810 public static final String CATEGORY_ERROR = "err"; 811 812 /** 813 * Notification category: media transport control for playback. 814 */ 815 public static final String CATEGORY_TRANSPORT = "transport"; 816 817 /** 818 * Notification category: system or device status update. Reserved for system use. 819 */ 820 public static final String CATEGORY_SYSTEM = "sys"; 821 822 /** 823 * Notification category: indication of running background service. 824 */ 825 public static final String CATEGORY_SERVICE = "service"; 826 827 /** 828 * Notification category: a specific, timely recommendation for a single thing. 829 * For example, a news app might want to recommend a news story it believes the user will 830 * want to read next. 831 */ 832 public static final String CATEGORY_RECOMMENDATION = "recommendation"; 833 834 /** 835 * Notification category: ongoing information about device or contextual status. 836 */ 837 public static final String CATEGORY_STATUS = "status"; 838 839 /** 840 * Notification category: user-scheduled reminder. 841 */ 842 public static final String CATEGORY_REMINDER = "reminder"; 843 844 /** 845 * Notification category: extreme car emergencies. 846 * @hide 847 */ 848 @SystemApi 849 public static final String CATEGORY_CAR_EMERGENCY = "car_emergency"; 850 851 /** 852 * Notification category: car warnings. 853 * @hide 854 */ 855 @SystemApi 856 public static final String CATEGORY_CAR_WARNING = "car_warning"; 857 858 /** 859 * Notification category: general car system information. 860 * @hide 861 */ 862 @SystemApi 863 public static final String CATEGORY_CAR_INFORMATION = "car_information"; 864 865 /** 866 * One of the predefined notification categories (see the <code>CATEGORY_*</code> constants) 867 * that best describes this Notification. May be used by the system for ranking and filtering. 868 */ 869 public String category; 870 871 private String mGroupKey; 872 873 /** 874 * Get the key used to group this notification into a cluster or stack 875 * with other notifications on devices which support such rendering. 876 */ 877 public String getGroup() { 878 return mGroupKey; 879 } 880 881 private String mSortKey; 882 883 /** 884 * Get a sort key that orders this notification among other notifications from the 885 * same package. This can be useful if an external sort was already applied and an app 886 * would like to preserve this. Notifications will be sorted lexicographically using this 887 * value, although providing different priorities in addition to providing sort key may 888 * cause this value to be ignored. 889 * 890 * <p>This sort key can also be used to order members of a notification group. See 891 * {@link Builder#setGroup}. 892 * 893 * @see String#compareTo(String) 894 */ 895 public String getSortKey() { 896 return mSortKey; 897 } 898 899 /** 900 * Additional semantic data to be carried around with this Notification. 901 * <p> 902 * The extras keys defined here are intended to capture the original inputs to {@link Builder} 903 * APIs, and are intended to be used by 904 * {@link android.service.notification.NotificationListenerService} implementations to extract 905 * detailed information from notification objects. 906 */ 907 public Bundle extras = new Bundle(); 908 909 /** 910 * All pending intents in the notification as the system needs to be able to access them but 911 * touching the extras bundle in the system process is not safe because the bundle may contain 912 * custom parcelable objects. 913 * 914 * @hide 915 */ 916 public ArraySet<PendingIntent> allPendingIntents; 917 918 /** 919 * Token identifying the notification that is applying doze/bgcheck whitelisting to the 920 * pending intents inside of it, so only those will get the behavior. 921 * 922 * @hide 923 */ 924 private IBinder mWhitelistToken; 925 926 /** 927 * Must be set by a process to start associating tokens with Notification objects 928 * coming in to it. This is set by NotificationManagerService. 929 * 930 * @hide 931 */ 932 static public IBinder processWhitelistToken; 933 934 /** 935 * {@link #extras} key: this is the title of the notification, 936 * as supplied to {@link Builder#setContentTitle(CharSequence)}. 937 */ 938 public static final String EXTRA_TITLE = "android.title"; 939 940 /** 941 * {@link #extras} key: this is the title of the notification when shown in expanded form, 942 * e.g. as supplied to {@link BigTextStyle#setBigContentTitle(CharSequence)}. 943 */ 944 public static final String EXTRA_TITLE_BIG = EXTRA_TITLE + ".big"; 945 946 /** 947 * {@link #extras} key: this is the main text payload, as supplied to 948 * {@link Builder#setContentText(CharSequence)}. 949 */ 950 public static final String EXTRA_TEXT = "android.text"; 951 952 /** 953 * {@link #extras} key: this is a third line of text, as supplied to 954 * {@link Builder#setSubText(CharSequence)}. 955 */ 956 public static final String EXTRA_SUB_TEXT = "android.subText"; 957 958 /** 959 * {@link #extras} key: this is the remote input history, as supplied to 960 * {@link Builder#setRemoteInputHistory(CharSequence[])}. 961 * 962 * Apps can fill this through {@link Builder#setRemoteInputHistory(CharSequence[])} 963 * with the most recent inputs that have been sent through a {@link RemoteInput} of this 964 * Notification and are expected to clear it once the it is no longer relevant (e.g. for chat 965 * notifications once the other party has responded). 966 * 967 * The extra with this key is of type CharSequence[] and contains the most recent entry at 968 * the 0 index, the second most recent at the 1 index, etc. 969 * 970 * @see Builder#setRemoteInputHistory(CharSequence[]) 971 */ 972 public static final String EXTRA_REMOTE_INPUT_HISTORY = "android.remoteInputHistory"; 973 974 /** 975 * {@link #extras} key: boolean as supplied to 976 * {@link Builder#setShowRemoteInputSpinner(boolean)}. 977 * 978 * If set to true, then the view displaying the remote input history from 979 * {@link Builder#setRemoteInputHistory(CharSequence[])} will have a progress spinner. 980 * 981 * @see Builder#setShowRemoteInputSpinner(boolean) 982 * @hide 983 */ 984 public static final String EXTRA_SHOW_REMOTE_INPUT_SPINNER = "android.remoteInputSpinner"; 985 986 /** 987 * {@link #extras} key: this is a small piece of additional text as supplied to 988 * {@link Builder#setContentInfo(CharSequence)}. 989 */ 990 public static final String EXTRA_INFO_TEXT = "android.infoText"; 991 992 /** 993 * {@link #extras} key: this is a line of summary information intended to be shown 994 * alongside expanded notifications, as supplied to (e.g.) 995 * {@link BigTextStyle#setSummaryText(CharSequence)}. 996 */ 997 public static final String EXTRA_SUMMARY_TEXT = "android.summaryText"; 998 999 /** 1000 * {@link #extras} key: this is the longer text shown in the big form of a 1001 * {@link BigTextStyle} notification, as supplied to 1002 * {@link BigTextStyle#bigText(CharSequence)}. 1003 */ 1004 public static final String EXTRA_BIG_TEXT = "android.bigText"; 1005 1006 /** 1007 * {@link #extras} key: this is the resource ID of the notification's main small icon, as 1008 * supplied to {@link Builder#setSmallIcon(int)}. 1009 * 1010 * @deprecated Use {@link #getSmallIcon()}, which supports a wider variety of icon sources. 1011 */ 1012 @Deprecated 1013 public static final String EXTRA_SMALL_ICON = "android.icon"; 1014 1015 /** 1016 * {@link #extras} key: this is a bitmap to be used instead of the small icon when showing the 1017 * notification payload, as 1018 * supplied to {@link Builder#setLargeIcon(android.graphics.Bitmap)}. 1019 * 1020 * @deprecated Use {@link #getLargeIcon()}, which supports a wider variety of icon sources. 1021 */ 1022 @Deprecated 1023 public static final String EXTRA_LARGE_ICON = "android.largeIcon"; 1024 1025 /** 1026 * {@link #extras} key: this is a bitmap to be used instead of the one from 1027 * {@link Builder#setLargeIcon(android.graphics.Bitmap)} when the notification is 1028 * shown in its expanded form, as supplied to 1029 * {@link BigPictureStyle#bigLargeIcon(android.graphics.Bitmap)}. 1030 */ 1031 public static final String EXTRA_LARGE_ICON_BIG = EXTRA_LARGE_ICON + ".big"; 1032 1033 /** 1034 * {@link #extras} key: this is the progress value supplied to 1035 * {@link Builder#setProgress(int, int, boolean)}. 1036 */ 1037 public static final String EXTRA_PROGRESS = "android.progress"; 1038 1039 /** 1040 * {@link #extras} key: this is the maximum value supplied to 1041 * {@link Builder#setProgress(int, int, boolean)}. 1042 */ 1043 public static final String EXTRA_PROGRESS_MAX = "android.progressMax"; 1044 1045 /** 1046 * {@link #extras} key: whether the progress bar is indeterminate, supplied to 1047 * {@link Builder#setProgress(int, int, boolean)}. 1048 */ 1049 public static final String EXTRA_PROGRESS_INDETERMINATE = "android.progressIndeterminate"; 1050 1051 /** 1052 * {@link #extras} key: whether {@link #when} should be shown as a count-up timer (specifically 1053 * a {@link android.widget.Chronometer}) instead of a timestamp, as supplied to 1054 * {@link Builder#setUsesChronometer(boolean)}. 1055 */ 1056 public static final String EXTRA_SHOW_CHRONOMETER = "android.showChronometer"; 1057 1058 /** 1059 * {@link #extras} key: whether the chronometer set on the notification should count down 1060 * instead of counting up. Is only relevant if key {@link #EXTRA_SHOW_CHRONOMETER} is present. 1061 * This extra is a boolean. The default is false. 1062 */ 1063 public static final String EXTRA_CHRONOMETER_COUNT_DOWN = "android.chronometerCountDown"; 1064 1065 /** 1066 * {@link #extras} key: whether {@link #when} should be shown, 1067 * as supplied to {@link Builder#setShowWhen(boolean)}. 1068 */ 1069 public static final String EXTRA_SHOW_WHEN = "android.showWhen"; 1070 1071 /** 1072 * {@link #extras} key: this is a bitmap to be shown in {@link BigPictureStyle} expanded 1073 * notifications, supplied to {@link BigPictureStyle#bigPicture(android.graphics.Bitmap)}. 1074 */ 1075 public static final String EXTRA_PICTURE = "android.picture"; 1076 1077 /** 1078 * {@link #extras} key: An array of CharSequences to show in {@link InboxStyle} expanded 1079 * notifications, each of which was supplied to {@link InboxStyle#addLine(CharSequence)}. 1080 */ 1081 public static final String EXTRA_TEXT_LINES = "android.textLines"; 1082 1083 /** 1084 * {@link #extras} key: A string representing the name of the specific 1085 * {@link android.app.Notification.Style} used to create this notification. 1086 */ 1087 public static final String EXTRA_TEMPLATE = "android.template"; 1088 1089 /** 1090 * {@link #extras} key: A String array containing the people that this notification relates to, 1091 * each of which was supplied to {@link Builder#addPerson(String)}. 1092 * 1093 * @deprecated the actual objects are now in {@link #EXTRA_PEOPLE_LIST} 1094 */ 1095 public static final String EXTRA_PEOPLE = "android.people"; 1096 1097 /** 1098 * {@link #extras} key: An arrayList of {@link Person} objects containing the people that 1099 * this notification relates to. 1100 */ 1101 public static final String EXTRA_PEOPLE_LIST = "android.people.list"; 1102 1103 /** 1104 * Allow certain system-generated notifications to appear before the device is provisioned. 1105 * Only available to notifications coming from the android package. 1106 * @hide 1107 */ 1108 @SystemApi 1109 @RequiresPermission(android.Manifest.permission.NOTIFICATION_DURING_SETUP) 1110 public static final String EXTRA_ALLOW_DURING_SETUP = "android.allowDuringSetup"; 1111 1112 /** 1113 * {@link #extras} key: A 1114 * {@link android.content.ContentUris content URI} pointing to an image that can be displayed 1115 * in the background when the notification is selected. Used on television platforms. 1116 * The URI must point to an image stream suitable for passing into 1117 * {@link android.graphics.BitmapFactory#decodeStream(java.io.InputStream) 1118 * BitmapFactory.decodeStream}; all other content types will be ignored. 1119 */ 1120 public static final String EXTRA_BACKGROUND_IMAGE_URI = "android.backgroundImageUri"; 1121 1122 /** 1123 * {@link #extras} key: A 1124 * {@link android.media.session.MediaSession.Token} associated with a 1125 * {@link android.app.Notification.MediaStyle} notification. 1126 */ 1127 public static final String EXTRA_MEDIA_SESSION = "android.mediaSession"; 1128 1129 /** 1130 * {@link #extras} key: the indices of actions to be shown in the compact view, 1131 * as supplied to (e.g.) {@link MediaStyle#setShowActionsInCompactView(int...)}. 1132 */ 1133 public static final String EXTRA_COMPACT_ACTIONS = "android.compactActions"; 1134 1135 /** 1136 * {@link #extras} key: the username to be displayed for all messages sent by the user including 1137 * direct replies 1138 * {@link android.app.Notification.MessagingStyle} notification. This extra is a 1139 * {@link CharSequence} 1140 * 1141 * @deprecated use {@link #EXTRA_MESSAGING_PERSON} 1142 */ 1143 public static final String EXTRA_SELF_DISPLAY_NAME = "android.selfDisplayName"; 1144 1145 /** 1146 * {@link #extras} key: the person to be displayed for all messages sent by the user including 1147 * direct replies 1148 * {@link android.app.Notification.MessagingStyle} notification. This extra is a 1149 * {@link Person} 1150 */ 1151 public static final String EXTRA_MESSAGING_PERSON = "android.messagingUser"; 1152 1153 /** 1154 * {@link #extras} key: a {@link CharSequence} to be displayed as the title to a conversation 1155 * represented by a {@link android.app.Notification.MessagingStyle} 1156 */ 1157 public static final String EXTRA_CONVERSATION_TITLE = "android.conversationTitle"; 1158 1159 /** 1160 * {@link #extras} key: an array of {@link android.app.Notification.MessagingStyle.Message} 1161 * bundles provided by a 1162 * {@link android.app.Notification.MessagingStyle} notification. This extra is a parcelable 1163 * array of bundles. 1164 */ 1165 public static final String EXTRA_MESSAGES = "android.messages"; 1166 1167 /** 1168 * {@link #extras} key: an array of 1169 * {@link android.app.Notification.MessagingStyle#addHistoricMessage historic} 1170 * {@link android.app.Notification.MessagingStyle.Message} bundles provided by a 1171 * {@link android.app.Notification.MessagingStyle} notification. This extra is a parcelable 1172 * array of bundles. 1173 */ 1174 public static final String EXTRA_HISTORIC_MESSAGES = "android.messages.historic"; 1175 1176 /** 1177 * {@link #extras} key: whether the {@link android.app.Notification.MessagingStyle} notification 1178 * represents a group conversation. 1179 */ 1180 public static final String EXTRA_IS_GROUP_CONVERSATION = "android.isGroupConversation"; 1181 1182 /** 1183 * {@link #extras} key: whether the notification should be colorized as 1184 * supplied to {@link Builder#setColorized(boolean)}}. 1185 */ 1186 public static final String EXTRA_COLORIZED = "android.colorized"; 1187 1188 /** 1189 * @hide 1190 */ 1191 public static final String EXTRA_BUILDER_APPLICATION_INFO = "android.appInfo"; 1192 1193 /** 1194 * @hide 1195 */ 1196 public static final String EXTRA_CONTAINS_CUSTOM_VIEW = "android.contains.customView"; 1197 1198 /** 1199 * @hide 1200 */ 1201 public static final String EXTRA_REDUCED_IMAGES = "android.reduced.images"; 1202 1203 /** 1204 * {@link #extras} key: the audio contents of this notification. 1205 * 1206 * This is for use when rendering the notification on an audio-focused interface; 1207 * the audio contents are a complete sound sample that contains the contents/body of the 1208 * notification. This may be used in substitute of a Text-to-Speech reading of the 1209 * notification. For example if the notification represents a voice message this should point 1210 * to the audio of that message. 1211 * 1212 * The data stored under this key should be a String representation of a Uri that contains the 1213 * audio contents in one of the following formats: WAV, PCM 16-bit, AMR-WB. 1214 * 1215 * This extra is unnecessary if you are using {@code MessagingStyle} since each {@code Message} 1216 * has a field for holding data URI. That field can be used for audio. 1217 * See {@code Message#setData}. 1218 * 1219 * Example usage: 1220 * <pre> 1221 * {@code 1222 * Notification.Builder myBuilder = (build your Notification as normal); 1223 * myBuilder.getExtras().putString(EXTRA_AUDIO_CONTENTS_URI, myAudioUri.toString()); 1224 * } 1225 * </pre> 1226 */ 1227 public static final String EXTRA_AUDIO_CONTENTS_URI = "android.audioContents"; 1228 1229 /** @hide */ 1230 @SystemApi 1231 @RequiresPermission(android.Manifest.permission.SUBSTITUTE_NOTIFICATION_APP_NAME) 1232 public static final String EXTRA_SUBSTITUTE_APP_NAME = "android.substName"; 1233 1234 /** 1235 * This is set on the notifications shown by system_server about apps running foreground 1236 * services. It indicates that the notification should be shown 1237 * only if any of the given apps do not already have a properly tagged 1238 * {@link #FLAG_FOREGROUND_SERVICE} notification currently visible to the user. 1239 * This is a string array of all package names of the apps. 1240 * @hide 1241 */ 1242 public static final String EXTRA_FOREGROUND_APPS = "android.foregroundApps"; 1243 1244 private Icon mSmallIcon; 1245 private Icon mLargeIcon; 1246 1247 private String mChannelId; 1248 private long mTimeout; 1249 1250 private String mShortcutId; 1251 private CharSequence mSettingsText; 1252 1253 /** @hide */ 1254 @IntDef(prefix = { "GROUP_ALERT_" }, value = { 1255 GROUP_ALERT_ALL, GROUP_ALERT_CHILDREN, GROUP_ALERT_SUMMARY 1256 }) 1257 @Retention(RetentionPolicy.SOURCE) 1258 public @interface GroupAlertBehavior {} 1259 1260 /** 1261 * Constant for {@link Builder#setGroupAlertBehavior(int)}, meaning that all notifications in a 1262 * group with sound or vibration ought to make sound or vibrate (respectively), so this 1263 * notification will not be muted when it is in a group. 1264 */ 1265 public static final int GROUP_ALERT_ALL = 0; 1266 1267 /** 1268 * Constant for {@link Builder#setGroupAlertBehavior(int)}, meaning that all children 1269 * notification in a group should be silenced (no sound or vibration) even if they are posted 1270 * to a {@link NotificationChannel} that has sound and/or vibration. Use this constant to 1271 * mute this notification if this notification is a group child. This must be applied to all 1272 * children notifications you want to mute. 1273 * 1274 * <p> For example, you might want to use this constant if you post a number of children 1275 * notifications at once (say, after a periodic sync), and only need to notify the user 1276 * audibly once. 1277 */ 1278 public static final int GROUP_ALERT_SUMMARY = 1; 1279 1280 /** 1281 * Constant for {@link Builder#setGroupAlertBehavior(int)}, meaning that the summary 1282 * notification in a group should be silenced (no sound or vibration) even if they are 1283 * posted to a {@link NotificationChannel} that has sound and/or vibration. Use this constant 1284 * to mute this notification if this notification is a group summary. 1285 * 1286 * <p>For example, you might want to use this constant if only the children notifications 1287 * in your group have content and the summary is only used to visually group notifications 1288 * rather than to alert the user that new information is available. 1289 */ 1290 public static final int GROUP_ALERT_CHILDREN = 2; 1291 1292 private int mGroupAlertBehavior = GROUP_ALERT_ALL; 1293 1294 /** 1295 * If this notification is being shown as a badge, always show as a number. 1296 */ 1297 public static final int BADGE_ICON_NONE = 0; 1298 1299 /** 1300 * If this notification is being shown as a badge, use the {@link #getSmallIcon()} to 1301 * represent this notification. 1302 */ 1303 public static final int BADGE_ICON_SMALL = 1; 1304 1305 /** 1306 * If this notification is being shown as a badge, use the {@link #getLargeIcon()} to 1307 * represent this notification. 1308 */ 1309 public static final int BADGE_ICON_LARGE = 2; 1310 private int mBadgeIcon = BADGE_ICON_NONE; 1311 1312 /** 1313 * Structure to encapsulate a named action that can be shown as part of this notification. 1314 * It must include an icon, a label, and a {@link PendingIntent} to be fired when the action is 1315 * selected by the user. 1316 * <p> 1317 * Apps should use {@link Notification.Builder#addAction(int, CharSequence, PendingIntent)} 1318 * or {@link Notification.Builder#addAction(Notification.Action)} 1319 * to attach actions. 1320 */ 1321 public static class Action implements Parcelable { 1322 /** 1323 * {@link #extras} key: Keys to a {@link Parcelable} {@link ArrayList} of 1324 * {@link RemoteInput}s. 1325 * 1326 * This is intended for {@link RemoteInput}s that only accept data, meaning 1327 * {@link RemoteInput#getAllowFreeFormInput} is false, {@link RemoteInput#getChoices} 1328 * is null or empty, and {@link RemoteInput#getAllowedDataTypes is non-null and not 1329 * empty. These {@link RemoteInput}s will be ignored by devices that do not 1330 * support non-text-based {@link RemoteInput}s. See {@link Builder#build}. 1331 * 1332 * You can test if a RemoteInput matches these constraints using 1333 * {@link RemoteInput#isDataOnly}. 1334 */ 1335 private static final String EXTRA_DATA_ONLY_INPUTS = "android.extra.DATA_ONLY_INPUTS"; 1336 1337 /** 1338 * {@link }: No semantic action defined. 1339 */ 1340 public static final int SEMANTIC_ACTION_NONE = 0; 1341 1342 /** 1343 * {@code SemanticAction}: Reply to a conversation, chat, group, or wherever replies 1344 * may be appropriate. 1345 */ 1346 public static final int SEMANTIC_ACTION_REPLY = 1; 1347 1348 /** 1349 * {@code SemanticAction}: Mark content as read. 1350 */ 1351 public static final int SEMANTIC_ACTION_MARK_AS_READ = 2; 1352 1353 /** 1354 * {@code SemanticAction}: Mark content as unread. 1355 */ 1356 public static final int SEMANTIC_ACTION_MARK_AS_UNREAD = 3; 1357 1358 /** 1359 * {@code SemanticAction}: Delete the content associated with the notification. This 1360 * could mean deleting an email, message, etc. 1361 */ 1362 public static final int SEMANTIC_ACTION_DELETE = 4; 1363 1364 /** 1365 * {@code SemanticAction}: Archive the content associated with the notification. This 1366 * could mean archiving an email, message, etc. 1367 */ 1368 public static final int SEMANTIC_ACTION_ARCHIVE = 5; 1369 1370 /** 1371 * {@code SemanticAction}: Mute the content associated with the notification. This could 1372 * mean silencing a conversation or currently playing media. 1373 */ 1374 public static final int SEMANTIC_ACTION_MUTE = 6; 1375 1376 /** 1377 * {@code SemanticAction}: Unmute the content associated with the notification. This could 1378 * mean un-silencing a conversation or currently playing media. 1379 */ 1380 public static final int SEMANTIC_ACTION_UNMUTE = 7; 1381 1382 /** 1383 * {@code SemanticAction}: Mark content with a thumbs up. 1384 */ 1385 public static final int SEMANTIC_ACTION_THUMBS_UP = 8; 1386 1387 /** 1388 * {@code SemanticAction}: Mark content with a thumbs down. 1389 */ 1390 public static final int SEMANTIC_ACTION_THUMBS_DOWN = 9; 1391 1392 /** 1393 * {@code SemanticAction}: Call a contact, group, etc. 1394 */ 1395 public static final int SEMANTIC_ACTION_CALL = 10; 1396 1397 private final Bundle mExtras; 1398 private Icon mIcon; 1399 private final RemoteInput[] mRemoteInputs; 1400 private boolean mAllowGeneratedReplies = true; 1401 private final @SemanticAction int mSemanticAction; 1402 1403 /** 1404 * Small icon representing the action. 1405 * 1406 * @deprecated Use {@link Action#getIcon()} instead. 1407 */ 1408 @Deprecated 1409 public int icon; 1410 1411 /** 1412 * Title of the action. 1413 */ 1414 public CharSequence title; 1415 1416 /** 1417 * Intent to send when the user invokes this action. May be null, in which case the action 1418 * may be rendered in a disabled presentation by the system UI. 1419 */ 1420 public PendingIntent actionIntent; 1421 1422 private Action(Parcel in) { 1423 if (in.readInt() != 0) { 1424 mIcon = Icon.CREATOR.createFromParcel(in); 1425 if (mIcon.getType() == Icon.TYPE_RESOURCE) { 1426 icon = mIcon.getResId(); 1427 } 1428 } 1429 title = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); 1430 if (in.readInt() == 1) { 1431 actionIntent = PendingIntent.CREATOR.createFromParcel(in); 1432 } 1433 mExtras = Bundle.setDefusable(in.readBundle(), true); 1434 mRemoteInputs = in.createTypedArray(RemoteInput.CREATOR); 1435 mAllowGeneratedReplies = in.readInt() == 1; 1436 mSemanticAction = in.readInt(); 1437 } 1438 1439 /** 1440 * @deprecated Use {@link android.app.Notification.Action.Builder}. 1441 */ 1442 @Deprecated 1443 public Action(int icon, CharSequence title, PendingIntent intent) { 1444 this(Icon.createWithResource("", icon), title, intent, new Bundle(), null, true, 1445 SEMANTIC_ACTION_NONE); 1446 } 1447 1448 /** Keep in sync with {@link Notification.Action.Builder#Builder(Action)}! */ 1449 private Action(Icon icon, CharSequence title, PendingIntent intent, Bundle extras, 1450 RemoteInput[] remoteInputs, boolean allowGeneratedReplies, 1451 @SemanticAction int semanticAction) { 1452 this.mIcon = icon; 1453 if (icon != null && icon.getType() == Icon.TYPE_RESOURCE) { 1454 this.icon = icon.getResId(); 1455 } 1456 this.title = title; 1457 this.actionIntent = intent; 1458 this.mExtras = extras != null ? extras : new Bundle(); 1459 this.mRemoteInputs = remoteInputs; 1460 this.mAllowGeneratedReplies = allowGeneratedReplies; 1461 this.mSemanticAction = semanticAction; 1462 } 1463 1464 /** 1465 * Return an icon representing the action. 1466 */ 1467 public Icon getIcon() { 1468 if (mIcon == null && icon != 0) { 1469 // you snuck an icon in here without using the builder; let's try to keep it 1470 mIcon = Icon.createWithResource("", icon); 1471 } 1472 return mIcon; 1473 } 1474 1475 /** 1476 * Get additional metadata carried around with this Action. 1477 */ 1478 public Bundle getExtras() { 1479 return mExtras; 1480 } 1481 1482 /** 1483 * Return whether the platform should automatically generate possible replies for this 1484 * {@link Action} 1485 */ 1486 public boolean getAllowGeneratedReplies() { 1487 return mAllowGeneratedReplies; 1488 } 1489 1490 /** 1491 * Get the list of inputs to be collected from the user when this action is sent. 1492 * May return null if no remote inputs were added. Only returns inputs which accept 1493 * a text input. For inputs which only accept data use {@link #getDataOnlyRemoteInputs}. 1494 */ 1495 public RemoteInput[] getRemoteInputs() { 1496 return mRemoteInputs; 1497 } 1498 1499 /** 1500 * Returns the {@code SemanticAction} associated with this {@link Action}. A 1501 * {@code SemanticAction} denotes what an {@link Action}'s {@link PendingIntent} will do 1502 * (eg. reply, mark as read, delete, etc). 1503 */ 1504 public @SemanticAction int getSemanticAction() { 1505 return mSemanticAction; 1506 } 1507 1508 /** 1509 * Get the list of inputs to be collected from the user that ONLY accept data when this 1510 * action is sent. These remote inputs are guaranteed to return true on a call to 1511 * {@link RemoteInput#isDataOnly}. 1512 * 1513 * Returns null if there are no data-only remote inputs. 1514 * 1515 * This method exists so that legacy RemoteInput collectors that pre-date the addition 1516 * of non-textual RemoteInputs do not access these remote inputs. 1517 */ 1518 public RemoteInput[] getDataOnlyRemoteInputs() { 1519 return (RemoteInput[]) mExtras.getParcelableArray(EXTRA_DATA_ONLY_INPUTS); 1520 } 1521 1522 /** 1523 * Builder class for {@link Action} objects. 1524 */ 1525 public static final class Builder { 1526 private final Icon mIcon; 1527 private final CharSequence mTitle; 1528 private final PendingIntent mIntent; 1529 private boolean mAllowGeneratedReplies = true; 1530 private final Bundle mExtras; 1531 private ArrayList<RemoteInput> mRemoteInputs; 1532 private @SemanticAction int mSemanticAction; 1533 1534 /** 1535 * Construct a new builder for {@link Action} object. 1536 * @param icon icon to show for this action 1537 * @param title the title of the action 1538 * @param intent the {@link PendingIntent} to fire when users trigger this action 1539 */ 1540 @Deprecated 1541 public Builder(int icon, CharSequence title, PendingIntent intent) { 1542 this(Icon.createWithResource("", icon), title, intent); 1543 } 1544 1545 /** 1546 * Construct a new builder for {@link Action} object. 1547 * @param icon icon to show for this action 1548 * @param title the title of the action 1549 * @param intent the {@link PendingIntent} to fire when users trigger this action 1550 */ 1551 public Builder(Icon icon, CharSequence title, PendingIntent intent) { 1552 this(icon, title, intent, new Bundle(), null, true, SEMANTIC_ACTION_NONE); 1553 } 1554 1555 /** 1556 * Construct a new builder for {@link Action} object using the fields from an 1557 * {@link Action}. 1558 * @param action the action to read fields from. 1559 */ 1560 public Builder(Action action) { 1561 this(action.getIcon(), action.title, action.actionIntent, 1562 new Bundle(action.mExtras), action.getRemoteInputs(), 1563 action.getAllowGeneratedReplies(), action.getSemanticAction()); 1564 } 1565 1566 private Builder(Icon icon, CharSequence title, PendingIntent intent, Bundle extras, 1567 RemoteInput[] remoteInputs, boolean allowGeneratedReplies, 1568 @SemanticAction int semanticAction) { 1569 mIcon = icon; 1570 mTitle = title; 1571 mIntent = intent; 1572 mExtras = extras; 1573 if (remoteInputs != null) { 1574 mRemoteInputs = new ArrayList<RemoteInput>(remoteInputs.length); 1575 Collections.addAll(mRemoteInputs, remoteInputs); 1576 } 1577 mAllowGeneratedReplies = allowGeneratedReplies; 1578 mSemanticAction = semanticAction; 1579 } 1580 1581 /** 1582 * Merge additional metadata into this builder. 1583 * 1584 * <p>Values within the Bundle will replace existing extras values in this Builder. 1585 * 1586 * @see Notification.Action#extras 1587 */ 1588 public Builder addExtras(Bundle extras) { 1589 if (extras != null) { 1590 mExtras.putAll(extras); 1591 } 1592 return this; 1593 } 1594 1595 /** 1596 * Get the metadata Bundle used by this Builder. 1597 * 1598 * <p>The returned Bundle is shared with this Builder. 1599 */ 1600 public Bundle getExtras() { 1601 return mExtras; 1602 } 1603 1604 /** 1605 * Add an input to be collected from the user when this action is sent. 1606 * Response values can be retrieved from the fired intent by using the 1607 * {@link RemoteInput#getResultsFromIntent} function. 1608 * @param remoteInput a {@link RemoteInput} to add to the action 1609 * @return this object for method chaining 1610 */ 1611 public Builder addRemoteInput(RemoteInput remoteInput) { 1612 if (mRemoteInputs == null) { 1613 mRemoteInputs = new ArrayList<RemoteInput>(); 1614 } 1615 mRemoteInputs.add(remoteInput); 1616 return this; 1617 } 1618 1619 /** 1620 * Set whether the platform should automatically generate possible replies to add to 1621 * {@link RemoteInput#getChoices()}. If the {@link Action} doesn't have a 1622 * {@link RemoteInput}, this has no effect. 1623 * @param allowGeneratedReplies {@code true} to allow generated replies, {@code false} 1624 * otherwise 1625 * @return this object for method chaining 1626 * The default value is {@code true} 1627 */ 1628 public Builder setAllowGeneratedReplies(boolean allowGeneratedReplies) { 1629 mAllowGeneratedReplies = allowGeneratedReplies; 1630 return this; 1631 } 1632 1633 /** 1634 * Sets the {@code SemanticAction} for this {@link Action}. A 1635 * {@code SemanticAction} denotes what an {@link Action}'s 1636 * {@link PendingIntent} will do (eg. reply, mark as read, delete, etc). 1637 * @param semanticAction a SemanticAction defined within {@link Action} with 1638 * {@code SEMANTIC_ACTION_} prefixes 1639 * @return this object for method chaining 1640 */ 1641 public Builder setSemanticAction(@SemanticAction int semanticAction) { 1642 mSemanticAction = semanticAction; 1643 return this; 1644 } 1645 1646 /** 1647 * Apply an extender to this action builder. Extenders may be used to add 1648 * metadata or change options on this builder. 1649 */ 1650 public Builder extend(Extender extender) { 1651 extender.extend(this); 1652 return this; 1653 } 1654 1655 /** 1656 * Combine all of the options that have been set and return a new {@link Action} 1657 * object. 1658 * @return the built action 1659 */ 1660 public Action build() { 1661 ArrayList<RemoteInput> dataOnlyInputs = new ArrayList<>(); 1662 RemoteInput[] previousDataInputs = 1663 (RemoteInput[]) mExtras.getParcelableArray(EXTRA_DATA_ONLY_INPUTS); 1664 if (previousDataInputs != null) { 1665 for (RemoteInput input : previousDataInputs) { 1666 dataOnlyInputs.add(input); 1667 } 1668 } 1669 List<RemoteInput> textInputs = new ArrayList<>(); 1670 if (mRemoteInputs != null) { 1671 for (RemoteInput input : mRemoteInputs) { 1672 if (input.isDataOnly()) { 1673 dataOnlyInputs.add(input); 1674 } else { 1675 textInputs.add(input); 1676 } 1677 } 1678 } 1679 if (!dataOnlyInputs.isEmpty()) { 1680 RemoteInput[] dataInputsArr = 1681 dataOnlyInputs.toArray(new RemoteInput[dataOnlyInputs.size()]); 1682 mExtras.putParcelableArray(EXTRA_DATA_ONLY_INPUTS, dataInputsArr); 1683 } 1684 RemoteInput[] textInputsArr = textInputs.isEmpty() 1685 ? null : textInputs.toArray(new RemoteInput[textInputs.size()]); 1686 return new Action(mIcon, mTitle, mIntent, mExtras, textInputsArr, 1687 mAllowGeneratedReplies, mSemanticAction); 1688 } 1689 } 1690 1691 @Override 1692 public Action clone() { 1693 return new Action( 1694 getIcon(), 1695 title, 1696 actionIntent, // safe to alias 1697 mExtras == null ? new Bundle() : new Bundle(mExtras), 1698 getRemoteInputs(), 1699 getAllowGeneratedReplies(), 1700 getSemanticAction()); 1701 } 1702 1703 @Override 1704 public int describeContents() { 1705 return 0; 1706 } 1707 1708 @Override 1709 public void writeToParcel(Parcel out, int flags) { 1710 final Icon ic = getIcon(); 1711 if (ic != null) { 1712 out.writeInt(1); 1713 ic.writeToParcel(out, 0); 1714 } else { 1715 out.writeInt(0); 1716 } 1717 TextUtils.writeToParcel(title, out, flags); 1718 if (actionIntent != null) { 1719 out.writeInt(1); 1720 actionIntent.writeToParcel(out, flags); 1721 } else { 1722 out.writeInt(0); 1723 } 1724 out.writeBundle(mExtras); 1725 out.writeTypedArray(mRemoteInputs, flags); 1726 out.writeInt(mAllowGeneratedReplies ? 1 : 0); 1727 out.writeInt(mSemanticAction); 1728 } 1729 1730 public static final Parcelable.Creator<Action> CREATOR = 1731 new Parcelable.Creator<Action>() { 1732 public Action createFromParcel(Parcel in) { 1733 return new Action(in); 1734 } 1735 public Action[] newArray(int size) { 1736 return new Action[size]; 1737 } 1738 }; 1739 1740 /** 1741 * Extender interface for use with {@link Builder#extend}. Extenders may be used to add 1742 * metadata or change options on an action builder. 1743 */ 1744 public interface Extender { 1745 /** 1746 * Apply this extender to a notification action builder. 1747 * @param builder the builder to be modified. 1748 * @return the build object for chaining. 1749 */ 1750 public Builder extend(Builder builder); 1751 } 1752 1753 /** 1754 * Wearable extender for notification actions. To add extensions to an action, 1755 * create a new {@link android.app.Notification.Action.WearableExtender} object using 1756 * the {@code WearableExtender()} constructor and apply it to a 1757 * {@link android.app.Notification.Action.Builder} using 1758 * {@link android.app.Notification.Action.Builder#extend}. 1759 * 1760 * <pre class="prettyprint"> 1761 * Notification.Action action = new Notification.Action.Builder( 1762 * R.drawable.archive_all, "Archive all", actionIntent) 1763 * .extend(new Notification.Action.WearableExtender() 1764 * .setAvailableOffline(false)) 1765 * .build();</pre> 1766 */ 1767 public static final class WearableExtender implements Extender { 1768 /** Notification action extra which contains wearable extensions */ 1769 private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS"; 1770 1771 // Keys within EXTRA_WEARABLE_EXTENSIONS for wearable options. 1772 private static final String KEY_FLAGS = "flags"; 1773 private static final String KEY_IN_PROGRESS_LABEL = "inProgressLabel"; 1774 private static final String KEY_CONFIRM_LABEL = "confirmLabel"; 1775 private static final String KEY_CANCEL_LABEL = "cancelLabel"; 1776 1777 // Flags bitwise-ored to mFlags 1778 private static final int FLAG_AVAILABLE_OFFLINE = 0x1; 1779 private static final int FLAG_HINT_LAUNCHES_ACTIVITY = 1 << 1; 1780 private static final int FLAG_HINT_DISPLAY_INLINE = 1 << 2; 1781 1782 // Default value for flags integer 1783 private static final int DEFAULT_FLAGS = FLAG_AVAILABLE_OFFLINE; 1784 1785 private int mFlags = DEFAULT_FLAGS; 1786 1787 private CharSequence mInProgressLabel; 1788 private CharSequence mConfirmLabel; 1789 private CharSequence mCancelLabel; 1790 1791 /** 1792 * Create a {@link android.app.Notification.Action.WearableExtender} with default 1793 * options. 1794 */ 1795 public WearableExtender() { 1796 } 1797 1798 /** 1799 * Create a {@link android.app.Notification.Action.WearableExtender} by reading 1800 * wearable options present in an existing notification action. 1801 * @param action the notification action to inspect. 1802 */ 1803 public WearableExtender(Action action) { 1804 Bundle wearableBundle = action.getExtras().getBundle(EXTRA_WEARABLE_EXTENSIONS); 1805 if (wearableBundle != null) { 1806 mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS); 1807 mInProgressLabel = wearableBundle.getCharSequence(KEY_IN_PROGRESS_LABEL); 1808 mConfirmLabel = wearableBundle.getCharSequence(KEY_CONFIRM_LABEL); 1809 mCancelLabel = wearableBundle.getCharSequence(KEY_CANCEL_LABEL); 1810 } 1811 } 1812 1813 /** 1814 * Apply wearable extensions to a notification action that is being built. This is 1815 * typically called by the {@link android.app.Notification.Action.Builder#extend} 1816 * method of {@link android.app.Notification.Action.Builder}. 1817 */ 1818 @Override 1819 public Action.Builder extend(Action.Builder builder) { 1820 Bundle wearableBundle = new Bundle(); 1821 1822 if (mFlags != DEFAULT_FLAGS) { 1823 wearableBundle.putInt(KEY_FLAGS, mFlags); 1824 } 1825 if (mInProgressLabel != null) { 1826 wearableBundle.putCharSequence(KEY_IN_PROGRESS_LABEL, mInProgressLabel); 1827 } 1828 if (mConfirmLabel != null) { 1829 wearableBundle.putCharSequence(KEY_CONFIRM_LABEL, mConfirmLabel); 1830 } 1831 if (mCancelLabel != null) { 1832 wearableBundle.putCharSequence(KEY_CANCEL_LABEL, mCancelLabel); 1833 } 1834 1835 builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle); 1836 return builder; 1837 } 1838 1839 @Override 1840 public WearableExtender clone() { 1841 WearableExtender that = new WearableExtender(); 1842 that.mFlags = this.mFlags; 1843 that.mInProgressLabel = this.mInProgressLabel; 1844 that.mConfirmLabel = this.mConfirmLabel; 1845 that.mCancelLabel = this.mCancelLabel; 1846 return that; 1847 } 1848 1849 /** 1850 * Set whether this action is available when the wearable device is not connected to 1851 * a companion device. The user can still trigger this action when the wearable device is 1852 * offline, but a visual hint will indicate that the action may not be available. 1853 * Defaults to true. 1854 */ 1855 public WearableExtender setAvailableOffline(boolean availableOffline) { 1856 setFlag(FLAG_AVAILABLE_OFFLINE, availableOffline); 1857 return this; 1858 } 1859 1860 /** 1861 * Get whether this action is available when the wearable device is not connected to 1862 * a companion device. The user can still trigger this action when the wearable device is 1863 * offline, but a visual hint will indicate that the action may not be available. 1864 * Defaults to true. 1865 */ 1866 public boolean isAvailableOffline() { 1867 return (mFlags & FLAG_AVAILABLE_OFFLINE) != 0; 1868 } 1869 1870 private void setFlag(int mask, boolean value) { 1871 if (value) { 1872 mFlags |= mask; 1873 } else { 1874 mFlags &= ~mask; 1875 } 1876 } 1877 1878 /** 1879 * Set a label to display while the wearable is preparing to automatically execute the 1880 * action. This is usually a 'ing' verb ending in ellipsis like "Sending..." 1881 * 1882 * @param label the label to display while the action is being prepared to execute 1883 * @return this object for method chaining 1884 */ 1885 @Deprecated 1886 public WearableExtender setInProgressLabel(CharSequence label) { 1887 mInProgressLabel = label; 1888 return this; 1889 } 1890 1891 /** 1892 * Get the label to display while the wearable is preparing to automatically execute 1893 * the action. This is usually a 'ing' verb ending in ellipsis like "Sending..." 1894 * 1895 * @return the label to display while the action is being prepared to execute 1896 */ 1897 @Deprecated 1898 public CharSequence getInProgressLabel() { 1899 return mInProgressLabel; 1900 } 1901 1902 /** 1903 * Set a label to display to confirm that the action should be executed. 1904 * This is usually an imperative verb like "Send". 1905 * 1906 * @param label the label to confirm the action should be executed 1907 * @return this object for method chaining 1908 */ 1909 @Deprecated 1910 public WearableExtender setConfirmLabel(CharSequence label) { 1911 mConfirmLabel = label; 1912 return this; 1913 } 1914 1915 /** 1916 * Get the label to display to confirm that the action should be executed. 1917 * This is usually an imperative verb like "Send". 1918 * 1919 * @return the label to confirm the action should be executed 1920 */ 1921 @Deprecated 1922 public CharSequence getConfirmLabel() { 1923 return mConfirmLabel; 1924 } 1925 1926 /** 1927 * Set a label to display to cancel the action. 1928 * This is usually an imperative verb, like "Cancel". 1929 * 1930 * @param label the label to display to cancel the action 1931 * @return this object for method chaining 1932 */ 1933 @Deprecated 1934 public WearableExtender setCancelLabel(CharSequence label) { 1935 mCancelLabel = label; 1936 return this; 1937 } 1938 1939 /** 1940 * Get the label to display to cancel the action. 1941 * This is usually an imperative verb like "Cancel". 1942 * 1943 * @return the label to display to cancel the action 1944 */ 1945 @Deprecated 1946 public CharSequence getCancelLabel() { 1947 return mCancelLabel; 1948 } 1949 1950 /** 1951 * Set a hint that this Action will launch an {@link Activity} directly, telling the 1952 * platform that it can generate the appropriate transitions. 1953 * @param hintLaunchesActivity {@code true} if the content intent will launch 1954 * an activity and transitions should be generated, false otherwise. 1955 * @return this object for method chaining 1956 */ 1957 public WearableExtender setHintLaunchesActivity( 1958 boolean hintLaunchesActivity) { 1959 setFlag(FLAG_HINT_LAUNCHES_ACTIVITY, hintLaunchesActivity); 1960 return this; 1961 } 1962 1963 /** 1964 * Get a hint that this Action will launch an {@link Activity} directly, telling the 1965 * platform that it can generate the appropriate transitions 1966 * @return {@code true} if the content intent will launch an activity and transitions 1967 * should be generated, false otherwise. The default value is {@code false} if this was 1968 * never set. 1969 */ 1970 public boolean getHintLaunchesActivity() { 1971 return (mFlags & FLAG_HINT_LAUNCHES_ACTIVITY) != 0; 1972 } 1973 1974 /** 1975 * Set a hint that this Action should be displayed inline. 1976 * 1977 * @param hintDisplayInline {@code true} if action should be displayed inline, false 1978 * otherwise 1979 * @return this object for method chaining 1980 */ 1981 public WearableExtender setHintDisplayActionInline( 1982 boolean hintDisplayInline) { 1983 setFlag(FLAG_HINT_DISPLAY_INLINE, hintDisplayInline); 1984 return this; 1985 } 1986 1987 /** 1988 * Get a hint that this Action should be displayed inline. 1989 * 1990 * @return {@code true} if the Action should be displayed inline, {@code false} 1991 * otherwise. The default value is {@code false} if this was never set. 1992 */ 1993 public boolean getHintDisplayActionInline() { 1994 return (mFlags & FLAG_HINT_DISPLAY_INLINE) != 0; 1995 } 1996 } 1997 1998 /** 1999 * Provides meaning to an {@link Action} that hints at what the associated 2000 * {@link PendingIntent} will do. For example, an {@link Action} with a 2001 * {@link PendingIntent} that replies to a text message notification may have the 2002 * {@link #SEMANTIC_ACTION_REPLY} {@code SemanticAction} set within it. 2003 * 2004 * @hide 2005 */ 2006 @IntDef(prefix = { "SEMANTIC_ACTION_" }, value = { 2007 SEMANTIC_ACTION_NONE, 2008 SEMANTIC_ACTION_REPLY, 2009 SEMANTIC_ACTION_MARK_AS_READ, 2010 SEMANTIC_ACTION_MARK_AS_UNREAD, 2011 SEMANTIC_ACTION_DELETE, 2012 SEMANTIC_ACTION_ARCHIVE, 2013 SEMANTIC_ACTION_MUTE, 2014 SEMANTIC_ACTION_UNMUTE, 2015 SEMANTIC_ACTION_THUMBS_UP, 2016 SEMANTIC_ACTION_THUMBS_DOWN, 2017 SEMANTIC_ACTION_CALL 2018 }) 2019 @Retention(RetentionPolicy.SOURCE) 2020 public @interface SemanticAction {} 2021 } 2022 2023 /** 2024 * Array of all {@link Action} structures attached to this notification by 2025 * {@link Builder#addAction(int, CharSequence, PendingIntent)}. Mostly useful for instances of 2026 * {@link android.service.notification.NotificationListenerService} that provide an alternative 2027 * interface for invoking actions. 2028 */ 2029 public Action[] actions; 2030 2031 /** 2032 * Replacement version of this notification whose content will be shown 2033 * in an insecure context such as atop a secure keyguard. See {@link #visibility} 2034 * and {@link #VISIBILITY_PUBLIC}. 2035 */ 2036 public Notification publicVersion; 2037 2038 /** 2039 * Constructs a Notification object with default values. 2040 * You might want to consider using {@link Builder} instead. 2041 */ 2042 public Notification() 2043 { 2044 this.when = System.currentTimeMillis(); 2045 this.creationTime = System.currentTimeMillis(); 2046 this.priority = PRIORITY_DEFAULT; 2047 } 2048 2049 /** 2050 * @hide 2051 */ 2052 public Notification(Context context, int icon, CharSequence tickerText, long when, 2053 CharSequence contentTitle, CharSequence contentText, Intent contentIntent) 2054 { 2055 new Builder(context) 2056 .setWhen(when) 2057 .setSmallIcon(icon) 2058 .setTicker(tickerText) 2059 .setContentTitle(contentTitle) 2060 .setContentText(contentText) 2061 .setContentIntent(PendingIntent.getActivity(context, 0, contentIntent, 0)) 2062 .buildInto(this); 2063 } 2064 2065 /** 2066 * Constructs a Notification object with the information needed to 2067 * have a status bar icon without the standard expanded view. 2068 * 2069 * @param icon The resource id of the icon to put in the status bar. 2070 * @param tickerText The text that flows by in the status bar when the notification first 2071 * activates. 2072 * @param when The time to show in the time field. In the System.currentTimeMillis 2073 * timebase. 2074 * 2075 * @deprecated Use {@link Builder} instead. 2076 */ 2077 @Deprecated 2078 public Notification(int icon, CharSequence tickerText, long when) 2079 { 2080 this.icon = icon; 2081 this.tickerText = tickerText; 2082 this.when = when; 2083 this.creationTime = System.currentTimeMillis(); 2084 } 2085 2086 /** 2087 * Unflatten the notification from a parcel. 2088 */ 2089 @SuppressWarnings("unchecked") 2090 public Notification(Parcel parcel) { 2091 // IMPORTANT: Add unmarshaling code in readFromParcel as the pending 2092 // intents in extras are always written as the last entry. 2093 readFromParcelImpl(parcel); 2094 // Must be read last! 2095 allPendingIntents = (ArraySet<PendingIntent>) parcel.readArraySet(null); 2096 } 2097 2098 private void readFromParcelImpl(Parcel parcel) 2099 { 2100 int version = parcel.readInt(); 2101 2102 mWhitelistToken = parcel.readStrongBinder(); 2103 if (mWhitelistToken == null) { 2104 mWhitelistToken = processWhitelistToken; 2105 } 2106 // Propagate this token to all pending intents that are unmarshalled from the parcel. 2107 parcel.setClassCookie(PendingIntent.class, mWhitelistToken); 2108 2109 when = parcel.readLong(); 2110 creationTime = parcel.readLong(); 2111 if (parcel.readInt() != 0) { 2112 mSmallIcon = Icon.CREATOR.createFromParcel(parcel); 2113 if (mSmallIcon.getType() == Icon.TYPE_RESOURCE) { 2114 icon = mSmallIcon.getResId(); 2115 } 2116 } 2117 number = parcel.readInt(); 2118 if (parcel.readInt() != 0) { 2119 contentIntent = PendingIntent.CREATOR.createFromParcel(parcel); 2120 } 2121 if (parcel.readInt() != 0) { 2122 deleteIntent = PendingIntent.CREATOR.createFromParcel(parcel); 2123 } 2124 if (parcel.readInt() != 0) { 2125 tickerText = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(parcel); 2126 } 2127 if (parcel.readInt() != 0) { 2128 tickerView = RemoteViews.CREATOR.createFromParcel(parcel); 2129 } 2130 if (parcel.readInt() != 0) { 2131 contentView = RemoteViews.CREATOR.createFromParcel(parcel); 2132 } 2133 if (parcel.readInt() != 0) { 2134 mLargeIcon = Icon.CREATOR.createFromParcel(parcel); 2135 } 2136 defaults = parcel.readInt(); 2137 flags = parcel.readInt(); 2138 if (parcel.readInt() != 0) { 2139 sound = Uri.CREATOR.createFromParcel(parcel); 2140 } 2141 2142 audioStreamType = parcel.readInt(); 2143 if (parcel.readInt() != 0) { 2144 audioAttributes = AudioAttributes.CREATOR.createFromParcel(parcel); 2145 } 2146 vibrate = parcel.createLongArray(); 2147 ledARGB = parcel.readInt(); 2148 ledOnMS = parcel.readInt(); 2149 ledOffMS = parcel.readInt(); 2150 iconLevel = parcel.readInt(); 2151 2152 if (parcel.readInt() != 0) { 2153 fullScreenIntent = PendingIntent.CREATOR.createFromParcel(parcel); 2154 } 2155 2156 priority = parcel.readInt(); 2157 2158 category = parcel.readString(); 2159 2160 mGroupKey = parcel.readString(); 2161 2162 mSortKey = parcel.readString(); 2163 2164 extras = Bundle.setDefusable(parcel.readBundle(), true); // may be null 2165 fixDuplicateExtras(); 2166 2167 actions = parcel.createTypedArray(Action.CREATOR); // may be null 2168 2169 if (parcel.readInt() != 0) { 2170 bigContentView = RemoteViews.CREATOR.createFromParcel(parcel); 2171 } 2172 2173 if (parcel.readInt() != 0) { 2174 headsUpContentView = RemoteViews.CREATOR.createFromParcel(parcel); 2175 } 2176 2177 visibility = parcel.readInt(); 2178 2179 if (parcel.readInt() != 0) { 2180 publicVersion = Notification.CREATOR.createFromParcel(parcel); 2181 } 2182 2183 color = parcel.readInt(); 2184 2185 if (parcel.readInt() != 0) { 2186 mChannelId = parcel.readString(); 2187 } 2188 mTimeout = parcel.readLong(); 2189 2190 if (parcel.readInt() != 0) { 2191 mShortcutId = parcel.readString(); 2192 } 2193 2194 mBadgeIcon = parcel.readInt(); 2195 2196 if (parcel.readInt() != 0) { 2197 mSettingsText = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(parcel); 2198 } 2199 2200 mGroupAlertBehavior = parcel.readInt(); 2201 } 2202 2203 @Override 2204 public Notification clone() { 2205 Notification that = new Notification(); 2206 cloneInto(that, true); 2207 return that; 2208 } 2209 2210 /** 2211 * Copy all (or if heavy is false, all except Bitmaps and RemoteViews) members 2212 * of this into that. 2213 * @hide 2214 */ 2215 public void cloneInto(Notification that, boolean heavy) { 2216 that.mWhitelistToken = this.mWhitelistToken; 2217 that.when = this.when; 2218 that.creationTime = this.creationTime; 2219 that.mSmallIcon = this.mSmallIcon; 2220 that.number = this.number; 2221 2222 // PendingIntents are global, so there's no reason (or way) to clone them. 2223 that.contentIntent = this.contentIntent; 2224 that.deleteIntent = this.deleteIntent; 2225 that.fullScreenIntent = this.fullScreenIntent; 2226 2227 if (this.tickerText != null) { 2228 that.tickerText = this.tickerText.toString(); 2229 } 2230 if (heavy && this.tickerView != null) { 2231 that.tickerView = this.tickerView.clone(); 2232 } 2233 if (heavy && this.contentView != null) { 2234 that.contentView = this.contentView.clone(); 2235 } 2236 if (heavy && this.mLargeIcon != null) { 2237 that.mLargeIcon = this.mLargeIcon; 2238 } 2239 that.iconLevel = this.iconLevel; 2240 that.sound = this.sound; // android.net.Uri is immutable 2241 that.audioStreamType = this.audioStreamType; 2242 if (this.audioAttributes != null) { 2243 that.audioAttributes = new AudioAttributes.Builder(this.audioAttributes).build(); 2244 } 2245 2246 final long[] vibrate = this.vibrate; 2247 if (vibrate != null) { 2248 final int N = vibrate.length; 2249 final long[] vib = that.vibrate = new long[N]; 2250 System.arraycopy(vibrate, 0, vib, 0, N); 2251 } 2252 2253 that.ledARGB = this.ledARGB; 2254 that.ledOnMS = this.ledOnMS; 2255 that.ledOffMS = this.ledOffMS; 2256 that.defaults = this.defaults; 2257 2258 that.flags = this.flags; 2259 2260 that.priority = this.priority; 2261 2262 that.category = this.category; 2263 2264 that.mGroupKey = this.mGroupKey; 2265 2266 that.mSortKey = this.mSortKey; 2267 2268 if (this.extras != null) { 2269 try { 2270 that.extras = new Bundle(this.extras); 2271 // will unparcel 2272 that.extras.size(); 2273 } catch (BadParcelableException e) { 2274 Log.e(TAG, "could not unparcel extras from notification: " + this, e); 2275 that.extras = null; 2276 } 2277 } 2278 2279 if (!ArrayUtils.isEmpty(allPendingIntents)) { 2280 that.allPendingIntents = new ArraySet<>(allPendingIntents); 2281 } 2282 2283 if (this.actions != null) { 2284 that.actions = new Action[this.actions.length]; 2285 for(int i=0; i<this.actions.length; i++) { 2286 if ( this.actions[i] != null) { 2287 that.actions[i] = this.actions[i].clone(); 2288 } 2289 } 2290 } 2291 2292 if (heavy && this.bigContentView != null) { 2293 that.bigContentView = this.bigContentView.clone(); 2294 } 2295 2296 if (heavy && this.headsUpContentView != null) { 2297 that.headsUpContentView = this.headsUpContentView.clone(); 2298 } 2299 2300 that.visibility = this.visibility; 2301 2302 if (this.publicVersion != null) { 2303 that.publicVersion = new Notification(); 2304 this.publicVersion.cloneInto(that.publicVersion, heavy); 2305 } 2306 2307 that.color = this.color; 2308 2309 that.mChannelId = this.mChannelId; 2310 that.mTimeout = this.mTimeout; 2311 that.mShortcutId = this.mShortcutId; 2312 that.mBadgeIcon = this.mBadgeIcon; 2313 that.mSettingsText = this.mSettingsText; 2314 that.mGroupAlertBehavior = this.mGroupAlertBehavior; 2315 2316 if (!heavy) { 2317 that.lightenPayload(); // will clean out extras 2318 } 2319 } 2320 2321 /** 2322 * Note all {@link Uri} that are referenced internally, with the expectation 2323 * that Uri permission grants will need to be issued to ensure the recipient 2324 * of this object is able to render its contents. 2325 * 2326 * @hide 2327 */ 2328 public void visitUris(@NonNull Consumer<Uri> visitor) { 2329 visitor.accept(sound); 2330 2331 if (tickerView != null) tickerView.visitUris(visitor); 2332 if (contentView != null) contentView.visitUris(visitor); 2333 if (bigContentView != null) bigContentView.visitUris(visitor); 2334 if (headsUpContentView != null) headsUpContentView.visitUris(visitor); 2335 2336 if (extras != null) { 2337 visitor.accept(extras.getParcelable(EXTRA_AUDIO_CONTENTS_URI)); 2338 visitor.accept(extras.getParcelable(EXTRA_BACKGROUND_IMAGE_URI)); 2339 } 2340 2341 if (MessagingStyle.class.equals(getNotificationStyle()) && extras != null) { 2342 final Parcelable[] messages = extras.getParcelableArray(EXTRA_MESSAGES); 2343 if (!ArrayUtils.isEmpty(messages)) { 2344 for (MessagingStyle.Message message : MessagingStyle.Message 2345 .getMessagesFromBundleArray(messages)) { 2346 visitor.accept(message.getDataUri()); 2347 } 2348 } 2349 2350 final Parcelable[] historic = extras.getParcelableArray(EXTRA_HISTORIC_MESSAGES); 2351 if (!ArrayUtils.isEmpty(historic)) { 2352 for (MessagingStyle.Message message : MessagingStyle.Message 2353 .getMessagesFromBundleArray(historic)) { 2354 visitor.accept(message.getDataUri()); 2355 } 2356 } 2357 } 2358 } 2359 2360 /** 2361 * Removes heavyweight parts of the Notification object for archival or for sending to 2362 * listeners when the full contents are not necessary. 2363 * @hide 2364 */ 2365 public final void lightenPayload() { 2366 tickerView = null; 2367 contentView = null; 2368 bigContentView = null; 2369 headsUpContentView = null; 2370 mLargeIcon = null; 2371 if (extras != null && !extras.isEmpty()) { 2372 final Set<String> keyset = extras.keySet(); 2373 final int N = keyset.size(); 2374 final String[] keys = keyset.toArray(new String[N]); 2375 for (int i=0; i<N; i++) { 2376 final String key = keys[i]; 2377 if (TvExtender.EXTRA_TV_EXTENDER.equals(key)) { 2378 continue; 2379 } 2380 final Object obj = extras.get(key); 2381 if (obj != null && 2382 ( obj instanceof Parcelable 2383 || obj instanceof Parcelable[] 2384 || obj instanceof SparseArray 2385 || obj instanceof ArrayList)) { 2386 extras.remove(key); 2387 } 2388 } 2389 } 2390 } 2391 2392 /** 2393 * Make sure this CharSequence is safe to put into a bundle, which basically 2394 * means it had better not be some custom Parcelable implementation. 2395 * @hide 2396 */ 2397 public static CharSequence safeCharSequence(CharSequence cs) { 2398 if (cs == null) return cs; 2399 if (cs.length() > MAX_CHARSEQUENCE_LENGTH) { 2400 cs = cs.subSequence(0, MAX_CHARSEQUENCE_LENGTH); 2401 } 2402 if (cs instanceof Parcelable) { 2403 Log.e(TAG, "warning: " + cs.getClass().getCanonicalName() 2404 + " instance is a custom Parcelable and not allowed in Notification"); 2405 return cs.toString(); 2406 } 2407 return removeTextSizeSpans(cs); 2408 } 2409 2410 private static CharSequence removeTextSizeSpans(CharSequence charSequence) { 2411 if (charSequence instanceof Spanned) { 2412 Spanned ss = (Spanned) charSequence; 2413 Object[] spans = ss.getSpans(0, ss.length(), Object.class); 2414 SpannableStringBuilder builder = new SpannableStringBuilder(ss.toString()); 2415 for (Object span : spans) { 2416 Object resultSpan = span; 2417 if (resultSpan instanceof CharacterStyle) { 2418 resultSpan = ((CharacterStyle) span).getUnderlying(); 2419 } 2420 if (resultSpan instanceof TextAppearanceSpan) { 2421 TextAppearanceSpan originalSpan = (TextAppearanceSpan) resultSpan; 2422 resultSpan = new TextAppearanceSpan( 2423 originalSpan.getFamily(), 2424 originalSpan.getTextStyle(), 2425 -1, 2426 originalSpan.getTextColor(), 2427 originalSpan.getLinkTextColor()); 2428 } else if (resultSpan instanceof RelativeSizeSpan 2429 || resultSpan instanceof AbsoluteSizeSpan) { 2430 continue; 2431 } else { 2432 resultSpan = span; 2433 } 2434 builder.setSpan(resultSpan, ss.getSpanStart(span), ss.getSpanEnd(span), 2435 ss.getSpanFlags(span)); 2436 } 2437 return builder; 2438 } 2439 return charSequence; 2440 } 2441 2442 public int describeContents() { 2443 return 0; 2444 } 2445 2446 /** 2447 * Flatten this notification into a parcel. 2448 */ 2449 public void writeToParcel(Parcel parcel, int flags) { 2450 // We need to mark all pending intents getting into the notification 2451 // system as being put there to later allow the notification ranker 2452 // to launch them and by doing so add the app to the battery saver white 2453 // list for a short period of time. The problem is that the system 2454 // cannot look into the extras as there may be parcelables there that 2455 // the platform does not know how to handle. To go around that we have 2456 // an explicit list of the pending intents in the extras bundle. 2457 final boolean collectPendingIntents = (allPendingIntents == null); 2458 if (collectPendingIntents) { 2459 PendingIntent.setOnMarshaledListener( 2460 (PendingIntent intent, Parcel out, int outFlags) -> { 2461 if (parcel == out) { 2462 if (allPendingIntents == null) { 2463 allPendingIntents = new ArraySet<>(); 2464 } 2465 allPendingIntents.add(intent); 2466 } 2467 }); 2468 } 2469 try { 2470 // IMPORTANT: Add marshaling code in writeToParcelImpl as we 2471 // want to intercept all pending events written to the parcel. 2472 writeToParcelImpl(parcel, flags); 2473 // Must be written last! 2474 parcel.writeArraySet(allPendingIntents); 2475 } finally { 2476 if (collectPendingIntents) { 2477 PendingIntent.setOnMarshaledListener(null); 2478 } 2479 } 2480 } 2481 2482 private void writeToParcelImpl(Parcel parcel, int flags) { 2483 parcel.writeInt(1); 2484 2485 parcel.writeStrongBinder(mWhitelistToken); 2486 parcel.writeLong(when); 2487 parcel.writeLong(creationTime); 2488 if (mSmallIcon == null && icon != 0) { 2489 // you snuck an icon in here without using the builder; let's try to keep it 2490 mSmallIcon = Icon.createWithResource("", icon); 2491 } 2492 if (mSmallIcon != null) { 2493 parcel.writeInt(1); 2494 mSmallIcon.writeToParcel(parcel, 0); 2495 } else { 2496 parcel.writeInt(0); 2497 } 2498 parcel.writeInt(number); 2499 if (contentIntent != null) { 2500 parcel.writeInt(1); 2501 contentIntent.writeToParcel(parcel, 0); 2502 } else { 2503 parcel.writeInt(0); 2504 } 2505 if (deleteIntent != null) { 2506 parcel.writeInt(1); 2507 deleteIntent.writeToParcel(parcel, 0); 2508 } else { 2509 parcel.writeInt(0); 2510 } 2511 if (tickerText != null) { 2512 parcel.writeInt(1); 2513 TextUtils.writeToParcel(tickerText, parcel, flags); 2514 } else { 2515 parcel.writeInt(0); 2516 } 2517 if (tickerView != null) { 2518 parcel.writeInt(1); 2519 tickerView.writeToParcel(parcel, 0); 2520 } else { 2521 parcel.writeInt(0); 2522 } 2523 if (contentView != null) { 2524 parcel.writeInt(1); 2525 contentView.writeToParcel(parcel, 0); 2526 } else { 2527 parcel.writeInt(0); 2528 } 2529 if (mLargeIcon == null && largeIcon != null) { 2530 // you snuck an icon in here without using the builder; let's try to keep it 2531 mLargeIcon = Icon.createWithBitmap(largeIcon); 2532 } 2533 if (mLargeIcon != null) { 2534 parcel.writeInt(1); 2535 mLargeIcon.writeToParcel(parcel, 0); 2536 } else { 2537 parcel.writeInt(0); 2538 } 2539 2540 parcel.writeInt(defaults); 2541 parcel.writeInt(this.flags); 2542 2543 if (sound != null) { 2544 parcel.writeInt(1); 2545 sound.writeToParcel(parcel, 0); 2546 } else { 2547 parcel.writeInt(0); 2548 } 2549 parcel.writeInt(audioStreamType); 2550 2551 if (audioAttributes != null) { 2552 parcel.writeInt(1); 2553 audioAttributes.writeToParcel(parcel, 0); 2554 } else { 2555 parcel.writeInt(0); 2556 } 2557 2558 parcel.writeLongArray(vibrate); 2559 parcel.writeInt(ledARGB); 2560 parcel.writeInt(ledOnMS); 2561 parcel.writeInt(ledOffMS); 2562 parcel.writeInt(iconLevel); 2563 2564 if (fullScreenIntent != null) { 2565 parcel.writeInt(1); 2566 fullScreenIntent.writeToParcel(parcel, 0); 2567 } else { 2568 parcel.writeInt(0); 2569 } 2570 2571 parcel.writeInt(priority); 2572 2573 parcel.writeString(category); 2574 2575 parcel.writeString(mGroupKey); 2576 2577 parcel.writeString(mSortKey); 2578 2579 parcel.writeBundle(extras); // null ok 2580 2581 parcel.writeTypedArray(actions, 0); // null ok 2582 2583 if (bigContentView != null) { 2584 parcel.writeInt(1); 2585 bigContentView.writeToParcel(parcel, 0); 2586 } else { 2587 parcel.writeInt(0); 2588 } 2589 2590 if (headsUpContentView != null) { 2591 parcel.writeInt(1); 2592 headsUpContentView.writeToParcel(parcel, 0); 2593 } else { 2594 parcel.writeInt(0); 2595 } 2596 2597 parcel.writeInt(visibility); 2598 2599 if (publicVersion != null) { 2600 parcel.writeInt(1); 2601 publicVersion.writeToParcel(parcel, 0); 2602 } else { 2603 parcel.writeInt(0); 2604 } 2605 2606 parcel.writeInt(color); 2607 2608 if (mChannelId != null) { 2609 parcel.writeInt(1); 2610 parcel.writeString(mChannelId); 2611 } else { 2612 parcel.writeInt(0); 2613 } 2614 parcel.writeLong(mTimeout); 2615 2616 if (mShortcutId != null) { 2617 parcel.writeInt(1); 2618 parcel.writeString(mShortcutId); 2619 } else { 2620 parcel.writeInt(0); 2621 } 2622 2623 parcel.writeInt(mBadgeIcon); 2624 2625 if (mSettingsText != null) { 2626 parcel.writeInt(1); 2627 TextUtils.writeToParcel(mSettingsText, parcel, flags); 2628 } else { 2629 parcel.writeInt(0); 2630 } 2631 2632 parcel.writeInt(mGroupAlertBehavior); 2633 2634 // mUsesStandardHeader is not written because it should be recomputed in listeners 2635 } 2636 2637 /** 2638 * Parcelable.Creator that instantiates Notification objects 2639 */ 2640 public static final Parcelable.Creator<Notification> CREATOR 2641 = new Parcelable.Creator<Notification>() 2642 { 2643 public Notification createFromParcel(Parcel parcel) 2644 { 2645 return new Notification(parcel); 2646 } 2647 2648 public Notification[] newArray(int size) 2649 { 2650 return new Notification[size]; 2651 } 2652 }; 2653 2654 /** 2655 * @hide 2656 */ 2657 public static boolean areActionsVisiblyDifferent(Notification first, Notification second) { 2658 Notification.Action[] firstAs = first.actions; 2659 Notification.Action[] secondAs = second.actions; 2660 if (firstAs == null && secondAs != null || firstAs != null && secondAs == null) { 2661 return true; 2662 } 2663 if (firstAs != null && secondAs != null) { 2664 if (firstAs.length != secondAs.length) { 2665 return true; 2666 } 2667 for (int i = 0; i < firstAs.length; i++) { 2668 if (!Objects.equals(firstAs[i].title, secondAs[i].title)) { 2669 return true; 2670 } 2671 RemoteInput[] firstRs = firstAs[i].getRemoteInputs(); 2672 RemoteInput[] secondRs = secondAs[i].getRemoteInputs(); 2673 if (firstRs == null) { 2674 firstRs = new RemoteInput[0]; 2675 } 2676 if (secondRs == null) { 2677 secondRs = new RemoteInput[0]; 2678 } 2679 if (firstRs.length != secondRs.length) { 2680 return true; 2681 } 2682 for (int j = 0; j < firstRs.length; j++) { 2683 if (!Objects.equals(firstRs[j].getLabel(), secondRs[j].getLabel())) { 2684 return true; 2685 } 2686 CharSequence[] firstCs = firstRs[j].getChoices(); 2687 CharSequence[] secondCs = secondRs[j].getChoices(); 2688 if (firstCs == null) { 2689 firstCs = new CharSequence[0]; 2690 } 2691 if (secondCs == null) { 2692 secondCs = new CharSequence[0]; 2693 } 2694 if (firstCs.length != secondCs.length) { 2695 return true; 2696 } 2697 for (int k = 0; k < firstCs.length; k++) { 2698 if (!Objects.equals(firstCs[k], secondCs[k])) { 2699 return true; 2700 } 2701 } 2702 } 2703 } 2704 } 2705 return false; 2706 } 2707 2708 /** 2709 * @hide 2710 */ 2711 public static boolean areStyledNotificationsVisiblyDifferent(Builder first, Builder second) { 2712 if (first.getStyle() == null) { 2713 return second.getStyle() != null; 2714 } 2715 if (second.getStyle() == null) { 2716 return true; 2717 } 2718 return first.getStyle().areNotificationsVisiblyDifferent(second.getStyle()); 2719 } 2720 2721 /** 2722 * @hide 2723 */ 2724 public static boolean areRemoteViewsChanged(Builder first, Builder second) { 2725 if (!Objects.equals(first.usesStandardHeader(), second.usesStandardHeader())) { 2726 return true; 2727 } 2728 2729 if (areRemoteViewsChanged(first.mN.contentView, second.mN.contentView)) { 2730 return true; 2731 } 2732 if (areRemoteViewsChanged(first.mN.bigContentView, second.mN.bigContentView)) { 2733 return true; 2734 } 2735 if (areRemoteViewsChanged(first.mN.headsUpContentView, second.mN.headsUpContentView)) { 2736 return true; 2737 } 2738 2739 return false; 2740 } 2741 2742 private static boolean areRemoteViewsChanged(RemoteViews first, RemoteViews second) { 2743 if (first == null && second == null) { 2744 return false; 2745 } 2746 if (first == null && second != null || first != null && second == null) { 2747 return true; 2748 } 2749 2750 if (!Objects.equals(first.getLayoutId(), second.getLayoutId())) { 2751 return true; 2752 } 2753 2754 if (!Objects.equals(first.getSequenceNumber(), second.getSequenceNumber())) { 2755 return true; 2756 } 2757 2758 return false; 2759 } 2760 2761 /** 2762 * Parcelling creates multiple copies of objects in {@code extras}. Fix them. 2763 * <p> 2764 * For backwards compatibility {@code extras} holds some references to "real" member data such 2765 * as {@link getLargeIcon()} which is mirrored by {@link #EXTRA_LARGE_ICON}. This is mostly 2766 * fine as long as the object stays in one process. 2767 * <p> 2768 * However, once the notification goes into a parcel each reference gets marshalled separately, 2769 * wasting memory. Especially with large images on Auto and TV, this is worth fixing. 2770 */ 2771 private void fixDuplicateExtras() { 2772 if (extras != null) { 2773 fixDuplicateExtra(mSmallIcon, EXTRA_SMALL_ICON); 2774 fixDuplicateExtra(mLargeIcon, EXTRA_LARGE_ICON); 2775 } 2776 } 2777 2778 /** 2779 * If we find an extra that's exactly the same as one of the "real" fields but refers to a 2780 * separate object, replace it with the field's version to avoid holding duplicate copies. 2781 */ 2782 private void fixDuplicateExtra(@Nullable Parcelable original, @NonNull String extraName) { 2783 if (original != null && extras.getParcelable(extraName) != null) { 2784 extras.putParcelable(extraName, original); 2785 } 2786 } 2787 2788 /** 2789 * Sets the {@link #contentView} field to be a view with the standard "Latest Event" 2790 * layout. 2791 * 2792 * <p>Uses the {@link #icon} and {@link #when} fields to set the icon and time fields 2793 * in the view.</p> 2794 * @param context The context for your application / activity. 2795 * @param contentTitle The title that goes in the expanded entry. 2796 * @param contentText The text that goes in the expanded entry. 2797 * @param contentIntent The intent to launch when the user clicks the expanded notification. 2798 * If this is an activity, it must include the 2799 * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires 2800 * that you take care of task management as described in the 2801 * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back 2802 * Stack</a> document. 2803 * 2804 * @deprecated Use {@link Builder} instead. 2805 * @removed 2806 */ 2807 @Deprecated 2808 public void setLatestEventInfo(Context context, 2809 CharSequence contentTitle, CharSequence contentText, PendingIntent contentIntent) { 2810 if (context.getApplicationInfo().targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1){ 2811 Log.e(TAG, "setLatestEventInfo() is deprecated and you should feel deprecated.", 2812 new Throwable()); 2813 } 2814 2815 if (context.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N) { 2816 extras.putBoolean(EXTRA_SHOW_WHEN, true); 2817 } 2818 2819 // ensure that any information already set directly is preserved 2820 final Notification.Builder builder = new Notification.Builder(context, this); 2821 2822 // now apply the latestEventInfo fields 2823 if (contentTitle != null) { 2824 builder.setContentTitle(contentTitle); 2825 } 2826 if (contentText != null) { 2827 builder.setContentText(contentText); 2828 } 2829 builder.setContentIntent(contentIntent); 2830 2831 builder.build(); // callers expect this notification to be ready to use 2832 } 2833 2834 /** 2835 * @hide 2836 */ 2837 public static void addFieldsFromContext(Context context, Notification notification) { 2838 addFieldsFromContext(context.getApplicationInfo(), notification); 2839 } 2840 2841 /** 2842 * @hide 2843 */ 2844 public static void addFieldsFromContext(ApplicationInfo ai, Notification notification) { 2845 notification.extras.putParcelable(EXTRA_BUILDER_APPLICATION_INFO, ai); 2846 } 2847 2848 /** 2849 * @hide 2850 */ 2851 public void writeToProto(ProtoOutputStream proto, long fieldId) { 2852 long token = proto.start(fieldId); 2853 proto.write(NotificationProto.CHANNEL_ID, getChannelId()); 2854 proto.write(NotificationProto.HAS_TICKER_TEXT, this.tickerText != null); 2855 proto.write(NotificationProto.FLAGS, this.flags); 2856 proto.write(NotificationProto.COLOR, this.color); 2857 proto.write(NotificationProto.CATEGORY, this.category); 2858 proto.write(NotificationProto.GROUP_KEY, this.mGroupKey); 2859 proto.write(NotificationProto.SORT_KEY, this.mSortKey); 2860 if (this.actions != null) { 2861 proto.write(NotificationProto.ACTION_LENGTH, this.actions.length); 2862 } 2863 if (this.visibility >= VISIBILITY_SECRET && this.visibility <= VISIBILITY_PUBLIC) { 2864 proto.write(NotificationProto.VISIBILITY, this.visibility); 2865 } 2866 if (publicVersion != null) { 2867 publicVersion.writeToProto(proto, NotificationProto.PUBLIC_VERSION); 2868 } 2869 proto.end(token); 2870 } 2871 2872 @Override 2873 public String toString() { 2874 StringBuilder sb = new StringBuilder(); 2875 sb.append("Notification(channel="); 2876 sb.append(getChannelId()); 2877 sb.append(" pri="); 2878 sb.append(priority); 2879 sb.append(" contentView="); 2880 if (contentView != null) { 2881 sb.append(contentView.getPackage()); 2882 sb.append("/0x"); 2883 sb.append(Integer.toHexString(contentView.getLayoutId())); 2884 } else { 2885 sb.append("null"); 2886 } 2887 sb.append(" vibrate="); 2888 if ((this.defaults & DEFAULT_VIBRATE) != 0) { 2889 sb.append("default"); 2890 } else if (this.vibrate != null) { 2891 int N = this.vibrate.length-1; 2892 sb.append("["); 2893 for (int i=0; i<N; i++) { 2894 sb.append(this.vibrate[i]); 2895 sb.append(','); 2896 } 2897 if (N != -1) { 2898 sb.append(this.vibrate[N]); 2899 } 2900 sb.append("]"); 2901 } else { 2902 sb.append("null"); 2903 } 2904 sb.append(" sound="); 2905 if ((this.defaults & DEFAULT_SOUND) != 0) { 2906 sb.append("default"); 2907 } else if (this.sound != null) { 2908 sb.append(this.sound.toString()); 2909 } else { 2910 sb.append("null"); 2911 } 2912 if (this.tickerText != null) { 2913 sb.append(" tick"); 2914 } 2915 sb.append(" defaults=0x"); 2916 sb.append(Integer.toHexString(this.defaults)); 2917 sb.append(" flags=0x"); 2918 sb.append(Integer.toHexString(this.flags)); 2919 sb.append(String.format(" color=0x%08x", this.color)); 2920 if (this.category != null) { 2921 sb.append(" category="); 2922 sb.append(this.category); 2923 } 2924 if (this.mGroupKey != null) { 2925 sb.append(" groupKey="); 2926 sb.append(this.mGroupKey); 2927 } 2928 if (this.mSortKey != null) { 2929 sb.append(" sortKey="); 2930 sb.append(this.mSortKey); 2931 } 2932 if (actions != null) { 2933 sb.append(" actions="); 2934 sb.append(actions.length); 2935 } 2936 sb.append(" vis="); 2937 sb.append(visibilityToString(this.visibility)); 2938 if (this.publicVersion != null) { 2939 sb.append(" publicVersion="); 2940 sb.append(publicVersion.toString()); 2941 } 2942 sb.append(")"); 2943 return sb.toString(); 2944 } 2945 2946 /** 2947 * {@hide} 2948 */ 2949 public static String visibilityToString(int vis) { 2950 switch (vis) { 2951 case VISIBILITY_PRIVATE: 2952 return "PRIVATE"; 2953 case VISIBILITY_PUBLIC: 2954 return "PUBLIC"; 2955 case VISIBILITY_SECRET: 2956 return "SECRET"; 2957 default: 2958 return "UNKNOWN(" + String.valueOf(vis) + ")"; 2959 } 2960 } 2961 2962 /** 2963 * {@hide} 2964 */ 2965 public static String priorityToString(@Priority int pri) { 2966 switch (pri) { 2967 case PRIORITY_MIN: 2968 return "MIN"; 2969 case PRIORITY_LOW: 2970 return "LOW"; 2971 case PRIORITY_DEFAULT: 2972 return "DEFAULT"; 2973 case PRIORITY_HIGH: 2974 return "HIGH"; 2975 case PRIORITY_MAX: 2976 return "MAX"; 2977 default: 2978 return "UNKNOWN(" + String.valueOf(pri) + ")"; 2979 } 2980 } 2981 2982 /** 2983 * @hide 2984 */ 2985 public boolean hasCompletedProgress() { 2986 // not a progress notification; can't be complete 2987 if (!extras.containsKey(EXTRA_PROGRESS) 2988 || !extras.containsKey(EXTRA_PROGRESS_MAX)) { 2989 return false; 2990 } 2991 // many apps use max 0 for 'indeterminate'; not complete 2992 if (extras.getInt(EXTRA_PROGRESS_MAX) == 0) { 2993 return false; 2994 } 2995 return extras.getInt(EXTRA_PROGRESS) == extras.getInt(EXTRA_PROGRESS_MAX); 2996 } 2997 2998 /** @removed */ 2999 @Deprecated 3000 public String getChannel() { 3001 return mChannelId; 3002 } 3003 3004 /** 3005 * Returns the id of the channel this notification posts to. 3006 */ 3007 public String getChannelId() { 3008 return mChannelId; 3009 } 3010 3011 /** @removed */ 3012 @Deprecated 3013 public long getTimeout() { 3014 return mTimeout; 3015 } 3016 3017 /** 3018 * Returns the duration from posting after which this notification should be canceled by the 3019 * system, if it's not canceled already. 3020 */ 3021 public long getTimeoutAfter() { 3022 return mTimeout; 3023 } 3024 3025 /** 3026 * Returns what icon should be shown for this notification if it is being displayed in a 3027 * Launcher that supports badging. Will be one of {@link #BADGE_ICON_NONE}, 3028 * {@link #BADGE_ICON_SMALL}, or {@link #BADGE_ICON_LARGE}. 3029 */ 3030 public int getBadgeIconType() { 3031 return mBadgeIcon; 3032 } 3033 3034 /** 3035 * Returns the {@link ShortcutInfo#getId() id} that this notification supersedes, if any. 3036 * 3037 * <p>Used by some Launchers that display notification content to hide shortcuts that duplicate 3038 * notifications. 3039 */ 3040 public String getShortcutId() { 3041 return mShortcutId; 3042 } 3043 3044 3045 /** 3046 * Returns the settings text provided to {@link Builder#setSettingsText(CharSequence)}. 3047 */ 3048 public CharSequence getSettingsText() { 3049 return mSettingsText; 3050 } 3051 3052 /** 3053 * Returns which type of notifications in a group are responsible for audibly alerting the 3054 * user. See {@link #GROUP_ALERT_ALL}, {@link #GROUP_ALERT_CHILDREN}, 3055 * {@link #GROUP_ALERT_SUMMARY}. 3056 */ 3057 public @GroupAlertBehavior int getGroupAlertBehavior() { 3058 return mGroupAlertBehavior; 3059 } 3060 3061 /** 3062 * The small icon representing this notification in the status bar and content view. 3063 * 3064 * @return the small icon representing this notification. 3065 * 3066 * @see Builder#getSmallIcon() 3067 * @see Builder#setSmallIcon(Icon) 3068 */ 3069 public Icon getSmallIcon() { 3070 return mSmallIcon; 3071 } 3072 3073 /** 3074 * Used when notifying to clean up legacy small icons. 3075 * @hide 3076 */ 3077 public void setSmallIcon(Icon icon) { 3078 mSmallIcon = icon; 3079 } 3080 3081 /** 3082 * The large icon shown in this notification's content view. 3083 * @see Builder#getLargeIcon() 3084 * @see Builder#setLargeIcon(Icon) 3085 */ 3086 public Icon getLargeIcon() { 3087 return mLargeIcon; 3088 } 3089 3090 /** 3091 * @hide 3092 */ 3093 public boolean isGroupSummary() { 3094 return mGroupKey != null && (flags & FLAG_GROUP_SUMMARY) != 0; 3095 } 3096 3097 /** 3098 * @hide 3099 */ 3100 public boolean isGroupChild() { 3101 return mGroupKey != null && (flags & FLAG_GROUP_SUMMARY) == 0; 3102 } 3103 3104 /** 3105 * @hide 3106 */ 3107 public boolean suppressAlertingDueToGrouping() { 3108 if (isGroupSummary() 3109 && getGroupAlertBehavior() == Notification.GROUP_ALERT_CHILDREN) { 3110 return true; 3111 } else if (isGroupChild() 3112 && getGroupAlertBehavior() == Notification.GROUP_ALERT_SUMMARY) { 3113 return true; 3114 } 3115 return false; 3116 } 3117 3118 /** 3119 * Builder class for {@link Notification} objects. 3120 * 3121 * Provides a convenient way to set the various fields of a {@link Notification} and generate 3122 * content views using the platform's notification layout template. If your app supports 3123 * versions of Android as old as API level 4, you can instead use 3124 * {@link android.support.v4.app.NotificationCompat.Builder NotificationCompat.Builder}, 3125 * available in the <a href="{@docRoot}tools/extras/support-library.html">Android Support 3126 * library</a>. 3127 * 3128 * <p>Example: 3129 * 3130 * <pre class="prettyprint"> 3131 * Notification noti = new Notification.Builder(mContext) 3132 * .setContentTitle("New mail from " + sender.toString()) 3133 * .setContentText(subject) 3134 * .setSmallIcon(R.drawable.new_mail) 3135 * .setLargeIcon(aBitmap) 3136 * .build(); 3137 * </pre> 3138 */ 3139 public static class Builder { 3140 /** 3141 * @hide 3142 */ 3143 public static final String EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT = 3144 "android.rebuild.contentViewActionCount"; 3145 /** 3146 * @hide 3147 */ 3148 public static final String EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT 3149 = "android.rebuild.bigViewActionCount"; 3150 /** 3151 * @hide 3152 */ 3153 public static final String EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT 3154 = "android.rebuild.hudViewActionCount"; 3155 3156 private static final int MAX_ACTION_BUTTONS = 3; 3157 3158 private static final boolean USE_ONLY_TITLE_IN_LOW_PRIORITY_SUMMARY = 3159 SystemProperties.getBoolean("notifications.only_title", true); 3160 3161 /** 3162 * The lightness difference that has to be added to the primary text color to obtain the 3163 * secondary text color when the background is light. 3164 */ 3165 private static final int LIGHTNESS_TEXT_DIFFERENCE_LIGHT = 20; 3166 3167 /** 3168 * The lightness difference that has to be added to the primary text color to obtain the 3169 * secondary text color when the background is dark. 3170 * A bit less then the above value, since it looks better on dark backgrounds. 3171 */ 3172 private static final int LIGHTNESS_TEXT_DIFFERENCE_DARK = -10; 3173 3174 private Context mContext; 3175 private Notification mN; 3176 private Bundle mUserExtras = new Bundle(); 3177 private Style mStyle; 3178 private ArrayList<Action> mActions = new ArrayList<Action>(MAX_ACTION_BUTTONS); 3179 private ArrayList<Person> mPersonList = new ArrayList<>(); 3180 private NotificationColorUtil mColorUtil; 3181 private boolean mIsLegacy; 3182 private boolean mIsLegacyInitialized; 3183 3184 /** 3185 * Caches a contrast-enhanced version of {@link #mCachedContrastColorIsFor}. 3186 */ 3187 private int mCachedContrastColor = COLOR_INVALID; 3188 private int mCachedContrastColorIsFor = COLOR_INVALID; 3189 /** 3190 * Caches a ambient version of {@link #mCachedAmbientColorIsFor}. 3191 */ 3192 private int mCachedAmbientColor = COLOR_INVALID; 3193 private int mCachedAmbientColorIsFor = COLOR_INVALID; 3194 /** 3195 * A neutral color color that can be used for icons. 3196 */ 3197 private int mNeutralColor = COLOR_INVALID; 3198 3199 /** 3200 * Caches an instance of StandardTemplateParams. Note that this may have been used before, 3201 * so make sure to call {@link StandardTemplateParams#reset()} before using it. 3202 */ 3203 StandardTemplateParams mParams = new StandardTemplateParams(); 3204 private int mTextColorsAreForBackground = COLOR_INVALID; 3205 private int mPrimaryTextColor = COLOR_INVALID; 3206 private int mSecondaryTextColor = COLOR_INVALID; 3207 private int mBackgroundColor = COLOR_INVALID; 3208 private int mForegroundColor = COLOR_INVALID; 3209 /** 3210 * A temporary location where actions are stored. If != null the view originally has action 3211 * but doesn't have any for this inflation. 3212 */ 3213 private ArrayList<Action> mOriginalActions; 3214 private boolean mRebuildStyledRemoteViews; 3215 3216 private boolean mTintActionButtons; 3217 private boolean mInNightMode; 3218 3219 /** 3220 * Constructs a new Builder with the defaults: 3221 * 3222 * @param context 3223 * A {@link Context} that will be used by the Builder to construct the 3224 * RemoteViews. The Context will not be held past the lifetime of this Builder 3225 * object. 3226 * @param channelId 3227 * The constructed Notification will be posted on this 3228 * {@link NotificationChannel}. To use a NotificationChannel, it must first be 3229 * created using {@link NotificationManager#createNotificationChannel}. 3230 */ 3231 public Builder(Context context, String channelId) { 3232 this(context, (Notification) null); 3233 mN.mChannelId = channelId; 3234 } 3235 3236 /** 3237 * @deprecated use {@link Notification.Builder#Notification.Builder(Context, String)} 3238 * instead. All posted Notifications must specify a NotificationChannel Id. 3239 */ 3240 @Deprecated 3241 public Builder(Context context) { 3242 this(context, (Notification) null); 3243 } 3244 3245 /** 3246 * @hide 3247 */ 3248 public Builder(Context context, Notification toAdopt) { 3249 mContext = context; 3250 Resources res = mContext.getResources(); 3251 mTintActionButtons = res.getBoolean(R.bool.config_tintNotificationActionButtons); 3252 3253 if (res.getBoolean(R.bool.config_enableNightMode)) { 3254 Configuration currentConfig = res.getConfiguration(); 3255 mInNightMode = (currentConfig.uiMode & Configuration.UI_MODE_NIGHT_MASK) 3256 == Configuration.UI_MODE_NIGHT_YES; 3257 } 3258 3259 if (toAdopt == null) { 3260 mN = new Notification(); 3261 if (context.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N) { 3262 mN.extras.putBoolean(EXTRA_SHOW_WHEN, true); 3263 } 3264 mN.priority = PRIORITY_DEFAULT; 3265 mN.visibility = VISIBILITY_PRIVATE; 3266 } else { 3267 mN = toAdopt; 3268 if (mN.actions != null) { 3269 Collections.addAll(mActions, mN.actions); 3270 } 3271 3272 if (mN.extras.containsKey(EXTRA_PEOPLE_LIST)) { 3273 ArrayList<Person> people = mN.extras.getParcelableArrayList(EXTRA_PEOPLE_LIST); 3274 mPersonList.addAll(people); 3275 } 3276 3277 if (mN.getSmallIcon() == null && mN.icon != 0) { 3278 setSmallIcon(mN.icon); 3279 } 3280 3281 if (mN.getLargeIcon() == null && mN.largeIcon != null) { 3282 setLargeIcon(mN.largeIcon); 3283 } 3284 3285 String templateClass = mN.extras.getString(EXTRA_TEMPLATE); 3286 if (!TextUtils.isEmpty(templateClass)) { 3287 final Class<? extends Style> styleClass 3288 = getNotificationStyleClass(templateClass); 3289 if (styleClass == null) { 3290 Log.d(TAG, "Unknown style class: " + templateClass); 3291 } else { 3292 try { 3293 final Constructor<? extends Style> ctor = 3294 styleClass.getDeclaredConstructor(); 3295 ctor.setAccessible(true); 3296 final Style style = ctor.newInstance(); 3297 style.restoreFromExtras(mN.extras); 3298 3299 if (style != null) { 3300 setStyle(style); 3301 } 3302 } catch (Throwable t) { 3303 Log.e(TAG, "Could not create Style", t); 3304 } 3305 } 3306 } 3307 3308 } 3309 } 3310 3311 private NotificationColorUtil getColorUtil() { 3312 if (mColorUtil == null) { 3313 mColorUtil = NotificationColorUtil.getInstance(mContext); 3314 } 3315 return mColorUtil; 3316 } 3317 3318 /** 3319 * If this notification is duplicative of a Launcher shortcut, sets the 3320 * {@link ShortcutInfo#getId() id} of the shortcut, in case the Launcher wants to hide 3321 * the shortcut. 3322 * 3323 * This field will be ignored by Launchers that don't support badging, don't show 3324 * notification content, or don't show {@link android.content.pm.ShortcutManager shortcuts}. 3325 * 3326 * @param shortcutId the {@link ShortcutInfo#getId() id} of the shortcut this notification 3327 * supersedes 3328 */ 3329 public Builder setShortcutId(String shortcutId) { 3330 mN.mShortcutId = shortcutId; 3331 return this; 3332 } 3333 3334 /** 3335 * Sets which icon to display as a badge for this notification. 3336 * 3337 * Must be one of {@link #BADGE_ICON_NONE}, {@link #BADGE_ICON_SMALL}, 3338 * {@link #BADGE_ICON_LARGE}. 3339 * 3340 * Note: This value might be ignored, for launchers that don't support badge icons. 3341 */ 3342 public Builder setBadgeIconType(int icon) { 3343 mN.mBadgeIcon = icon; 3344 return this; 3345 } 3346 3347 /** 3348 * Sets the group alert behavior for this notification. Use this method to mute this 3349 * notification if alerts for this notification's group should be handled by a different 3350 * notification. This is only applicable for notifications that belong to a 3351 * {@link #setGroup(String) group}. This must be called on all notifications you want to 3352 * mute. For example, if you want only the summary of your group to make noise, all 3353 * children in the group should have the group alert behavior {@link #GROUP_ALERT_SUMMARY}. 3354 * 3355 * <p> The default value is {@link #GROUP_ALERT_ALL}.</p> 3356 */ 3357 public Builder setGroupAlertBehavior(@GroupAlertBehavior int groupAlertBehavior) { 3358 mN.mGroupAlertBehavior = groupAlertBehavior; 3359 return this; 3360 } 3361 3362 /** @removed */ 3363 @Deprecated 3364 public Builder setChannel(String channelId) { 3365 mN.mChannelId = channelId; 3366 return this; 3367 } 3368 3369 /** 3370 * Specifies the channel the notification should be delivered on. 3371 */ 3372 public Builder setChannelId(String channelId) { 3373 mN.mChannelId = channelId; 3374 return this; 3375 } 3376 3377 /** @removed */ 3378 @Deprecated 3379 public Builder setTimeout(long durationMs) { 3380 mN.mTimeout = durationMs; 3381 return this; 3382 } 3383 3384 /** 3385 * Specifies a duration in milliseconds after which this notification should be canceled, 3386 * if it is not already canceled. 3387 */ 3388 public Builder setTimeoutAfter(long durationMs) { 3389 mN.mTimeout = durationMs; 3390 return this; 3391 } 3392 3393 /** 3394 * Add a timestamp pertaining to the notification (usually the time the event occurred). 3395 * 3396 * For apps targeting {@link android.os.Build.VERSION_CODES#N} and above, this time is not 3397 * shown anymore by default and must be opted into by using 3398 * {@link android.app.Notification.Builder#setShowWhen(boolean)} 3399 * 3400 * @see Notification#when 3401 */ 3402 public Builder setWhen(long when) { 3403 mN.when = when; 3404 return this; 3405 } 3406 3407 /** 3408 * Control whether the timestamp set with {@link #setWhen(long) setWhen} is shown 3409 * in the content view. 3410 * For apps targeting {@link android.os.Build.VERSION_CODES#N} and above, this defaults to 3411 * {@code false}. For earlier apps, the default is {@code true}. 3412 */ 3413 public Builder setShowWhen(boolean show) { 3414 mN.extras.putBoolean(EXTRA_SHOW_WHEN, show); 3415 return this; 3416 } 3417 3418 /** 3419 * Show the {@link Notification#when} field as a stopwatch. 3420 * 3421 * Instead of presenting <code>when</code> as a timestamp, the notification will show an 3422 * automatically updating display of the minutes and seconds since <code>when</code>. 3423 * 3424 * Useful when showing an elapsed time (like an ongoing phone call). 3425 * 3426 * The counter can also be set to count down to <code>when</code> when using 3427 * {@link #setChronometerCountDown(boolean)}. 3428 * 3429 * @see android.widget.Chronometer 3430 * @see Notification#when 3431 * @see #setChronometerCountDown(boolean) 3432 */ 3433 public Builder setUsesChronometer(boolean b) { 3434 mN.extras.putBoolean(EXTRA_SHOW_CHRONOMETER, b); 3435 return this; 3436 } 3437 3438 /** 3439 * Sets the Chronometer to count down instead of counting up. 3440 * 3441 * <p>This is only relevant if {@link #setUsesChronometer(boolean)} has been set to true. 3442 * If it isn't set the chronometer will count up. 3443 * 3444 * @see #setUsesChronometer(boolean) 3445 */ 3446 public Builder setChronometerCountDown(boolean countDown) { 3447 mN.extras.putBoolean(EXTRA_CHRONOMETER_COUNT_DOWN, countDown); 3448 return this; 3449 } 3450 3451 /** 3452 * Set the small icon resource, which will be used to represent the notification in the 3453 * status bar. 3454 * 3455 3456 * The platform template for the expanded view will draw this icon in the left, unless a 3457 * {@link #setLargeIcon(Bitmap) large icon} has also been specified, in which case the small 3458 * icon will be moved to the right-hand side. 3459 * 3460 3461 * @param icon 3462 * A resource ID in the application's package of the drawable to use. 3463 * @see Notification#icon 3464 */ 3465 public Builder setSmallIcon(@DrawableRes int icon) { 3466 return setSmallIcon(icon != 0 3467 ? Icon.createWithResource(mContext, icon) 3468 : null); 3469 } 3470 3471 /** 3472 * A variant of {@link #setSmallIcon(int) setSmallIcon(int)} that takes an additional 3473 * level parameter for when the icon is a {@link android.graphics.drawable.LevelListDrawable 3474 * LevelListDrawable}. 3475 * 3476 * @param icon A resource ID in the application's package of the drawable to use. 3477 * @param level The level to use for the icon. 3478 * 3479 * @see Notification#icon 3480 * @see Notification#iconLevel 3481 */ 3482 public Builder setSmallIcon(@DrawableRes int icon, int level) { 3483 mN.iconLevel = level; 3484 return setSmallIcon(icon); 3485 } 3486 3487 /** 3488 * Set the small icon, which will be used to represent the notification in the 3489 * status bar and content view (unless overriden there by a 3490 * {@link #setLargeIcon(Bitmap) large icon}). 3491 * 3492 * @param icon An Icon object to use. 3493 * @see Notification#icon 3494 */ 3495 public Builder setSmallIcon(Icon icon) { 3496 mN.setSmallIcon(icon); 3497 if (icon != null && icon.getType() == Icon.TYPE_RESOURCE) { 3498 mN.icon = icon.getResId(); 3499 } 3500 return this; 3501 } 3502 3503 /** 3504 * Set the first line of text in the platform notification template. 3505 */ 3506 public Builder setContentTitle(CharSequence title) { 3507 mN.extras.putCharSequence(EXTRA_TITLE, safeCharSequence(title)); 3508 return this; 3509 } 3510 3511 /** 3512 * Set the second line of text in the platform notification template. 3513 */ 3514 public Builder setContentText(CharSequence text) { 3515 mN.extras.putCharSequence(EXTRA_TEXT, safeCharSequence(text)); 3516 return this; 3517 } 3518 3519 /** 3520 * This provides some additional information that is displayed in the notification. No 3521 * guarantees are given where exactly it is displayed. 3522 * 3523 * <p>This information should only be provided if it provides an essential 3524 * benefit to the understanding of the notification. The more text you provide the 3525 * less readable it becomes. For example, an email client should only provide the account 3526 * name here if more than one email account has been added.</p> 3527 * 3528 * <p>As of {@link android.os.Build.VERSION_CODES#N} this information is displayed in the 3529 * notification header area. 3530 * 3531 * On Android versions before {@link android.os.Build.VERSION_CODES#N} 3532 * this will be shown in the third line of text in the platform notification template. 3533 * You should not be using {@link #setProgress(int, int, boolean)} at the 3534 * same time on those versions; they occupy the same place. 3535 * </p> 3536 */ 3537 public Builder setSubText(CharSequence text) { 3538 mN.extras.putCharSequence(EXTRA_SUB_TEXT, safeCharSequence(text)); 3539 return this; 3540 } 3541 3542 /** 3543 * Provides text that will appear as a link to your application's settings. 3544 * 3545 * <p>This text does not appear within notification {@link Style templates} but may 3546 * appear when the user uses an affordance to learn more about the notification. 3547 * Additionally, this text will not appear unless you provide a valid link target by 3548 * handling {@link #INTENT_CATEGORY_NOTIFICATION_PREFERENCES}. 3549 * 3550 * <p>This text is meant to be concise description about what the user can customize 3551 * when they click on this link. The recommended maximum length is 40 characters. 3552 * @param text 3553 * @return 3554 */ 3555 public Builder setSettingsText(CharSequence text) { 3556 mN.mSettingsText = safeCharSequence(text); 3557 return this; 3558 } 3559 3560 /** 3561 * Set the remote input history. 3562 * 3563 * This should be set to the most recent inputs that have been sent 3564 * through a {@link RemoteInput} of this Notification and cleared once the it is no 3565 * longer relevant (e.g. for chat notifications once the other party has responded). 3566 * 3567 * The most recent input must be stored at the 0 index, the second most recent at the 3568 * 1 index, etc. Note that the system will limit both how far back the inputs will be shown 3569 * and how much of each individual input is shown. 3570 * 3571 * <p>Note: The reply text will only be shown on notifications that have least one action 3572 * with a {@code RemoteInput}.</p> 3573 */ 3574 public Builder setRemoteInputHistory(CharSequence[] text) { 3575 if (text == null) { 3576 mN.extras.putCharSequenceArray(EXTRA_REMOTE_INPUT_HISTORY, null); 3577 } else { 3578 final int N = Math.min(MAX_REPLY_HISTORY, text.length); 3579 CharSequence[] safe = new CharSequence[N]; 3580 for (int i = 0; i < N; i++) { 3581 safe[i] = safeCharSequence(text[i]); 3582 } 3583 mN.extras.putCharSequenceArray(EXTRA_REMOTE_INPUT_HISTORY, safe); 3584 } 3585 return this; 3586 } 3587 3588 /** 3589 * Sets whether remote history entries view should have a spinner. 3590 * @hide 3591 */ 3592 public Builder setShowRemoteInputSpinner(boolean showSpinner) { 3593 mN.extras.putBoolean(EXTRA_SHOW_REMOTE_INPUT_SPINNER, showSpinner); 3594 return this; 3595 } 3596 3597 /** 3598 * Sets the number of items this notification represents. May be displayed as a badge count 3599 * for Launchers that support badging. 3600 */ 3601 public Builder setNumber(int number) { 3602 mN.number = number; 3603 return this; 3604 } 3605 3606 /** 3607 * A small piece of additional information pertaining to this notification. 3608 * 3609 * The platform template will draw this on the last line of the notification, at the far 3610 * right (to the right of a smallIcon if it has been placed there). 3611 * 3612 * @deprecated use {@link #setSubText(CharSequence)} instead to set a text in the header. 3613 * For legacy apps targeting a version below {@link android.os.Build.VERSION_CODES#N} this 3614 * field will still show up, but the subtext will take precedence. 3615 */ 3616 @Deprecated 3617 public Builder setContentInfo(CharSequence info) { 3618 mN.extras.putCharSequence(EXTRA_INFO_TEXT, safeCharSequence(info)); 3619 return this; 3620 } 3621 3622 /** 3623 * Set the progress this notification represents. 3624 * 3625 * The platform template will represent this using a {@link ProgressBar}. 3626 */ 3627 public Builder setProgress(int max, int progress, boolean indeterminate) { 3628 mN.extras.putInt(EXTRA_PROGRESS, progress); 3629 mN.extras.putInt(EXTRA_PROGRESS_MAX, max); 3630 mN.extras.putBoolean(EXTRA_PROGRESS_INDETERMINATE, indeterminate); 3631 return this; 3632 } 3633 3634 /** 3635 * Supply a custom RemoteViews to use instead of the platform template. 3636 * 3637 * Use {@link #setCustomContentView(RemoteViews)} instead. 3638 */ 3639 @Deprecated 3640 public Builder setContent(RemoteViews views) { 3641 return setCustomContentView(views); 3642 } 3643 3644 /** 3645 * Supply custom RemoteViews to use instead of the platform template. 3646 * 3647 * This will override the layout that would otherwise be constructed by this Builder 3648 * object. 3649 */ 3650 public Builder setCustomContentView(RemoteViews contentView) { 3651 mN.contentView = contentView; 3652 return this; 3653 } 3654 3655 /** 3656 * Supply custom RemoteViews to use instead of the platform template in the expanded form. 3657 * 3658 * This will override the expanded layout that would otherwise be constructed by this 3659 * Builder object. 3660 */ 3661 public Builder setCustomBigContentView(RemoteViews contentView) { 3662 mN.bigContentView = contentView; 3663 return this; 3664 } 3665 3666 /** 3667 * Supply custom RemoteViews to use instead of the platform template in the heads up dialog. 3668 * 3669 * This will override the heads-up layout that would otherwise be constructed by this 3670 * Builder object. 3671 */ 3672 public Builder setCustomHeadsUpContentView(RemoteViews contentView) { 3673 mN.headsUpContentView = contentView; 3674 return this; 3675 } 3676 3677 /** 3678 * Supply a {@link PendingIntent} to be sent when the notification is clicked. 3679 * 3680 * As of {@link android.os.Build.VERSION_CODES#HONEYCOMB}, if this field is unset and you 3681 * have specified a custom RemoteViews with {@link #setContent(RemoteViews)}, you can use 3682 * {@link RemoteViews#setOnClickPendingIntent RemoteViews.setOnClickPendingIntent(int,PendingIntent)} 3683 * to assign PendingIntents to individual views in that custom layout (i.e., to create 3684 * clickable buttons inside the notification view). 3685 * 3686 * @see Notification#contentIntent Notification.contentIntent 3687 */ 3688 public Builder setContentIntent(PendingIntent intent) { 3689 mN.contentIntent = intent; 3690 return this; 3691 } 3692 3693 /** 3694 * Supply a {@link PendingIntent} to send when the notification is cleared explicitly by the user. 3695 * 3696 * @see Notification#deleteIntent 3697 */ 3698 public Builder setDeleteIntent(PendingIntent intent) { 3699 mN.deleteIntent = intent; 3700 return this; 3701 } 3702 3703 /** 3704 * An intent to launch instead of posting the notification to the status bar. 3705 * Only for use with extremely high-priority notifications demanding the user's 3706 * <strong>immediate</strong> attention, such as an incoming phone call or 3707 * alarm clock that the user has explicitly set to a particular time. 3708 * If this facility is used for something else, please give the user an option 3709 * to turn it off and use a normal notification, as this can be extremely 3710 * disruptive. 3711 * 3712 * <p> 3713 * The system UI may choose to display a heads-up notification, instead of 3714 * launching this intent, while the user is using the device. 3715 * </p> 3716 * 3717 * @param intent The pending intent to launch. 3718 * @param highPriority Passing true will cause this notification to be sent 3719 * even if other notifications are suppressed. 3720 * 3721 * @see Notification#fullScreenIntent 3722 */ 3723 public Builder setFullScreenIntent(PendingIntent intent, boolean highPriority) { 3724 mN.fullScreenIntent = intent; 3725 setFlag(FLAG_HIGH_PRIORITY, highPriority); 3726 return this; 3727 } 3728 3729 /** 3730 * Set the "ticker" text which is sent to accessibility services. 3731 * 3732 * @see Notification#tickerText 3733 */ 3734 public Builder setTicker(CharSequence tickerText) { 3735 mN.tickerText = safeCharSequence(tickerText); 3736 return this; 3737 } 3738 3739 /** 3740 * Obsolete version of {@link #setTicker(CharSequence)}. 3741 * 3742 */ 3743 @Deprecated 3744 public Builder setTicker(CharSequence tickerText, RemoteViews views) { 3745 setTicker(tickerText); 3746 // views is ignored 3747 return this; 3748 } 3749 3750 /** 3751 * Add a large icon to the notification content view. 3752 * 3753 * In the platform template, this image will be shown on the left of the notification view 3754 * in place of the {@link #setSmallIcon(Icon) small icon} (which will be placed in a small 3755 * badge atop the large icon). 3756 */ 3757 public Builder setLargeIcon(Bitmap b) { 3758 return setLargeIcon(b != null ? Icon.createWithBitmap(b) : null); 3759 } 3760 3761 /** 3762 * Add a large icon to the notification content view. 3763 * 3764 * In the platform template, this image will be shown on the left of the notification view 3765 * in place of the {@link #setSmallIcon(Icon) small icon} (which will be placed in a small 3766 * badge atop the large icon). 3767 */ 3768 public Builder setLargeIcon(Icon icon) { 3769 mN.mLargeIcon = icon; 3770 mN.extras.putParcelable(EXTRA_LARGE_ICON, icon); 3771 return this; 3772 } 3773 3774 /** 3775 * Set the sound to play. 3776 * 3777 * It will be played using the {@link #AUDIO_ATTRIBUTES_DEFAULT default audio attributes} 3778 * for notifications. 3779 * 3780 * @deprecated use {@link NotificationChannel#setSound(Uri, AudioAttributes)} instead. 3781 */ 3782 @Deprecated 3783 public Builder setSound(Uri sound) { 3784 mN.sound = sound; 3785 mN.audioAttributes = AUDIO_ATTRIBUTES_DEFAULT; 3786 return this; 3787 } 3788 3789 /** 3790 * Set the sound to play, along with a specific stream on which to play it. 3791 * 3792 * See {@link android.media.AudioManager} for the <code>STREAM_</code> constants. 3793 * 3794 * @deprecated use {@link NotificationChannel#setSound(Uri, AudioAttributes)}. 3795 */ 3796 @Deprecated 3797 public Builder setSound(Uri sound, int streamType) { 3798 PlayerBase.deprecateStreamTypeForPlayback(streamType, "Notification", "setSound()"); 3799 mN.sound = sound; 3800 mN.audioStreamType = streamType; 3801 return this; 3802 } 3803 3804 /** 3805 * Set the sound to play, along with specific {@link AudioAttributes audio attributes} to 3806 * use during playback. 3807 * 3808 * @deprecated use {@link NotificationChannel#setSound(Uri, AudioAttributes)} instead. 3809 * @see Notification#sound 3810 */ 3811 @Deprecated 3812 public Builder setSound(Uri sound, AudioAttributes audioAttributes) { 3813 mN.sound = sound; 3814 mN.audioAttributes = audioAttributes; 3815 return this; 3816 } 3817 3818 /** 3819 * Set the vibration pattern to use. 3820 * 3821 * See {@link android.os.Vibrator#vibrate(long[], int)} for a discussion of the 3822 * <code>pattern</code> parameter. 3823 * 3824 * <p> 3825 * A notification that vibrates is more likely to be presented as a heads-up notification. 3826 * </p> 3827 * 3828 * @deprecated use {@link NotificationChannel#setVibrationPattern(long[])} instead. 3829 * @see Notification#vibrate 3830 */ 3831 @Deprecated 3832 public Builder setVibrate(long[] pattern) { 3833 mN.vibrate = pattern; 3834 return this; 3835 } 3836 3837 /** 3838 * Set the desired color for the indicator LED on the device, as well as the 3839 * blink duty cycle (specified in milliseconds). 3840 * 3841 3842 * Not all devices will honor all (or even any) of these values. 3843 * 3844 * @deprecated use {@link NotificationChannel#enableLights(boolean)} instead. 3845 * @see Notification#ledARGB 3846 * @see Notification#ledOnMS 3847 * @see Notification#ledOffMS 3848 */ 3849 @Deprecated 3850 public Builder setLights(@ColorInt int argb, int onMs, int offMs) { 3851 mN.ledARGB = argb; 3852 mN.ledOnMS = onMs; 3853 mN.ledOffMS = offMs; 3854 if (onMs != 0 || offMs != 0) { 3855 mN.flags |= FLAG_SHOW_LIGHTS; 3856 } 3857 return this; 3858 } 3859 3860 /** 3861 * Set whether this is an "ongoing" notification. 3862 * 3863 3864 * Ongoing notifications cannot be dismissed by the user, so your application or service 3865 * must take care of canceling them. 3866 * 3867 3868 * They are typically used to indicate a background task that the user is actively engaged 3869 * with (e.g., playing music) or is pending in some way and therefore occupying the device 3870 * (e.g., a file download, sync operation, active network connection). 3871 * 3872 3873 * @see Notification#FLAG_ONGOING_EVENT 3874 * @see Service#setForeground(boolean) 3875 */ 3876 public Builder setOngoing(boolean ongoing) { 3877 setFlag(FLAG_ONGOING_EVENT, ongoing); 3878 return this; 3879 } 3880 3881 /** 3882 * Set whether this notification should be colorized. When set, the color set with 3883 * {@link #setColor(int)} will be used as the background color of this notification. 3884 * <p> 3885 * This should only be used for high priority ongoing tasks like navigation, an ongoing 3886 * call, or other similarly high-priority events for the user. 3887 * <p> 3888 * For most styles, the coloring will only be applied if the notification is for a 3889 * foreground service notification. 3890 * However, for {@link MediaStyle} and {@link DecoratedMediaCustomViewStyle} notifications 3891 * that have a media session attached there is no such requirement. 3892 * 3893 * @see Builder#setColor(int) 3894 * @see MediaStyle#setMediaSession(MediaSession.Token) 3895 */ 3896 public Builder setColorized(boolean colorize) { 3897 mN.extras.putBoolean(EXTRA_COLORIZED, colorize); 3898 return this; 3899 } 3900 3901 /** 3902 * Set this flag if you would only like the sound, vibrate 3903 * and ticker to be played if the notification is not already showing. 3904 * 3905 * @see Notification#FLAG_ONLY_ALERT_ONCE 3906 */ 3907 public Builder setOnlyAlertOnce(boolean onlyAlertOnce) { 3908 setFlag(FLAG_ONLY_ALERT_ONCE, onlyAlertOnce); 3909 return this; 3910 } 3911 3912 /** 3913 * Make this notification automatically dismissed when the user touches it. 3914 * 3915 * @see Notification#FLAG_AUTO_CANCEL 3916 */ 3917 public Builder setAutoCancel(boolean autoCancel) { 3918 setFlag(FLAG_AUTO_CANCEL, autoCancel); 3919 return this; 3920 } 3921 3922 /** 3923 * Set whether or not this notification should not bridge to other devices. 3924 * 3925 * <p>Some notifications can be bridged to other devices for remote display. 3926 * This hint can be set to recommend this notification not be bridged. 3927 */ 3928 public Builder setLocalOnly(boolean localOnly) { 3929 setFlag(FLAG_LOCAL_ONLY, localOnly); 3930 return this; 3931 } 3932 3933 /** 3934 * Set which notification properties will be inherited from system defaults. 3935 * <p> 3936 * The value should be one or more of the following fields combined with 3937 * bitwise-or: 3938 * {@link #DEFAULT_SOUND}, {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}. 3939 * <p> 3940 * For all default values, use {@link #DEFAULT_ALL}. 3941 * 3942 * @deprecated use {@link NotificationChannel#enableVibration(boolean)} and 3943 * {@link NotificationChannel#enableLights(boolean)} and 3944 * {@link NotificationChannel#setSound(Uri, AudioAttributes)} instead. 3945 */ 3946 @Deprecated 3947 public Builder setDefaults(int defaults) { 3948 mN.defaults = defaults; 3949 return this; 3950 } 3951 3952 /** 3953 * Set the priority of this notification. 3954 * 3955 * @see Notification#priority 3956 * @deprecated use {@link NotificationChannel#setImportance(int)} instead. 3957 */ 3958 @Deprecated 3959 public Builder setPriority(@Priority int pri) { 3960 mN.priority = pri; 3961 return this; 3962 } 3963 3964 /** 3965 * Set the notification category. 3966 * 3967 * @see Notification#category 3968 */ 3969 public Builder setCategory(String category) { 3970 mN.category = category; 3971 return this; 3972 } 3973 3974 /** 3975 * Add a person that is relevant to this notification. 3976 * 3977 * <P> 3978 * Depending on user preferences, this annotation may allow the notification to pass 3979 * through interruption filters, if this notification is of category {@link #CATEGORY_CALL} 3980 * or {@link #CATEGORY_MESSAGE}. The addition of people may also cause this notification to 3981 * appear more prominently in the user interface. 3982 * </P> 3983 * 3984 * <P> 3985 * The person should be specified by the {@code String} representation of a 3986 * {@link android.provider.ContactsContract.Contacts#CONTENT_LOOKUP_URI}. 3987 * </P> 3988 * 3989 * <P>The system will also attempt to resolve {@code mailto:} and {@code tel:} schema 3990 * URIs. The path part of these URIs must exist in the contacts database, in the 3991 * appropriate column, or the reference will be discarded as invalid. Telephone schema 3992 * URIs will be resolved by {@link android.provider.ContactsContract.PhoneLookup}. 3993 * It is also possible to provide a URI with the schema {@code name:} in order to uniquely 3994 * identify a person without an entry in the contacts database. 3995 * </P> 3996 * 3997 * @param uri A URI for the person. 3998 * @see Notification#EXTRA_PEOPLE 3999 * @deprecated use {@link #addPerson(Person)} 4000 */ 4001 public Builder addPerson(String uri) { 4002 addPerson(new Person.Builder().setUri(uri).build()); 4003 return this; 4004 } 4005 4006 /** 4007 * Add a person that is relevant to this notification. 4008 * 4009 * <P> 4010 * Depending on user preferences, this annotation may allow the notification to pass 4011 * through interruption filters, if this notification is of category {@link #CATEGORY_CALL} 4012 * or {@link #CATEGORY_MESSAGE}. The addition of people may also cause this notification to 4013 * appear more prominently in the user interface. 4014 * </P> 4015 * 4016 * <P> 4017 * A person should usually contain a uri in order to benefit from the ranking boost. 4018 * However, even if no uri is provided, it's beneficial to provide other people in the 4019 * notification, such that listeners and voice only devices can announce and handle them 4020 * properly. 4021 * </P> 4022 * 4023 * @param person the person to add. 4024 * @see Notification#EXTRA_PEOPLE_LIST 4025 */ 4026 public Builder addPerson(Person person) { 4027 mPersonList.add(person); 4028 return this; 4029 } 4030 4031 /** 4032 * Set this notification to be part of a group of notifications sharing the same key. 4033 * Grouped notifications may display in a cluster or stack on devices which 4034 * support such rendering. 4035 * 4036 * <p>To make this notification the summary for its group, also call 4037 * {@link #setGroupSummary}. A sort order can be specified for group members by using 4038 * {@link #setSortKey}. 4039 * @param groupKey The group key of the group. 4040 * @return this object for method chaining 4041 */ 4042 public Builder setGroup(String groupKey) { 4043 mN.mGroupKey = groupKey; 4044 return this; 4045 } 4046 4047 /** 4048 * Set this notification to be the group summary for a group of notifications. 4049 * Grouped notifications may display in a cluster or stack on devices which 4050 * support such rendering. If thereRequires a group key also be set using {@link #setGroup}. 4051 * The group summary may be suppressed if too few notifications are included in the group. 4052 * @param isGroupSummary Whether this notification should be a group summary. 4053 * @return this object for method chaining 4054 */ 4055 public Builder setGroupSummary(boolean isGroupSummary) { 4056 setFlag(FLAG_GROUP_SUMMARY, isGroupSummary); 4057 return this; 4058 } 4059 4060 /** 4061 * Set a sort key that orders this notification among other notifications from the 4062 * same package. This can be useful if an external sort was already applied and an app 4063 * would like to preserve this. Notifications will be sorted lexicographically using this 4064 * value, although providing different priorities in addition to providing sort key may 4065 * cause this value to be ignored. 4066 * 4067 * <p>This sort key can also be used to order members of a notification group. See 4068 * {@link #setGroup}. 4069 * 4070 * @see String#compareTo(String) 4071 */ 4072 public Builder setSortKey(String sortKey) { 4073 mN.mSortKey = sortKey; 4074 return this; 4075 } 4076 4077 /** 4078 * Merge additional metadata into this notification. 4079 * 4080 * <p>Values within the Bundle will replace existing extras values in this Builder. 4081 * 4082 * @see Notification#extras 4083 */ 4084 public Builder addExtras(Bundle extras) { 4085 if (extras != null) { 4086 mUserExtras.putAll(extras); 4087 } 4088 return this; 4089 } 4090 4091 /** 4092 * Set metadata for this notification. 4093 * 4094 * <p>A reference to the Bundle is held for the lifetime of this Builder, and the Bundle's 4095 * current contents are copied into the Notification each time {@link #build()} is 4096 * called. 4097 * 4098 * <p>Replaces any existing extras values with those from the provided Bundle. 4099 * Use {@link #addExtras} to merge in metadata instead. 4100 * 4101 * @see Notification#extras 4102 */ 4103 public Builder setExtras(Bundle extras) { 4104 if (extras != null) { 4105 mUserExtras = extras; 4106 } 4107 return this; 4108 } 4109 4110 /** 4111 * Get the current metadata Bundle used by this notification Builder. 4112 * 4113 * <p>The returned Bundle is shared with this Builder. 4114 * 4115 * <p>The current contents of this Bundle are copied into the Notification each time 4116 * {@link #build()} is called. 4117 * 4118 * @see Notification#extras 4119 */ 4120 public Bundle getExtras() { 4121 return mUserExtras; 4122 } 4123 4124 private Bundle getAllExtras() { 4125 final Bundle saveExtras = (Bundle) mUserExtras.clone(); 4126 saveExtras.putAll(mN.extras); 4127 return saveExtras; 4128 } 4129 4130 /** 4131 * Add an action to this notification. Actions are typically displayed by 4132 * the system as a button adjacent to the notification content. 4133 * <p> 4134 * Every action must have an icon (32dp square and matching the 4135 * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo 4136 * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}. 4137 * <p> 4138 * A notification in its expanded form can display up to 3 actions, from left to right in 4139 * the order they were added. Actions will not be displayed when the notification is 4140 * collapsed, however, so be sure that any essential functions may be accessed by the user 4141 * in some other way (for example, in the Activity pointed to by {@link #contentIntent}). 4142 * 4143 * @param icon Resource ID of a drawable that represents the action. 4144 * @param title Text describing the action. 4145 * @param intent PendingIntent to be fired when the action is invoked. 4146 * 4147 * @deprecated Use {@link #addAction(Action)} instead. 4148 */ 4149 @Deprecated 4150 public Builder addAction(int icon, CharSequence title, PendingIntent intent) { 4151 mActions.add(new Action(icon, safeCharSequence(title), intent)); 4152 return this; 4153 } 4154 4155 /** 4156 * Add an action to this notification. Actions are typically displayed by 4157 * the system as a button adjacent to the notification content. 4158 * <p> 4159 * Every action must have an icon (32dp square and matching the 4160 * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo 4161 * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}. 4162 * <p> 4163 * A notification in its expanded form can display up to 3 actions, from left to right in 4164 * the order they were added. Actions will not be displayed when the notification is 4165 * collapsed, however, so be sure that any essential functions may be accessed by the user 4166 * in some other way (for example, in the Activity pointed to by {@link #contentIntent}). 4167 * 4168 * @param action The action to add. 4169 */ 4170 public Builder addAction(Action action) { 4171 if (action != null) { 4172 mActions.add(action); 4173 } 4174 return this; 4175 } 4176 4177 /** 4178 * Alter the complete list of actions attached to this notification. 4179 * @see #addAction(Action). 4180 * 4181 * @param actions 4182 * @return 4183 */ 4184 public Builder setActions(Action... actions) { 4185 mActions.clear(); 4186 for (int i = 0; i < actions.length; i++) { 4187 if (actions[i] != null) { 4188 mActions.add(actions[i]); 4189 } 4190 } 4191 return this; 4192 } 4193 4194 /** 4195 * Add a rich notification style to be applied at build time. 4196 * 4197 * @param style Object responsible for modifying the notification style. 4198 */ 4199 public Builder setStyle(Style style) { 4200 if (mStyle != style) { 4201 mStyle = style; 4202 if (mStyle != null) { 4203 mStyle.setBuilder(this); 4204 mN.extras.putString(EXTRA_TEMPLATE, style.getClass().getName()); 4205 } else { 4206 mN.extras.remove(EXTRA_TEMPLATE); 4207 } 4208 } 4209 return this; 4210 } 4211 4212 /** 4213 * Returns the style set by {@link #setStyle(Style)}. 4214 */ 4215 public Style getStyle() { 4216 return mStyle; 4217 } 4218 4219 /** 4220 * Specify the value of {@link #visibility}. 4221 * 4222 * @return The same Builder. 4223 */ 4224 public Builder setVisibility(@Visibility int visibility) { 4225 mN.visibility = visibility; 4226 return this; 4227 } 4228 4229 /** 4230 * Supply a replacement Notification whose contents should be shown in insecure contexts 4231 * (i.e. atop the secure lockscreen). See {@link #visibility} and {@link #VISIBILITY_PUBLIC}. 4232 * @param n A replacement notification, presumably with some or all info redacted. 4233 * @return The same Builder. 4234 */ 4235 public Builder setPublicVersion(Notification n) { 4236 if (n != null) { 4237 mN.publicVersion = new Notification(); 4238 n.cloneInto(mN.publicVersion, /*heavy=*/ true); 4239 } else { 4240 mN.publicVersion = null; 4241 } 4242 return this; 4243 } 4244 4245 /** 4246 * Apply an extender to this notification builder. Extenders may be used to add 4247 * metadata or change options on this builder. 4248 */ 4249 public Builder extend(Extender extender) { 4250 extender.extend(this); 4251 return this; 4252 } 4253 4254 /** 4255 * @hide 4256 */ 4257 public Builder setFlag(int mask, boolean value) { 4258 if (value) { 4259 mN.flags |= mask; 4260 } else { 4261 mN.flags &= ~mask; 4262 } 4263 return this; 4264 } 4265 4266 /** 4267 * Sets {@link Notification#color}. 4268 * 4269 * @param argb The accent color to use 4270 * 4271 * @return The same Builder. 4272 */ 4273 public Builder setColor(@ColorInt int argb) { 4274 mN.color = argb; 4275 sanitizeColor(); 4276 return this; 4277 } 4278 4279 private Drawable getProfileBadgeDrawable() { 4280 if (mContext.getUserId() == UserHandle.USER_SYSTEM) { 4281 // This user can never be a badged profile, 4282 // and also includes USER_ALL system notifications. 4283 return null; 4284 } 4285 // Note: This assumes that the current user can read the profile badge of the 4286 // originating user. 4287 return mContext.getPackageManager().getUserBadgeForDensityNoBackground( 4288 new UserHandle(mContext.getUserId()), 0); 4289 } 4290 4291 private Bitmap getProfileBadge() { 4292 Drawable badge = getProfileBadgeDrawable(); 4293 if (badge == null) { 4294 return null; 4295 } 4296 final int size = mContext.getResources().getDimensionPixelSize( 4297 R.dimen.notification_badge_size); 4298 Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); 4299 Canvas canvas = new Canvas(bitmap); 4300 badge.setBounds(0, 0, size, size); 4301 badge.draw(canvas); 4302 return bitmap; 4303 } 4304 4305 private void bindProfileBadge(RemoteViews contentView) { 4306 Bitmap profileBadge = getProfileBadge(); 4307 4308 if (profileBadge != null) { 4309 contentView.setImageViewBitmap(R.id.profile_badge, profileBadge); 4310 contentView.setViewVisibility(R.id.profile_badge, View.VISIBLE); 4311 if (isColorized()) { 4312 contentView.setDrawableTint(R.id.profile_badge, false, 4313 getPrimaryTextColor(), PorterDuff.Mode.SRC_ATOP); 4314 } 4315 } 4316 } 4317 4318 /** 4319 * @hide 4320 */ 4321 public boolean usesStandardHeader() { 4322 if (mN.mUsesStandardHeader) { 4323 return true; 4324 } 4325 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.N) { 4326 if (mN.contentView == null && mN.bigContentView == null) { 4327 return true; 4328 } 4329 } 4330 boolean contentViewUsesHeader = mN.contentView == null 4331 || STANDARD_LAYOUTS.contains(mN.contentView.getLayoutId()); 4332 boolean bigContentViewUsesHeader = mN.bigContentView == null 4333 || STANDARD_LAYOUTS.contains(mN.bigContentView.getLayoutId()); 4334 return contentViewUsesHeader && bigContentViewUsesHeader; 4335 } 4336 4337 private void resetStandardTemplate(RemoteViews contentView) { 4338 resetNotificationHeader(contentView); 4339 contentView.setViewVisibility(R.id.right_icon, View.GONE); 4340 contentView.setViewVisibility(R.id.title, View.GONE); 4341 contentView.setTextViewText(R.id.title, null); 4342 contentView.setViewVisibility(R.id.text, View.GONE); 4343 contentView.setTextViewText(R.id.text, null); 4344 contentView.setViewVisibility(R.id.text_line_1, View.GONE); 4345 contentView.setTextViewText(R.id.text_line_1, null); 4346 } 4347 4348 /** 4349 * Resets the notification header to its original state 4350 */ 4351 private void resetNotificationHeader(RemoteViews contentView) { 4352 // Small icon doesn't need to be reset, as it's always set. Resetting would prevent 4353 // re-using the drawable when the notification is updated. 4354 contentView.setBoolean(R.id.notification_header, "setExpanded", false); 4355 contentView.setTextViewText(R.id.app_name_text, null); 4356 contentView.setViewVisibility(R.id.chronometer, View.GONE); 4357 contentView.setViewVisibility(R.id.header_text, View.GONE); 4358 contentView.setTextViewText(R.id.header_text, null); 4359 contentView.setViewVisibility(R.id.header_text_secondary, View.GONE); 4360 contentView.setTextViewText(R.id.header_text_secondary, null); 4361 contentView.setViewVisibility(R.id.header_text_divider, View.GONE); 4362 contentView.setViewVisibility(R.id.header_text_secondary_divider, View.GONE); 4363 contentView.setViewVisibility(R.id.time_divider, View.GONE); 4364 contentView.setViewVisibility(R.id.time, View.GONE); 4365 contentView.setImageViewIcon(R.id.profile_badge, null); 4366 contentView.setViewVisibility(R.id.profile_badge, View.GONE); 4367 mN.mUsesStandardHeader = false; 4368 } 4369 4370 private RemoteViews applyStandardTemplate(int resId, TemplateBindResult result) { 4371 return applyStandardTemplate(resId, mParams.reset().fillTextsFrom(this), 4372 result); 4373 } 4374 4375 /** 4376 * @param hasProgress whether the progress bar should be shown and set 4377 * @param result 4378 */ 4379 private RemoteViews applyStandardTemplate(int resId, boolean hasProgress, 4380 TemplateBindResult result) { 4381 return applyStandardTemplate(resId, mParams.reset().hasProgress(hasProgress) 4382 .fillTextsFrom(this), result); 4383 } 4384 4385 private RemoteViews applyStandardTemplate(int resId, StandardTemplateParams p, 4386 TemplateBindResult result) { 4387 RemoteViews contentView = new BuilderRemoteViews(mContext.getApplicationInfo(), resId); 4388 4389 resetStandardTemplate(contentView); 4390 4391 final Bundle ex = mN.extras; 4392 updateBackgroundColor(contentView); 4393 bindNotificationHeader(contentView, p.ambient, p.headerTextSecondary); 4394 bindLargeIconAndReply(contentView, p, result); 4395 boolean showProgress = handleProgressBar(p.hasProgress, contentView, ex); 4396 if (p.title != null) { 4397 contentView.setViewVisibility(R.id.title, View.VISIBLE); 4398 contentView.setTextViewText(R.id.title, processTextSpans(p.title)); 4399 if (!p.ambient) { 4400 setTextViewColorPrimary(contentView, R.id.title); 4401 } 4402 contentView.setViewLayoutWidth(R.id.title, showProgress 4403 ? ViewGroup.LayoutParams.WRAP_CONTENT 4404 : ViewGroup.LayoutParams.MATCH_PARENT); 4405 } 4406 if (p.text != null) { 4407 int textId = showProgress ? com.android.internal.R.id.text_line_1 4408 : com.android.internal.R.id.text; 4409 contentView.setTextViewText(textId, processTextSpans(p.text)); 4410 if (!p.ambient) { 4411 setTextViewColorSecondary(contentView, textId); 4412 } 4413 contentView.setViewVisibility(textId, View.VISIBLE); 4414 } 4415 4416 setContentMinHeight(contentView, showProgress || mN.hasLargeIcon()); 4417 4418 return contentView; 4419 } 4420 4421 private CharSequence processTextSpans(CharSequence text) { 4422 if (hasForegroundColor()) { 4423 return NotificationColorUtil.clearColorSpans(text); 4424 } 4425 return text; 4426 } 4427 4428 private void setTextViewColorPrimary(RemoteViews contentView, int id) { 4429 ensureColors(); 4430 contentView.setTextColor(id, mPrimaryTextColor); 4431 } 4432 4433 private boolean hasForegroundColor() { 4434 return mForegroundColor != COLOR_INVALID; 4435 } 4436 4437 /** 4438 * @return the primary text color 4439 * @hide 4440 */ 4441 @VisibleForTesting 4442 public int getPrimaryTextColor() { 4443 ensureColors(); 4444 return mPrimaryTextColor; 4445 } 4446 4447 /** 4448 * @return the secondary text color 4449 * @hide 4450 */ 4451 @VisibleForTesting 4452 public int getSecondaryTextColor() { 4453 ensureColors(); 4454 return mSecondaryTextColor; 4455 } 4456 4457 private void setTextViewColorSecondary(RemoteViews contentView, int id) { 4458 ensureColors(); 4459 contentView.setTextColor(id, mSecondaryTextColor); 4460 } 4461 4462 private void ensureColors() { 4463 int backgroundColor = getBackgroundColor(); 4464 if (mPrimaryTextColor == COLOR_INVALID 4465 || mSecondaryTextColor == COLOR_INVALID 4466 || mTextColorsAreForBackground != backgroundColor) { 4467 mTextColorsAreForBackground = backgroundColor; 4468 if (!hasForegroundColor() || !isColorized()) { 4469 mPrimaryTextColor = NotificationColorUtil.resolvePrimaryColor(mContext, 4470 backgroundColor); 4471 mSecondaryTextColor = NotificationColorUtil.resolveSecondaryColor(mContext, 4472 backgroundColor); 4473 if (backgroundColor != COLOR_DEFAULT && isColorized()) { 4474 mPrimaryTextColor = NotificationColorUtil.findAlphaToMeetContrast( 4475 mPrimaryTextColor, backgroundColor, 4.5); 4476 mSecondaryTextColor = NotificationColorUtil.findAlphaToMeetContrast( 4477 mSecondaryTextColor, backgroundColor, 4.5); 4478 } 4479 } else { 4480 double backLum = NotificationColorUtil.calculateLuminance(backgroundColor); 4481 double textLum = NotificationColorUtil.calculateLuminance(mForegroundColor); 4482 double contrast = NotificationColorUtil.calculateContrast(mForegroundColor, 4483 backgroundColor); 4484 // We only respect the given colors if worst case Black or White still has 4485 // contrast 4486 boolean backgroundLight = backLum > textLum 4487 && satisfiesTextContrast(backgroundColor, Color.BLACK) 4488 || backLum <= textLum 4489 && !satisfiesTextContrast(backgroundColor, Color.WHITE); 4490 if (contrast < 4.5f) { 4491 if (backgroundLight) { 4492 mSecondaryTextColor = NotificationColorUtil.findContrastColor( 4493 mForegroundColor, 4494 backgroundColor, 4495 true /* findFG */, 4496 4.5f); 4497 mPrimaryTextColor = NotificationColorUtil.changeColorLightness( 4498 mSecondaryTextColor, -LIGHTNESS_TEXT_DIFFERENCE_LIGHT); 4499 } else { 4500 mSecondaryTextColor = 4501 NotificationColorUtil.findContrastColorAgainstDark( 4502 mForegroundColor, 4503 backgroundColor, 4504 true /* findFG */, 4505 4.5f); 4506 mPrimaryTextColor = NotificationColorUtil.changeColorLightness( 4507 mSecondaryTextColor, -LIGHTNESS_TEXT_DIFFERENCE_DARK); 4508 } 4509 } else { 4510 mPrimaryTextColor = mForegroundColor; 4511 mSecondaryTextColor = NotificationColorUtil.changeColorLightness( 4512 mPrimaryTextColor, backgroundLight ? LIGHTNESS_TEXT_DIFFERENCE_LIGHT 4513 : LIGHTNESS_TEXT_DIFFERENCE_DARK); 4514 if (NotificationColorUtil.calculateContrast(mSecondaryTextColor, 4515 backgroundColor) < 4.5f) { 4516 // oh well the secondary is not good enough 4517 if (backgroundLight) { 4518 mSecondaryTextColor = NotificationColorUtil.findContrastColor( 4519 mSecondaryTextColor, 4520 backgroundColor, 4521 true /* findFG */, 4522 4.5f); 4523 } else { 4524 mSecondaryTextColor 4525 = NotificationColorUtil.findContrastColorAgainstDark( 4526 mSecondaryTextColor, 4527 backgroundColor, 4528 true /* findFG */, 4529 4.5f); 4530 } 4531 mPrimaryTextColor = NotificationColorUtil.changeColorLightness( 4532 mSecondaryTextColor, backgroundLight 4533 ? -LIGHTNESS_TEXT_DIFFERENCE_LIGHT 4534 : -LIGHTNESS_TEXT_DIFFERENCE_DARK); 4535 } 4536 } 4537 } 4538 } 4539 } 4540 4541 private void updateBackgroundColor(RemoteViews contentView) { 4542 if (isColorized()) { 4543 contentView.setInt(R.id.status_bar_latest_event_content, "setBackgroundColor", 4544 getBackgroundColor()); 4545 } else { 4546 // Clear it! 4547 contentView.setInt(R.id.status_bar_latest_event_content, "setBackgroundResource", 4548 0); 4549 } 4550 } 4551 4552 /** 4553 * @param remoteView the remote view to update the minheight in 4554 * @param hasMinHeight does it have a mimHeight 4555 * @hide 4556 */ 4557 void setContentMinHeight(RemoteViews remoteView, boolean hasMinHeight) { 4558 int minHeight = 0; 4559 if (hasMinHeight) { 4560 // we need to set the minHeight of the notification 4561 minHeight = mContext.getResources().getDimensionPixelSize( 4562 com.android.internal.R.dimen.notification_min_content_height); 4563 } 4564 remoteView.setInt(R.id.notification_main_column, "setMinimumHeight", minHeight); 4565 } 4566 4567 private boolean handleProgressBar(boolean hasProgress, RemoteViews contentView, Bundle ex) { 4568 final int max = ex.getInt(EXTRA_PROGRESS_MAX, 0); 4569 final int progress = ex.getInt(EXTRA_PROGRESS, 0); 4570 final boolean ind = ex.getBoolean(EXTRA_PROGRESS_INDETERMINATE); 4571 if (hasProgress && (max != 0 || ind)) { 4572 contentView.setViewVisibility(com.android.internal.R.id.progress, View.VISIBLE); 4573 contentView.setProgressBar( 4574 R.id.progress, max, progress, ind); 4575 contentView.setProgressBackgroundTintList( 4576 R.id.progress, ColorStateList.valueOf(mContext.getColor( 4577 R.color.notification_progress_background_color))); 4578 if (mN.color != COLOR_DEFAULT) { 4579 ColorStateList colorStateList = ColorStateList.valueOf(resolveContrastColor()); 4580 contentView.setProgressTintList(R.id.progress, colorStateList); 4581 contentView.setProgressIndeterminateTintList(R.id.progress, colorStateList); 4582 } 4583 return true; 4584 } else { 4585 contentView.setViewVisibility(R.id.progress, View.GONE); 4586 return false; 4587 } 4588 } 4589 4590 private void bindLargeIconAndReply(RemoteViews contentView, StandardTemplateParams p, 4591 TemplateBindResult result) { 4592 boolean largeIconShown = bindLargeIcon(contentView, p.hideLargeIcon || p.ambient); 4593 boolean replyIconShown = bindReplyIcon(contentView, p.hideReplyIcon || p.ambient); 4594 contentView.setViewVisibility(R.id.right_icon_container, 4595 largeIconShown || replyIconShown ? View.VISIBLE : View.GONE); 4596 int marginEnd = calculateMarginEnd(largeIconShown, replyIconShown); 4597 contentView.setViewLayoutMarginEnd(R.id.line1, marginEnd); 4598 contentView.setViewLayoutMarginEnd(R.id.text, marginEnd); 4599 contentView.setViewLayoutMarginEnd(R.id.progress, marginEnd); 4600 if (result != null) { 4601 result.setIconMarginEnd(marginEnd); 4602 } 4603 } 4604 4605 private int calculateMarginEnd(boolean largeIconShown, boolean replyIconShown) { 4606 int marginEnd = 0; 4607 int contentMargin = mContext.getResources().getDimensionPixelSize( 4608 R.dimen.notification_content_margin_end); 4609 int iconSize = mContext.getResources().getDimensionPixelSize( 4610 R.dimen.notification_right_icon_size); 4611 if (replyIconShown) { 4612 // The size of the reply icon 4613 marginEnd += iconSize; 4614 4615 int replyInset = mContext.getResources().getDimensionPixelSize( 4616 R.dimen.notification_reply_inset); 4617 // We're subtracting the inset of the reply icon to make sure it's 4618 // aligned nicely on the right, and remove it from the following padding 4619 marginEnd -= replyInset * 2; 4620 } 4621 if (largeIconShown) { 4622 // adding size of the right icon 4623 marginEnd += iconSize; 4624 4625 if (replyIconShown) { 4626 // We also add some padding to the reply icon if it's around 4627 marginEnd += contentMargin; 4628 } 4629 } 4630 if (replyIconShown || largeIconShown) { 4631 // The padding to the content 4632 marginEnd += contentMargin; 4633 } 4634 return marginEnd; 4635 } 4636 4637 /** 4638 * Bind the large icon. 4639 * @return if the largeIcon is visible 4640 */ 4641 private boolean bindLargeIcon(RemoteViews contentView, boolean hideLargeIcon) { 4642 if (mN.mLargeIcon == null && mN.largeIcon != null) { 4643 mN.mLargeIcon = Icon.createWithBitmap(mN.largeIcon); 4644 } 4645 boolean showLargeIcon = mN.mLargeIcon != null && !hideLargeIcon; 4646 if (showLargeIcon) { 4647 contentView.setViewVisibility(R.id.right_icon, View.VISIBLE); 4648 contentView.setImageViewIcon(R.id.right_icon, mN.mLargeIcon); 4649 processLargeLegacyIcon(mN.mLargeIcon, contentView); 4650 } 4651 return showLargeIcon; 4652 } 4653 4654 /** 4655 * Bind the reply icon. 4656 * @return if the reply icon is visible 4657 */ 4658 private boolean bindReplyIcon(RemoteViews contentView, boolean hideReplyIcon) { 4659 boolean actionVisible = !hideReplyIcon; 4660 Action action = null; 4661 if (actionVisible) { 4662 action = findReplyAction(); 4663 actionVisible = action != null; 4664 } 4665 if (actionVisible) { 4666 contentView.setViewVisibility(R.id.reply_icon_action, View.VISIBLE); 4667 contentView.setDrawableTint(R.id.reply_icon_action, 4668 false /* targetBackground */, 4669 getNeutralColor(), 4670 PorterDuff.Mode.SRC_ATOP); 4671 contentView.setOnClickPendingIntent(R.id.reply_icon_action, action.actionIntent); 4672 contentView.setRemoteInputs(R.id.reply_icon_action, action.mRemoteInputs); 4673 } else { 4674 contentView.setRemoteInputs(R.id.reply_icon_action, null); 4675 } 4676 contentView.setViewVisibility(R.id.reply_icon_action, 4677 actionVisible ? View.VISIBLE : View.GONE); 4678 return actionVisible; 4679 } 4680 4681 private Action findReplyAction() { 4682 ArrayList<Action> actions = mActions; 4683 if (mOriginalActions != null) { 4684 actions = mOriginalActions; 4685 } 4686 int numActions = actions.size(); 4687 for (int i = 0; i < numActions; i++) { 4688 Action action = actions.get(i); 4689 if (hasValidRemoteInput(action)) { 4690 return action; 4691 } 4692 } 4693 return null; 4694 } 4695 4696 private void bindNotificationHeader(RemoteViews contentView, boolean ambient, 4697 CharSequence secondaryHeaderText) { 4698 bindSmallIcon(contentView, ambient); 4699 bindHeaderAppName(contentView, ambient); 4700 if (!ambient) { 4701 // Ambient view does not have these 4702 bindHeaderText(contentView); 4703 bindHeaderTextSecondary(contentView, secondaryHeaderText); 4704 bindHeaderChronometerAndTime(contentView); 4705 bindProfileBadge(contentView); 4706 } 4707 bindActivePermissions(contentView, ambient); 4708 bindExpandButton(contentView); 4709 mN.mUsesStandardHeader = true; 4710 } 4711 4712 private void bindActivePermissions(RemoteViews contentView, boolean ambient) { 4713 int color = ambient ? resolveAmbientColor() : getNeutralColor(); 4714 contentView.setDrawableTint(R.id.camera, false, color, PorterDuff.Mode.SRC_ATOP); 4715 contentView.setDrawableTint(R.id.mic, false, color, PorterDuff.Mode.SRC_ATOP); 4716 contentView.setDrawableTint(R.id.overlay, false, color, PorterDuff.Mode.SRC_ATOP); 4717 } 4718 4719 private void bindExpandButton(RemoteViews contentView) { 4720 int color = isColorized() ? getPrimaryTextColor() : getSecondaryTextColor(); 4721 contentView.setDrawableTint(R.id.expand_button, false, color, 4722 PorterDuff.Mode.SRC_ATOP); 4723 contentView.setInt(R.id.notification_header, "setOriginalNotificationColor", 4724 color); 4725 } 4726 4727 private void bindHeaderChronometerAndTime(RemoteViews contentView) { 4728 if (showsTimeOrChronometer()) { 4729 contentView.setViewVisibility(R.id.time_divider, View.VISIBLE); 4730 setTextViewColorSecondary(contentView, R.id.time_divider); 4731 if (mN.extras.getBoolean(EXTRA_SHOW_CHRONOMETER)) { 4732 contentView.setViewVisibility(R.id.chronometer, View.VISIBLE); 4733 contentView.setLong(R.id.chronometer, "setBase", 4734 mN.when + (SystemClock.elapsedRealtime() - System.currentTimeMillis())); 4735 contentView.setBoolean(R.id.chronometer, "setStarted", true); 4736 boolean countsDown = mN.extras.getBoolean(EXTRA_CHRONOMETER_COUNT_DOWN); 4737 contentView.setChronometerCountDown(R.id.chronometer, countsDown); 4738 setTextViewColorSecondary(contentView, R.id.chronometer); 4739 } else { 4740 contentView.setViewVisibility(R.id.time, View.VISIBLE); 4741 contentView.setLong(R.id.time, "setTime", mN.when); 4742 setTextViewColorSecondary(contentView, R.id.time); 4743 } 4744 } else { 4745 // We still want a time to be set but gone, such that we can show and hide it 4746 // on demand in case it's a child notification without anything in the header 4747 contentView.setLong(R.id.time, "setTime", mN.when != 0 ? mN.when : mN.creationTime); 4748 } 4749 } 4750 4751 private void bindHeaderText(RemoteViews contentView) { 4752 CharSequence headerText = mN.extras.getCharSequence(EXTRA_SUB_TEXT); 4753 if (headerText == null && mStyle != null && mStyle.mSummaryTextSet 4754 && mStyle.hasSummaryInHeader()) { 4755 headerText = mStyle.mSummaryText; 4756 } 4757 if (headerText == null 4758 && mContext.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N 4759 && mN.extras.getCharSequence(EXTRA_INFO_TEXT) != null) { 4760 headerText = mN.extras.getCharSequence(EXTRA_INFO_TEXT); 4761 } 4762 if (headerText != null) { 4763 // TODO: Remove the span entirely to only have the string with propper formating. 4764 contentView.setTextViewText(R.id.header_text, processTextSpans( 4765 processLegacyText(headerText))); 4766 setTextViewColorSecondary(contentView, R.id.header_text); 4767 contentView.setViewVisibility(R.id.header_text, View.VISIBLE); 4768 contentView.setViewVisibility(R.id.header_text_divider, View.VISIBLE); 4769 setTextViewColorSecondary(contentView, R.id.header_text_divider); 4770 } 4771 } 4772 4773 private void bindHeaderTextSecondary(RemoteViews contentView, CharSequence secondaryText) { 4774 if (!TextUtils.isEmpty(secondaryText)) { 4775 contentView.setTextViewText(R.id.header_text_secondary, processTextSpans( 4776 processLegacyText(secondaryText))); 4777 setTextViewColorSecondary(contentView, R.id.header_text_secondary); 4778 contentView.setViewVisibility(R.id.header_text_secondary, View.VISIBLE); 4779 contentView.setViewVisibility(R.id.header_text_secondary_divider, View.VISIBLE); 4780 setTextViewColorSecondary(contentView, R.id.header_text_secondary_divider); 4781 } 4782 } 4783 4784 /** 4785 * @hide 4786 */ 4787 public String loadHeaderAppName() { 4788 CharSequence name = null; 4789 final PackageManager pm = mContext.getPackageManager(); 4790 if (mN.extras.containsKey(EXTRA_SUBSTITUTE_APP_NAME)) { 4791 // only system packages which lump together a bunch of unrelated stuff 4792 // may substitute a different name to make the purpose of the 4793 // notification more clear. the correct package label should always 4794 // be accessible via SystemUI. 4795 final String pkg = mContext.getPackageName(); 4796 final String subName = mN.extras.getString(EXTRA_SUBSTITUTE_APP_NAME); 4797 if (PackageManager.PERMISSION_GRANTED == pm.checkPermission( 4798 android.Manifest.permission.SUBSTITUTE_NOTIFICATION_APP_NAME, pkg)) { 4799 name = subName; 4800 } else { 4801 Log.w(TAG, "warning: pkg " 4802 + pkg + " attempting to substitute app name '" + subName 4803 + "' without holding perm " 4804 + android.Manifest.permission.SUBSTITUTE_NOTIFICATION_APP_NAME); 4805 } 4806 } 4807 if (TextUtils.isEmpty(name)) { 4808 name = pm.getApplicationLabel(mContext.getApplicationInfo()); 4809 } 4810 if (TextUtils.isEmpty(name)) { 4811 // still nothing? 4812 return null; 4813 } 4814 4815 return String.valueOf(name); 4816 } 4817 private void bindHeaderAppName(RemoteViews contentView, boolean ambient) { 4818 contentView.setTextViewText(R.id.app_name_text, loadHeaderAppName()); 4819 if (isColorized() && !ambient) { 4820 setTextViewColorPrimary(contentView, R.id.app_name_text); 4821 } else { 4822 contentView.setTextColor(R.id.app_name_text, 4823 ambient ? resolveAmbientColor() : getSecondaryTextColor()); 4824 } 4825 } 4826 4827 private void bindSmallIcon(RemoteViews contentView, boolean ambient) { 4828 if (mN.mSmallIcon == null && mN.icon != 0) { 4829 mN.mSmallIcon = Icon.createWithResource(mContext, mN.icon); 4830 } 4831 contentView.setImageViewIcon(R.id.icon, mN.mSmallIcon); 4832 contentView.setInt(R.id.icon, "setImageLevel", mN.iconLevel); 4833 processSmallIconColor(mN.mSmallIcon, contentView, ambient); 4834 } 4835 4836 /** 4837 * @return true if the built notification will show the time or the chronometer; false 4838 * otherwise 4839 */ 4840 private boolean showsTimeOrChronometer() { 4841 return mN.showsTime() || mN.showsChronometer(); 4842 } 4843 4844 private void resetStandardTemplateWithActions(RemoteViews big) { 4845 // actions_container is only reset when there are no actions to avoid focus issues with 4846 // remote inputs. 4847 big.setViewVisibility(R.id.actions, View.GONE); 4848 big.removeAllViews(R.id.actions); 4849 4850 big.setViewVisibility(R.id.notification_material_reply_container, View.GONE); 4851 big.setTextViewText(R.id.notification_material_reply_text_1, null); 4852 big.setViewVisibility(R.id.notification_material_reply_text_1_container, View.GONE); 4853 big.setViewVisibility(R.id.notification_material_reply_progress, View.GONE); 4854 4855 big.setViewVisibility(R.id.notification_material_reply_text_2, View.GONE); 4856 big.setTextViewText(R.id.notification_material_reply_text_2, null); 4857 big.setViewVisibility(R.id.notification_material_reply_text_3, View.GONE); 4858 big.setTextViewText(R.id.notification_material_reply_text_3, null); 4859 4860 big.setViewLayoutMarginBottomDimen(R.id.notification_action_list_margin_target, 4861 R.dimen.notification_content_margin); 4862 } 4863 4864 private RemoteViews applyStandardTemplateWithActions(int layoutId, 4865 TemplateBindResult result) { 4866 return applyStandardTemplateWithActions(layoutId, mParams.reset().fillTextsFrom(this), 4867 result); 4868 } 4869 4870 private RemoteViews applyStandardTemplateWithActions(int layoutId, 4871 StandardTemplateParams p, TemplateBindResult result) { 4872 RemoteViews big = applyStandardTemplate(layoutId, p, result); 4873 4874 resetStandardTemplateWithActions(big); 4875 4876 boolean validRemoteInput = false; 4877 4878 int N = mActions.size(); 4879 boolean emphazisedMode = mN.fullScreenIntent != null && !p.ambient; 4880 big.setBoolean(R.id.actions, "setEmphasizedMode", emphazisedMode); 4881 if (N > 0) { 4882 big.setViewVisibility(R.id.actions_container, View.VISIBLE); 4883 big.setViewVisibility(R.id.actions, View.VISIBLE); 4884 big.setViewLayoutMarginBottomDimen(R.id.notification_action_list_margin_target, 0); 4885 if (N>MAX_ACTION_BUTTONS) N=MAX_ACTION_BUTTONS; 4886 for (int i=0; i<N; i++) { 4887 Action action = mActions.get(i); 4888 boolean actionHasValidInput = hasValidRemoteInput(action); 4889 validRemoteInput |= actionHasValidInput; 4890 4891 final RemoteViews button = generateActionButton(action, emphazisedMode, 4892 p.ambient); 4893 if (actionHasValidInput && !emphazisedMode) { 4894 // Clear the drawable 4895 button.setInt(R.id.action0, "setBackgroundResource", 0); 4896 } 4897 big.addView(R.id.actions, button); 4898 } 4899 } else { 4900 big.setViewVisibility(R.id.actions_container, View.GONE); 4901 } 4902 4903 CharSequence[] replyText = mN.extras.getCharSequenceArray(EXTRA_REMOTE_INPUT_HISTORY); 4904 if (!p.ambient && validRemoteInput && replyText != null 4905 && replyText.length > 0 && !TextUtils.isEmpty(replyText[0])) { 4906 boolean showSpinner = mN.extras.getBoolean(EXTRA_SHOW_REMOTE_INPUT_SPINNER); 4907 big.setViewVisibility(R.id.notification_material_reply_container, View.VISIBLE); 4908 big.setViewVisibility(R.id.notification_material_reply_text_1_container, 4909 View.VISIBLE); 4910 big.setTextViewText(R.id.notification_material_reply_text_1, 4911 processTextSpans(replyText[0])); 4912 setTextViewColorSecondary(big, R.id.notification_material_reply_text_1); 4913 big.setViewVisibility(R.id.notification_material_reply_progress, 4914 showSpinner ? View.VISIBLE : View.GONE); 4915 big.setProgressIndeterminateTintList( 4916 R.id.notification_material_reply_progress, 4917 ColorStateList.valueOf( 4918 isColorized() ? getPrimaryTextColor() : resolveContrastColor())); 4919 4920 if (replyText.length > 1 && !TextUtils.isEmpty(replyText[1])) { 4921 big.setViewVisibility(R.id.notification_material_reply_text_2, View.VISIBLE); 4922 big.setTextViewText(R.id.notification_material_reply_text_2, 4923 processTextSpans(replyText[1])); 4924 setTextViewColorSecondary(big, R.id.notification_material_reply_text_2); 4925 4926 if (replyText.length > 2 && !TextUtils.isEmpty(replyText[2])) { 4927 big.setViewVisibility( 4928 R.id.notification_material_reply_text_3, View.VISIBLE); 4929 big.setTextViewText(R.id.notification_material_reply_text_3, 4930 processTextSpans(replyText[2])); 4931 setTextViewColorSecondary(big, R.id.notification_material_reply_text_3); 4932 } 4933 } 4934 } 4935 4936 return big; 4937 } 4938 4939 private boolean hasValidRemoteInput(Action action) { 4940 if (TextUtils.isEmpty(action.title) || action.actionIntent == null) { 4941 // Weird actions 4942 return false; 4943 } 4944 4945 RemoteInput[] remoteInputs = action.getRemoteInputs(); 4946 if (remoteInputs == null) { 4947 return false; 4948 } 4949 4950 for (RemoteInput r : remoteInputs) { 4951 CharSequence[] choices = r.getChoices(); 4952 if (r.getAllowFreeFormInput() || (choices != null && choices.length != 0)) { 4953 return true; 4954 } 4955 } 4956 return false; 4957 } 4958 4959 /** 4960 * Construct a RemoteViews for the final 1U notification layout. In order: 4961 * 1. Custom contentView from the caller 4962 * 2. Style's proposed content view 4963 * 3. Standard template view 4964 */ 4965 public RemoteViews createContentView() { 4966 return createContentView(false /* increasedheight */ ); 4967 } 4968 4969 /** 4970 * Construct a RemoteViews for the smaller content view. 4971 * 4972 * @param increasedHeight true if this layout be created with an increased height. Some 4973 * styles may support showing more then just that basic 1U size 4974 * and the system may decide to render important notifications 4975 * slightly bigger even when collapsed. 4976 * 4977 * @hide 4978 */ 4979 public RemoteViews createContentView(boolean increasedHeight) { 4980 if (mN.contentView != null && useExistingRemoteView()) { 4981 return mN.contentView; 4982 } else if (mStyle != null) { 4983 final RemoteViews styleView = mStyle.makeContentView(increasedHeight); 4984 if (styleView != null) { 4985 return styleView; 4986 } 4987 } 4988 return applyStandardTemplate(getBaseLayoutResource(), null /* result */); 4989 } 4990 4991 private boolean useExistingRemoteView() { 4992 return mStyle == null || (!mStyle.displayCustomViewInline() 4993 && !mRebuildStyledRemoteViews); 4994 } 4995 4996 /** 4997 * Construct a RemoteViews for the final big notification layout. 4998 */ 4999 public RemoteViews createBigContentView() { 5000 RemoteViews result = null; 5001 if (mN.bigContentView != null && useExistingRemoteView()) { 5002 return mN.bigContentView; 5003 } else if (mStyle != null) { 5004 result = mStyle.makeBigContentView(); 5005 hideLine1Text(result); 5006 } else if (mActions.size() != 0) { 5007 result = applyStandardTemplateWithActions(getBigBaseLayoutResource(), 5008 null /* result */); 5009 } 5010 makeHeaderExpanded(result); 5011 return result; 5012 } 5013 5014 /** 5015 * Construct a RemoteViews for the final notification header only. This will not be 5016 * colorized. 5017 * 5018 * @param ambient if true, generate the header for the ambient display layout. 5019 * @hide 5020 */ 5021 public RemoteViews makeNotificationHeader(boolean ambient) { 5022 Boolean colorized = (Boolean) mN.extras.get(EXTRA_COLORIZED); 5023 mN.extras.putBoolean(EXTRA_COLORIZED, false); 5024 RemoteViews header = new BuilderRemoteViews(mContext.getApplicationInfo(), 5025 ambient ? R.layout.notification_template_ambient_header 5026 : R.layout.notification_template_header); 5027 resetNotificationHeader(header); 5028 bindNotificationHeader(header, ambient, null); 5029 if (colorized != null) { 5030 mN.extras.putBoolean(EXTRA_COLORIZED, colorized); 5031 } else { 5032 mN.extras.remove(EXTRA_COLORIZED); 5033 } 5034 return header; 5035 } 5036 5037 /** 5038 * Construct a RemoteViews for the ambient version of the notification. 5039 * 5040 * @hide 5041 */ 5042 public RemoteViews makeAmbientNotification() { 5043 RemoteViews ambient = applyStandardTemplateWithActions( 5044 R.layout.notification_template_material_ambient, 5045 mParams.reset().ambient(true).fillTextsFrom(this).hasProgress(false), 5046 null /* result */); 5047 return ambient; 5048 } 5049 5050 private void hideLine1Text(RemoteViews result) { 5051 if (result != null) { 5052 result.setViewVisibility(R.id.text_line_1, View.GONE); 5053 } 5054 } 5055 5056 /** 5057 * Adapt the Notification header if this view is used as an expanded view. 5058 * 5059 * @hide 5060 */ 5061 public static void makeHeaderExpanded(RemoteViews result) { 5062 if (result != null) { 5063 result.setBoolean(R.id.notification_header, "setExpanded", true); 5064 } 5065 } 5066 5067 /** 5068 * Construct a RemoteViews for the final heads-up notification layout. 5069 * 5070 * @param increasedHeight true if this layout be created with an increased height. Some 5071 * styles may support showing more then just that basic 1U size 5072 * and the system may decide to render important notifications 5073 * slightly bigger even when collapsed. 5074 * 5075 * @hide 5076 */ 5077 public RemoteViews createHeadsUpContentView(boolean increasedHeight) { 5078 if (mN.headsUpContentView != null && useExistingRemoteView()) { 5079 return mN.headsUpContentView; 5080 } else if (mStyle != null) { 5081 final RemoteViews styleView = mStyle.makeHeadsUpContentView(increasedHeight); 5082 if (styleView != null) { 5083 return styleView; 5084 } 5085 } else if (mActions.size() == 0) { 5086 return null; 5087 } 5088 5089 return applyStandardTemplateWithActions(getBigBaseLayoutResource(), null /* result */); 5090 } 5091 5092 /** 5093 * Construct a RemoteViews for the final heads-up notification layout. 5094 */ 5095 public RemoteViews createHeadsUpContentView() { 5096 return createHeadsUpContentView(false /* useIncreasedHeight */); 5097 } 5098 5099 /** 5100 * Construct a RemoteViews for the display in public contexts like on the lockscreen. 5101 * 5102 * @hide 5103 */ 5104 public RemoteViews makePublicContentView() { 5105 return makePublicView(false /* ambient */); 5106 } 5107 5108 /** 5109 * Construct a RemoteViews for the display in public contexts like on the lockscreen. 5110 * 5111 * @hide 5112 */ 5113 public RemoteViews makePublicAmbientNotification() { 5114 return makePublicView(true /* ambient */); 5115 } 5116 5117 private RemoteViews makePublicView(boolean ambient) { 5118 if (mN.publicVersion != null) { 5119 final Builder builder = recoverBuilder(mContext, mN.publicVersion); 5120 return ambient ? builder.makeAmbientNotification() : builder.createContentView(); 5121 } 5122 Bundle savedBundle = mN.extras; 5123 Style style = mStyle; 5124 mStyle = null; 5125 Icon largeIcon = mN.mLargeIcon; 5126 mN.mLargeIcon = null; 5127 Bitmap largeIconLegacy = mN.largeIcon; 5128 mN.largeIcon = null; 5129 ArrayList<Action> actions = mActions; 5130 mActions = new ArrayList<>(); 5131 Bundle publicExtras = new Bundle(); 5132 publicExtras.putBoolean(EXTRA_SHOW_WHEN, 5133 savedBundle.getBoolean(EXTRA_SHOW_WHEN)); 5134 publicExtras.putBoolean(EXTRA_SHOW_CHRONOMETER, 5135 savedBundle.getBoolean(EXTRA_SHOW_CHRONOMETER)); 5136 publicExtras.putBoolean(EXTRA_CHRONOMETER_COUNT_DOWN, 5137 savedBundle.getBoolean(EXTRA_CHRONOMETER_COUNT_DOWN)); 5138 String appName = savedBundle.getString(EXTRA_SUBSTITUTE_APP_NAME); 5139 if (appName != null) { 5140 publicExtras.putString(EXTRA_SUBSTITUTE_APP_NAME, appName); 5141 } 5142 mN.extras = publicExtras; 5143 RemoteViews view; 5144 if (ambient) { 5145 publicExtras.putCharSequence(EXTRA_TITLE, 5146 mContext.getString(com.android.internal.R.string.notification_hidden_text)); 5147 view = makeAmbientNotification(); 5148 } else{ 5149 view = makeNotificationHeader(false /* ambient */); 5150 view.setBoolean(R.id.notification_header, "setExpandOnlyOnButton", true); 5151 } 5152 mN.extras = savedBundle; 5153 mN.mLargeIcon = largeIcon; 5154 mN.largeIcon = largeIconLegacy; 5155 mActions = actions; 5156 mStyle = style; 5157 return view; 5158 } 5159 5160 /** 5161 * Construct a content view for the display when low - priority 5162 * 5163 * @param useRegularSubtext uses the normal subtext set if there is one available. Otherwise 5164 * a new subtext is created consisting of the content of the 5165 * notification. 5166 * @hide 5167 */ 5168 public RemoteViews makeLowPriorityContentView(boolean useRegularSubtext) { 5169 int color = mN.color; 5170 mN.color = COLOR_DEFAULT; 5171 CharSequence summary = mN.extras.getCharSequence(EXTRA_SUB_TEXT); 5172 if (!useRegularSubtext || TextUtils.isEmpty(summary)) { 5173 CharSequence newSummary = createSummaryText(); 5174 if (!TextUtils.isEmpty(newSummary)) { 5175 mN.extras.putCharSequence(EXTRA_SUB_TEXT, newSummary); 5176 } 5177 } 5178 5179 RemoteViews header = makeNotificationHeader(false /* ambient */); 5180 header.setBoolean(R.id.notification_header, "setAcceptAllTouches", true); 5181 if (summary != null) { 5182 mN.extras.putCharSequence(EXTRA_SUB_TEXT, summary); 5183 } else { 5184 mN.extras.remove(EXTRA_SUB_TEXT); 5185 } 5186 mN.color = color; 5187 return header; 5188 } 5189 5190 private CharSequence createSummaryText() { 5191 CharSequence titleText = mN.extras.getCharSequence(Notification.EXTRA_TITLE); 5192 if (USE_ONLY_TITLE_IN_LOW_PRIORITY_SUMMARY) { 5193 return titleText; 5194 } 5195 SpannableStringBuilder summary = new SpannableStringBuilder(); 5196 if (titleText == null) { 5197 titleText = mN.extras.getCharSequence(Notification.EXTRA_TITLE_BIG); 5198 } 5199 BidiFormatter bidi = BidiFormatter.getInstance(); 5200 if (titleText != null) { 5201 summary.append(bidi.unicodeWrap(titleText)); 5202 } 5203 CharSequence contentText = mN.extras.getCharSequence(Notification.EXTRA_TEXT); 5204 if (titleText != null && contentText != null) { 5205 summary.append(bidi.unicodeWrap(mContext.getText( 5206 R.string.notification_header_divider_symbol_with_spaces))); 5207 } 5208 if (contentText != null) { 5209 summary.append(bidi.unicodeWrap(contentText)); 5210 } 5211 return summary; 5212 } 5213 5214 private RemoteViews generateActionButton(Action action, boolean emphazisedMode, 5215 boolean ambient) { 5216 final boolean tombstone = (action.actionIntent == null); 5217 RemoteViews button = new BuilderRemoteViews(mContext.getApplicationInfo(), 5218 emphazisedMode ? getEmphasizedActionLayoutResource() 5219 : tombstone ? getActionTombstoneLayoutResource() 5220 : getActionLayoutResource()); 5221 if (!tombstone) { 5222 button.setOnClickPendingIntent(R.id.action0, action.actionIntent); 5223 } 5224 button.setContentDescription(R.id.action0, action.title); 5225 if (action.mRemoteInputs != null) { 5226 button.setRemoteInputs(R.id.action0, action.mRemoteInputs); 5227 } 5228 if (emphazisedMode) { 5229 // change the background bgColor 5230 CharSequence title = action.title; 5231 ColorStateList[] outResultColor = null; 5232 int background = resolveBackgroundColor(); 5233 if (isLegacy()) { 5234 title = NotificationColorUtil.clearColorSpans(title); 5235 } else { 5236 outResultColor = new ColorStateList[1]; 5237 title = ensureColorSpanContrast(title, background, outResultColor); 5238 } 5239 button.setTextViewText(R.id.action0, processTextSpans(title)); 5240 setTextViewColorPrimary(button, R.id.action0); 5241 int rippleColor; 5242 boolean hasColorOverride = outResultColor != null && outResultColor[0] != null; 5243 if (hasColorOverride) { 5244 // There's a span spanning the full text, let's take it and use it as the 5245 // background color 5246 background = outResultColor[0].getDefaultColor(); 5247 int textColor = NotificationColorUtil.resolvePrimaryColor(mContext, 5248 background); 5249 button.setTextColor(R.id.action0, textColor); 5250 rippleColor = textColor; 5251 } else if (mN.color != COLOR_DEFAULT && !isColorized() && mTintActionButtons) { 5252 rippleColor = resolveContrastColor(); 5253 button.setTextColor(R.id.action0, rippleColor); 5254 } else { 5255 rippleColor = getPrimaryTextColor(); 5256 } 5257 // We only want about 20% alpha for the ripple 5258 rippleColor = (rippleColor & 0x00ffffff) | 0x33000000; 5259 button.setColorStateList(R.id.action0, "setRippleColor", 5260 ColorStateList.valueOf(rippleColor)); 5261 button.setColorStateList(R.id.action0, "setButtonBackground", 5262 ColorStateList.valueOf(background)); 5263 button.setBoolean(R.id.action0, "setHasStroke", !hasColorOverride); 5264 } else { 5265 button.setTextViewText(R.id.action0, processTextSpans( 5266 processLegacyText(action.title))); 5267 if (isColorized() && !ambient) { 5268 setTextViewColorPrimary(button, R.id.action0); 5269 } else if (mN.color != COLOR_DEFAULT && mTintActionButtons) { 5270 button.setTextColor(R.id.action0, 5271 ambient ? resolveAmbientColor() : resolveContrastColor()); 5272 } 5273 } 5274 return button; 5275 } 5276 5277 /** 5278 * Ensures contrast on color spans against a background color. also returns the color of the 5279 * text if a span was found that spans over the whole text. 5280 * 5281 * @param charSequence the charSequence on which the spans are 5282 * @param background the background color to ensure the contrast against 5283 * @param outResultColor an array in which a color will be returned as the first element if 5284 * there exists a full length color span. 5285 * @return the contrasted charSequence 5286 */ 5287 private CharSequence ensureColorSpanContrast(CharSequence charSequence, int background, 5288 ColorStateList[] outResultColor) { 5289 if (charSequence instanceof Spanned) { 5290 Spanned ss = (Spanned) charSequence; 5291 Object[] spans = ss.getSpans(0, ss.length(), Object.class); 5292 SpannableStringBuilder builder = new SpannableStringBuilder(ss.toString()); 5293 for (Object span : spans) { 5294 Object resultSpan = span; 5295 int spanStart = ss.getSpanStart(span); 5296 int spanEnd = ss.getSpanEnd(span); 5297 boolean fullLength = (spanEnd - spanStart) == charSequence.length(); 5298 if (resultSpan instanceof CharacterStyle) { 5299 resultSpan = ((CharacterStyle) span).getUnderlying(); 5300 } 5301 if (resultSpan instanceof TextAppearanceSpan) { 5302 TextAppearanceSpan originalSpan = (TextAppearanceSpan) resultSpan; 5303 ColorStateList textColor = originalSpan.getTextColor(); 5304 if (textColor != null) { 5305 int[] colors = textColor.getColors(); 5306 int[] newColors = new int[colors.length]; 5307 for (int i = 0; i < newColors.length; i++) { 5308 newColors[i] = NotificationColorUtil.ensureLargeTextContrast( 5309 colors[i], background, mInNightMode); 5310 } 5311 textColor = new ColorStateList(textColor.getStates().clone(), 5312 newColors); 5313 if (fullLength) { 5314 outResultColor[0] = textColor; 5315 // Let's drop the color from the span 5316 textColor = null; 5317 } 5318 resultSpan = new TextAppearanceSpan( 5319 originalSpan.getFamily(), 5320 originalSpan.getTextStyle(), 5321 originalSpan.getTextSize(), 5322 textColor, 5323 originalSpan.getLinkTextColor()); 5324 } 5325 } else if (resultSpan instanceof ForegroundColorSpan) { 5326 ForegroundColorSpan originalSpan = (ForegroundColorSpan) resultSpan; 5327 int foregroundColor = originalSpan.getForegroundColor(); 5328 foregroundColor = NotificationColorUtil.ensureLargeTextContrast( 5329 foregroundColor, background, mInNightMode); 5330 if (fullLength) { 5331 outResultColor[0] = ColorStateList.valueOf(foregroundColor); 5332 resultSpan = null; 5333 } else { 5334 resultSpan = new ForegroundColorSpan(foregroundColor); 5335 } 5336 } else { 5337 resultSpan = span; 5338 } 5339 if (resultSpan != null) { 5340 builder.setSpan(resultSpan, spanStart, spanEnd, ss.getSpanFlags(span)); 5341 } 5342 } 5343 return builder; 5344 } 5345 return charSequence; 5346 } 5347 5348 /** 5349 * @return Whether we are currently building a notification from a legacy (an app that 5350 * doesn't create material notifications by itself) app. 5351 */ 5352 private boolean isLegacy() { 5353 if (!mIsLegacyInitialized) { 5354 mIsLegacy = mContext.getApplicationInfo().targetSdkVersion 5355 < Build.VERSION_CODES.LOLLIPOP; 5356 mIsLegacyInitialized = true; 5357 } 5358 return mIsLegacy; 5359 } 5360 5361 private CharSequence processLegacyText(CharSequence charSequence) { 5362 return processLegacyText(charSequence, false /* ambient */); 5363 } 5364 5365 private CharSequence processLegacyText(CharSequence charSequence, boolean ambient) { 5366 boolean isAlreadyLightText = isLegacy() || textColorsNeedInversion(); 5367 boolean wantLightText = ambient; 5368 if (isAlreadyLightText != wantLightText) { 5369 return getColorUtil().invertCharSequenceColors(charSequence); 5370 } else { 5371 return charSequence; 5372 } 5373 } 5374 5375 /** 5376 * Apply any necessariy colors to the small icon 5377 */ 5378 private void processSmallIconColor(Icon smallIcon, RemoteViews contentView, 5379 boolean ambient) { 5380 boolean colorable = !isLegacy() || getColorUtil().isGrayscaleIcon(mContext, smallIcon); 5381 int color; 5382 if (ambient) { 5383 color = resolveAmbientColor(); 5384 } else if (isColorized()) { 5385 color = getPrimaryTextColor(); 5386 } else { 5387 color = resolveContrastColor(); 5388 } 5389 if (colorable) { 5390 contentView.setDrawableTint(R.id.icon, false, color, 5391 PorterDuff.Mode.SRC_ATOP); 5392 5393 } 5394 contentView.setInt(R.id.notification_header, "setOriginalIconColor", 5395 colorable ? color : NotificationHeaderView.NO_COLOR); 5396 } 5397 5398 /** 5399 * Make the largeIcon dark if it's a fake smallIcon (that is, 5400 * if it's grayscale). 5401 */ 5402 // TODO: also check bounds, transparency, that sort of thing. 5403 private void processLargeLegacyIcon(Icon largeIcon, RemoteViews contentView) { 5404 if (largeIcon != null && isLegacy() 5405 && getColorUtil().isGrayscaleIcon(mContext, largeIcon)) { 5406 // resolve color will fall back to the default when legacy 5407 contentView.setDrawableTint(R.id.icon, false, resolveContrastColor(), 5408 PorterDuff.Mode.SRC_ATOP); 5409 } 5410 } 5411 5412 private void sanitizeColor() { 5413 if (mN.color != COLOR_DEFAULT) { 5414 mN.color |= 0xFF000000; // no alpha for custom colors 5415 } 5416 } 5417 5418 int resolveContrastColor() { 5419 if (mCachedContrastColorIsFor == mN.color && mCachedContrastColor != COLOR_INVALID) { 5420 return mCachedContrastColor; 5421 } 5422 5423 int color; 5424 int background = mContext.getColor( 5425 com.android.internal.R.color.notification_material_background_color); 5426 if (mN.color == COLOR_DEFAULT) { 5427 ensureColors(); 5428 color = NotificationColorUtil.resolveDefaultColor(mContext, background); 5429 } else { 5430 color = NotificationColorUtil.resolveContrastColor(mContext, mN.color, 5431 background, mInNightMode); 5432 } 5433 if (Color.alpha(color) < 255) { 5434 // alpha doesn't go well for color filters, so let's blend it manually 5435 color = NotificationColorUtil.compositeColors(color, background); 5436 } 5437 mCachedContrastColorIsFor = mN.color; 5438 return mCachedContrastColor = color; 5439 } 5440 5441 int resolveNeutralColor() { 5442 if (mNeutralColor != COLOR_INVALID) { 5443 return mNeutralColor; 5444 } 5445 int background = mContext.getColor( 5446 com.android.internal.R.color.notification_material_background_color); 5447 mNeutralColor = NotificationColorUtil.resolveDefaultColor(mContext, background); 5448 if (Color.alpha(mNeutralColor) < 255) { 5449 // alpha doesn't go well for color filters, so let's blend it manually 5450 mNeutralColor = NotificationColorUtil.compositeColors(mNeutralColor, background); 5451 } 5452 return mNeutralColor; 5453 } 5454 5455 int resolveAmbientColor() { 5456 if (mCachedAmbientColorIsFor == mN.color && mCachedAmbientColorIsFor != COLOR_INVALID) { 5457 return mCachedAmbientColor; 5458 } 5459 final int contrasted = NotificationColorUtil.resolveAmbientColor(mContext, mN.color); 5460 5461 mCachedAmbientColorIsFor = mN.color; 5462 return mCachedAmbientColor = contrasted; 5463 } 5464 5465 /** 5466 * Apply the unstyled operations and return a new {@link Notification} object. 5467 * @hide 5468 */ 5469 public Notification buildUnstyled() { 5470 if (mActions.size() > 0) { 5471 mN.actions = new Action[mActions.size()]; 5472 mActions.toArray(mN.actions); 5473 } 5474 if (!mPersonList.isEmpty()) { 5475 mN.extras.putParcelableArrayList(EXTRA_PEOPLE_LIST, mPersonList); 5476 } 5477 if (mN.bigContentView != null || mN.contentView != null 5478 || mN.headsUpContentView != null) { 5479 mN.extras.putBoolean(EXTRA_CONTAINS_CUSTOM_VIEW, true); 5480 } 5481 return mN; 5482 } 5483 5484 /** 5485 * Creates a Builder from an existing notification so further changes can be made. 5486 * @param context The context for your application / activity. 5487 * @param n The notification to create a Builder from. 5488 */ 5489 public static Notification.Builder recoverBuilder(Context context, Notification n) { 5490 // Re-create notification context so we can access app resources. 5491 ApplicationInfo applicationInfo = n.extras.getParcelable( 5492 EXTRA_BUILDER_APPLICATION_INFO); 5493 Context builderContext; 5494 if (applicationInfo != null) { 5495 try { 5496 builderContext = context.createApplicationContext(applicationInfo, 5497 Context.CONTEXT_RESTRICTED); 5498 } catch (NameNotFoundException e) { 5499 Log.e(TAG, "ApplicationInfo " + applicationInfo + " not found"); 5500 builderContext = context; // try with our context 5501 } 5502 } else { 5503 builderContext = context; // try with given context 5504 } 5505 5506 return new Builder(builderContext, n); 5507 } 5508 5509 /** 5510 * @deprecated Use {@link #build()} instead. 5511 */ 5512 @Deprecated 5513 public Notification getNotification() { 5514 return build(); 5515 } 5516 5517 /** 5518 * Combine all of the options that have been set and return a new {@link Notification} 5519 * object. 5520 */ 5521 public Notification build() { 5522 // first, add any extras from the calling code 5523 if (mUserExtras != null) { 5524 mN.extras = getAllExtras(); 5525 } 5526 5527 mN.creationTime = System.currentTimeMillis(); 5528 5529 // lazy stuff from mContext; see comment in Builder(Context, Notification) 5530 Notification.addFieldsFromContext(mContext, mN); 5531 5532 buildUnstyled(); 5533 5534 if (mStyle != null) { 5535 mStyle.reduceImageSizes(mContext); 5536 mStyle.purgeResources(); 5537 mStyle.validate(mContext); 5538 mStyle.buildStyled(mN); 5539 } 5540 mN.reduceImageSizes(mContext); 5541 5542 if (mContext.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N 5543 && (useExistingRemoteView())) { 5544 if (mN.contentView == null) { 5545 mN.contentView = createContentView(); 5546 mN.extras.putInt(EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT, 5547 mN.contentView.getSequenceNumber()); 5548 } 5549 if (mN.bigContentView == null) { 5550 mN.bigContentView = createBigContentView(); 5551 if (mN.bigContentView != null) { 5552 mN.extras.putInt(EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT, 5553 mN.bigContentView.getSequenceNumber()); 5554 } 5555 } 5556 if (mN.headsUpContentView == null) { 5557 mN.headsUpContentView = createHeadsUpContentView(); 5558 if (mN.headsUpContentView != null) { 5559 mN.extras.putInt(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT, 5560 mN.headsUpContentView.getSequenceNumber()); 5561 } 5562 } 5563 } 5564 5565 if ((mN.defaults & DEFAULT_LIGHTS) != 0) { 5566 mN.flags |= FLAG_SHOW_LIGHTS; 5567 } 5568 5569 mN.allPendingIntents = null; 5570 5571 return mN; 5572 } 5573 5574 /** 5575 * Apply this Builder to an existing {@link Notification} object. 5576 * 5577 * @hide 5578 */ 5579 public Notification buildInto(Notification n) { 5580 build().cloneInto(n, true); 5581 return n; 5582 } 5583 5584 /** 5585 * Removes RemoteViews that were created for compatibility from {@param n}, if they did not 5586 * change. Also removes extenders on low ram devices, as 5587 * {@link android.service.notification.NotificationListenerService} services are disabled. 5588 * 5589 * @return {@param n}, if no stripping is needed, otherwise a stripped clone of {@param n}. 5590 * 5591 * @hide 5592 */ 5593 public static Notification maybeCloneStrippedForDelivery(Notification n, boolean isLowRam, 5594 Context context) { 5595 String templateClass = n.extras.getString(EXTRA_TEMPLATE); 5596 5597 // Only strip views for known Styles because we won't know how to 5598 // re-create them otherwise. 5599 if (!isLowRam 5600 && !TextUtils.isEmpty(templateClass) 5601 && getNotificationStyleClass(templateClass) == null) { 5602 return n; 5603 } 5604 5605 // Only strip unmodified BuilderRemoteViews. 5606 boolean stripContentView = n.contentView instanceof BuilderRemoteViews && 5607 n.extras.getInt(EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT, -1) == 5608 n.contentView.getSequenceNumber(); 5609 boolean stripBigContentView = n.bigContentView instanceof BuilderRemoteViews && 5610 n.extras.getInt(EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT, -1) == 5611 n.bigContentView.getSequenceNumber(); 5612 boolean stripHeadsUpContentView = n.headsUpContentView instanceof BuilderRemoteViews && 5613 n.extras.getInt(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT, -1) == 5614 n.headsUpContentView.getSequenceNumber(); 5615 5616 // Nothing to do here, no need to clone. 5617 if (!isLowRam 5618 && !stripContentView && !stripBigContentView && !stripHeadsUpContentView) { 5619 return n; 5620 } 5621 5622 Notification clone = n.clone(); 5623 if (stripContentView) { 5624 clone.contentView = null; 5625 clone.extras.remove(EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT); 5626 } 5627 if (stripBigContentView) { 5628 clone.bigContentView = null; 5629 clone.extras.remove(EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT); 5630 } 5631 if (stripHeadsUpContentView) { 5632 clone.headsUpContentView = null; 5633 clone.extras.remove(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT); 5634 } 5635 if (isLowRam) { 5636 String[] allowedServices = context.getResources().getStringArray( 5637 R.array.config_allowedManagedServicesOnLowRamDevices); 5638 if (allowedServices.length == 0) { 5639 clone.extras.remove(Notification.TvExtender.EXTRA_TV_EXTENDER); 5640 clone.extras.remove(WearableExtender.EXTRA_WEARABLE_EXTENSIONS); 5641 clone.extras.remove(CarExtender.EXTRA_CAR_EXTENDER); 5642 } 5643 } 5644 return clone; 5645 } 5646 5647 private int getBaseLayoutResource() { 5648 return R.layout.notification_template_material_base; 5649 } 5650 5651 private int getBigBaseLayoutResource() { 5652 return R.layout.notification_template_material_big_base; 5653 } 5654 5655 private int getBigPictureLayoutResource() { 5656 return R.layout.notification_template_material_big_picture; 5657 } 5658 5659 private int getBigTextLayoutResource() { 5660 return R.layout.notification_template_material_big_text; 5661 } 5662 5663 private int getInboxLayoutResource() { 5664 return R.layout.notification_template_material_inbox; 5665 } 5666 5667 private int getMessagingLayoutResource() { 5668 return R.layout.notification_template_material_messaging; 5669 } 5670 5671 private int getActionLayoutResource() { 5672 return R.layout.notification_material_action; 5673 } 5674 5675 private int getEmphasizedActionLayoutResource() { 5676 return R.layout.notification_material_action_emphasized; 5677 } 5678 5679 private int getActionTombstoneLayoutResource() { 5680 return R.layout.notification_material_action_tombstone; 5681 } 5682 5683 private int getBackgroundColor() { 5684 if (isColorized()) { 5685 return mBackgroundColor != COLOR_INVALID ? mBackgroundColor : mN.color; 5686 } else { 5687 return COLOR_DEFAULT; 5688 } 5689 } 5690 5691 /** 5692 * Gets a neutral color that can be used for icons or similar that should not stand out. 5693 */ 5694 private int getNeutralColor() { 5695 if (isColorized()) { 5696 return getSecondaryTextColor(); 5697 } else { 5698 return resolveNeutralColor(); 5699 } 5700 } 5701 5702 /** 5703 * Same as getBackgroundColor but also resolved the default color to the background. 5704 */ 5705 private int resolveBackgroundColor() { 5706 int backgroundColor = getBackgroundColor(); 5707 if (backgroundColor == COLOR_DEFAULT) { 5708 backgroundColor = mContext.getColor( 5709 com.android.internal.R.color.notification_material_background_color); 5710 } 5711 return backgroundColor; 5712 } 5713 5714 private boolean isColorized() { 5715 return mN.isColorized(); 5716 } 5717 5718 private boolean shouldTintActionButtons() { 5719 return mTintActionButtons; 5720 } 5721 5722 private boolean textColorsNeedInversion() { 5723 if (mStyle == null || !MediaStyle.class.equals(mStyle.getClass())) { 5724 return false; 5725 } 5726 int targetSdkVersion = mContext.getApplicationInfo().targetSdkVersion; 5727 return targetSdkVersion > Build.VERSION_CODES.M 5728 && targetSdkVersion < Build.VERSION_CODES.O; 5729 } 5730 5731 /** 5732 * Set a color palette to be used as the background and textColors 5733 * 5734 * @param backgroundColor the color to be used as the background 5735 * @param foregroundColor the color to be used as the foreground 5736 * 5737 * @hide 5738 */ 5739 public void setColorPalette(int backgroundColor, int foregroundColor) { 5740 mBackgroundColor = backgroundColor; 5741 mForegroundColor = foregroundColor; 5742 mTextColorsAreForBackground = COLOR_INVALID; 5743 ensureColors(); 5744 } 5745 5746 /** 5747 * Forces all styled remoteViews to be built from scratch and not use any cached 5748 * RemoteViews. 5749 * This is needed for legacy apps that are baking in their remoteviews into the 5750 * notification. 5751 * 5752 * @hide 5753 */ 5754 public void setRebuildStyledRemoteViews(boolean rebuild) { 5755 mRebuildStyledRemoteViews = rebuild; 5756 } 5757 5758 /** 5759 * Get the text that should be displayed in the statusBar when heads upped. This is 5760 * usually just the app name, but may be different depending on the style. 5761 * 5762 * @param publicMode If true, return a text that is safe to display in public. 5763 * 5764 * @hide 5765 */ 5766 public CharSequence getHeadsUpStatusBarText(boolean publicMode) { 5767 if (mStyle != null && !publicMode) { 5768 CharSequence text = mStyle.getHeadsUpStatusBarText(); 5769 if (!TextUtils.isEmpty(text)) { 5770 return text; 5771 } 5772 } 5773 return loadHeaderAppName(); 5774 } 5775 } 5776 5777 /** 5778 * Reduces the image sizes to conform to a maximum allowed size. This also processes all custom 5779 * remote views. 5780 * 5781 * @hide 5782 */ 5783 void reduceImageSizes(Context context) { 5784 if (extras.getBoolean(EXTRA_REDUCED_IMAGES)) { 5785 return; 5786 } 5787 boolean isLowRam = ActivityManager.isLowRamDeviceStatic(); 5788 if (mLargeIcon != null || largeIcon != null) { 5789 Resources resources = context.getResources(); 5790 Class<? extends Style> style = getNotificationStyle(); 5791 int maxWidth = resources.getDimensionPixelSize(isLowRam 5792 ? R.dimen.notification_right_icon_size_low_ram 5793 : R.dimen.notification_right_icon_size); 5794 int maxHeight = maxWidth; 5795 if (MediaStyle.class.equals(style) 5796 || DecoratedMediaCustomViewStyle.class.equals(style)) { 5797 maxHeight = resources.getDimensionPixelSize(isLowRam 5798 ? R.dimen.notification_media_image_max_height_low_ram 5799 : R.dimen.notification_media_image_max_height); 5800 maxWidth = resources.getDimensionPixelSize(isLowRam 5801 ? R.dimen.notification_media_image_max_width_low_ram 5802 : R.dimen.notification_media_image_max_width); 5803 } 5804 if (mLargeIcon != null) { 5805 mLargeIcon.scaleDownIfNecessary(maxWidth, maxHeight); 5806 } 5807 if (largeIcon != null) { 5808 largeIcon = Icon.scaleDownIfNecessary(largeIcon, maxWidth, maxHeight); 5809 } 5810 } 5811 reduceImageSizesForRemoteView(contentView, context, isLowRam); 5812 reduceImageSizesForRemoteView(headsUpContentView, context, isLowRam); 5813 reduceImageSizesForRemoteView(bigContentView, context, isLowRam); 5814 extras.putBoolean(EXTRA_REDUCED_IMAGES, true); 5815 } 5816 5817 private void reduceImageSizesForRemoteView(RemoteViews remoteView, Context context, 5818 boolean isLowRam) { 5819 if (remoteView != null) { 5820 Resources resources = context.getResources(); 5821 int maxWidth = resources.getDimensionPixelSize(isLowRam 5822 ? R.dimen.notification_custom_view_max_image_width_low_ram 5823 : R.dimen.notification_custom_view_max_image_width); 5824 int maxHeight = resources.getDimensionPixelSize(isLowRam 5825 ? R.dimen.notification_custom_view_max_image_height_low_ram 5826 : R.dimen.notification_custom_view_max_image_height); 5827 remoteView.reduceImageSizes(maxWidth, maxHeight); 5828 } 5829 } 5830 5831 /** 5832 * @return whether this notification is a foreground service notification 5833 */ 5834 private boolean isForegroundService() { 5835 return (flags & Notification.FLAG_FOREGROUND_SERVICE) != 0; 5836 } 5837 5838 /** 5839 * @return whether this notification has a media session attached 5840 * @hide 5841 */ 5842 public boolean hasMediaSession() { 5843 return extras.getParcelable(Notification.EXTRA_MEDIA_SESSION) != null; 5844 } 5845 5846 /** 5847 * @return the style class of this notification 5848 * @hide 5849 */ 5850 public Class<? extends Notification.Style> getNotificationStyle() { 5851 String templateClass = extras.getString(Notification.EXTRA_TEMPLATE); 5852 5853 if (!TextUtils.isEmpty(templateClass)) { 5854 return Notification.getNotificationStyleClass(templateClass); 5855 } 5856 return null; 5857 } 5858 5859 /** 5860 * @return true if this notification is colorized. 5861 * 5862 * @hide 5863 */ 5864 public boolean isColorized() { 5865 if (isColorizedMedia()) { 5866 return true; 5867 } 5868 return extras.getBoolean(EXTRA_COLORIZED) 5869 && (hasColorizedPermission() || isForegroundService()); 5870 } 5871 5872 /** 5873 * Returns whether an app can colorize due to the android.permission.USE_COLORIZED_NOTIFICATIONS 5874 * permission. The permission is checked when a notification is enqueued. 5875 */ 5876 private boolean hasColorizedPermission() { 5877 return (flags & Notification.FLAG_CAN_COLORIZE) != 0; 5878 } 5879 5880 /** 5881 * @return true if this notification is colorized and it is a media notification 5882 * 5883 * @hide 5884 */ 5885 public boolean isColorizedMedia() { 5886 Class<? extends Style> style = getNotificationStyle(); 5887 if (MediaStyle.class.equals(style)) { 5888 Boolean colorized = (Boolean) extras.get(EXTRA_COLORIZED); 5889 if ((colorized == null || colorized) && hasMediaSession()) { 5890 return true; 5891 } 5892 } else if (DecoratedMediaCustomViewStyle.class.equals(style)) { 5893 if (extras.getBoolean(EXTRA_COLORIZED) && hasMediaSession()) { 5894 return true; 5895 } 5896 } 5897 return false; 5898 } 5899 5900 5901 /** 5902 * @return true if this is a media notification 5903 * 5904 * @hide 5905 */ 5906 public boolean isMediaNotification() { 5907 Class<? extends Style> style = getNotificationStyle(); 5908 if (MediaStyle.class.equals(style)) { 5909 return true; 5910 } else if (DecoratedMediaCustomViewStyle.class.equals(style)) { 5911 return true; 5912 } 5913 return false; 5914 } 5915 5916 private boolean hasLargeIcon() { 5917 return mLargeIcon != null || largeIcon != null; 5918 } 5919 5920 /** 5921 * @return true if the notification will show the time; false otherwise 5922 * @hide 5923 */ 5924 public boolean showsTime() { 5925 return when != 0 && extras.getBoolean(EXTRA_SHOW_WHEN); 5926 } 5927 5928 /** 5929 * @return true if the notification will show a chronometer; false otherwise 5930 * @hide 5931 */ 5932 public boolean showsChronometer() { 5933 return when != 0 && extras.getBoolean(EXTRA_SHOW_CHRONOMETER); 5934 } 5935 5936 /** 5937 * @removed 5938 */ 5939 @SystemApi 5940 public static Class<? extends Style> getNotificationStyleClass(String templateClass) { 5941 Class<? extends Style>[] classes = new Class[] { 5942 BigTextStyle.class, BigPictureStyle.class, InboxStyle.class, MediaStyle.class, 5943 DecoratedCustomViewStyle.class, DecoratedMediaCustomViewStyle.class, 5944 MessagingStyle.class }; 5945 for (Class<? extends Style> innerClass : classes) { 5946 if (templateClass.equals(innerClass.getName())) { 5947 return innerClass; 5948 } 5949 } 5950 return null; 5951 } 5952 5953 /** 5954 * An object that can apply a rich notification style to a {@link Notification.Builder} 5955 * object. 5956 */ 5957 public static abstract class Style { 5958 private CharSequence mBigContentTitle; 5959 5960 /** 5961 * @hide 5962 */ 5963 protected CharSequence mSummaryText = null; 5964 5965 /** 5966 * @hide 5967 */ 5968 protected boolean mSummaryTextSet = false; 5969 5970 protected Builder mBuilder; 5971 5972 /** 5973 * Overrides ContentTitle in the big form of the template. 5974 * This defaults to the value passed to setContentTitle(). 5975 */ 5976 protected void internalSetBigContentTitle(CharSequence title) { 5977 mBigContentTitle = title; 5978 } 5979 5980 /** 5981 * Set the first line of text after the detail section in the big form of the template. 5982 */ 5983 protected void internalSetSummaryText(CharSequence cs) { 5984 mSummaryText = cs; 5985 mSummaryTextSet = true; 5986 } 5987 5988 public void setBuilder(Builder builder) { 5989 if (mBuilder != builder) { 5990 mBuilder = builder; 5991 if (mBuilder != null) { 5992 mBuilder.setStyle(this); 5993 } 5994 } 5995 } 5996 5997 protected void checkBuilder() { 5998 if (mBuilder == null) { 5999 throw new IllegalArgumentException("Style requires a valid Builder object"); 6000 } 6001 } 6002 6003 protected RemoteViews getStandardView(int layoutId) { 6004 return getStandardView(layoutId, null); 6005 } 6006 6007 /** 6008 * Get the standard view for this style. 6009 * 6010 * @param layoutId The layout id to use 6011 * @param result The result where template bind information is saved. 6012 * @return A remoteView for this style. 6013 * @hide 6014 */ 6015 protected RemoteViews getStandardView(int layoutId, TemplateBindResult result) { 6016 checkBuilder(); 6017 6018 // Nasty. 6019 CharSequence oldBuilderContentTitle = 6020 mBuilder.getAllExtras().getCharSequence(EXTRA_TITLE); 6021 if (mBigContentTitle != null) { 6022 mBuilder.setContentTitle(mBigContentTitle); 6023 } 6024 6025 RemoteViews contentView = mBuilder.applyStandardTemplateWithActions(layoutId, result); 6026 6027 mBuilder.getAllExtras().putCharSequence(EXTRA_TITLE, oldBuilderContentTitle); 6028 6029 if (mBigContentTitle != null && mBigContentTitle.equals("")) { 6030 contentView.setViewVisibility(R.id.line1, View.GONE); 6031 } else { 6032 contentView.setViewVisibility(R.id.line1, View.VISIBLE); 6033 } 6034 6035 return contentView; 6036 } 6037 6038 /** 6039 * Construct a Style-specific RemoteViews for the collapsed notification layout. 6040 * The default implementation has nothing additional to add. 6041 * 6042 * @param increasedHeight true if this layout be created with an increased height. 6043 * @hide 6044 */ 6045 public RemoteViews makeContentView(boolean increasedHeight) { 6046 return null; 6047 } 6048 6049 /** 6050 * Construct a Style-specific RemoteViews for the final big notification layout. 6051 * @hide 6052 */ 6053 public RemoteViews makeBigContentView() { 6054 return null; 6055 } 6056 6057 /** 6058 * Construct a Style-specific RemoteViews for the final HUN layout. 6059 * 6060 * @param increasedHeight true if this layout be created with an increased height. 6061 * @hide 6062 */ 6063 public RemoteViews makeHeadsUpContentView(boolean increasedHeight) { 6064 return null; 6065 } 6066 6067 /** 6068 * Apply any style-specific extras to this notification before shipping it out. 6069 * @hide 6070 */ 6071 public void addExtras(Bundle extras) { 6072 if (mSummaryTextSet) { 6073 extras.putCharSequence(EXTRA_SUMMARY_TEXT, mSummaryText); 6074 } 6075 if (mBigContentTitle != null) { 6076 extras.putCharSequence(EXTRA_TITLE_BIG, mBigContentTitle); 6077 } 6078 extras.putString(EXTRA_TEMPLATE, this.getClass().getName()); 6079 } 6080 6081 /** 6082 * Reconstruct the internal state of this Style object from extras. 6083 * @hide 6084 */ 6085 protected void restoreFromExtras(Bundle extras) { 6086 if (extras.containsKey(EXTRA_SUMMARY_TEXT)) { 6087 mSummaryText = extras.getCharSequence(EXTRA_SUMMARY_TEXT); 6088 mSummaryTextSet = true; 6089 } 6090 if (extras.containsKey(EXTRA_TITLE_BIG)) { 6091 mBigContentTitle = extras.getCharSequence(EXTRA_TITLE_BIG); 6092 } 6093 } 6094 6095 6096 /** 6097 * @hide 6098 */ 6099 public Notification buildStyled(Notification wip) { 6100 addExtras(wip.extras); 6101 return wip; 6102 } 6103 6104 /** 6105 * @hide 6106 */ 6107 public void purgeResources() {} 6108 6109 /** 6110 * Calls {@link android.app.Notification.Builder#build()} on the Builder this Style is 6111 * attached to. 6112 * 6113 * @return the fully constructed Notification. 6114 */ 6115 public Notification build() { 6116 checkBuilder(); 6117 return mBuilder.build(); 6118 } 6119 6120 /** 6121 * @hide 6122 * @return true if the style positions the progress bar on the second line; false if the 6123 * style hides the progress bar 6124 */ 6125 protected boolean hasProgress() { 6126 return true; 6127 } 6128 6129 /** 6130 * @hide 6131 * @return Whether we should put the summary be put into the notification header 6132 */ 6133 public boolean hasSummaryInHeader() { 6134 return true; 6135 } 6136 6137 /** 6138 * @hide 6139 * @return Whether custom content views are displayed inline in the style 6140 */ 6141 public boolean displayCustomViewInline() { 6142 return false; 6143 } 6144 6145 /** 6146 * Reduces the image sizes contained in this style. 6147 * 6148 * @hide 6149 */ 6150 public void reduceImageSizes(Context context) { 6151 } 6152 6153 /** 6154 * Validate that this style was properly composed. This is called at build time. 6155 * @hide 6156 */ 6157 public void validate(Context context) { 6158 } 6159 6160 /** 6161 * @hide 6162 */ 6163 public abstract boolean areNotificationsVisiblyDifferent(Style other); 6164 6165 /** 6166 * @return the the text that should be displayed in the statusBar when heads-upped. 6167 * If {@code null} is returned, the default implementation will be used. 6168 * 6169 * @hide 6170 */ 6171 public CharSequence getHeadsUpStatusBarText() { 6172 return null; 6173 } 6174 } 6175 6176 /** 6177 * Helper class for generating large-format notifications that include a large image attachment. 6178 * 6179 * Here's how you'd set the <code>BigPictureStyle</code> on a notification: 6180 * <pre class="prettyprint"> 6181 * Notification notif = new Notification.Builder(mContext) 6182 * .setContentTitle("New photo from " + sender.toString()) 6183 * .setContentText(subject) 6184 * .setSmallIcon(R.drawable.new_post) 6185 * .setLargeIcon(aBitmap) 6186 * .setStyle(new Notification.BigPictureStyle() 6187 * .bigPicture(aBigBitmap)) 6188 * .build(); 6189 * </pre> 6190 * 6191 * @see Notification#bigContentView 6192 */ 6193 public static class BigPictureStyle extends Style { 6194 private Bitmap mPicture; 6195 private Icon mBigLargeIcon; 6196 private boolean mBigLargeIconSet = false; 6197 6198 public BigPictureStyle() { 6199 } 6200 6201 /** 6202 * @deprecated use {@code BigPictureStyle()}. 6203 */ 6204 @Deprecated 6205 public BigPictureStyle(Builder builder) { 6206 setBuilder(builder); 6207 } 6208 6209 /** 6210 * Overrides ContentTitle in the big form of the template. 6211 * This defaults to the value passed to setContentTitle(). 6212 */ 6213 public BigPictureStyle setBigContentTitle(CharSequence title) { 6214 internalSetBigContentTitle(safeCharSequence(title)); 6215 return this; 6216 } 6217 6218 /** 6219 * Set the first line of text after the detail section in the big form of the template. 6220 */ 6221 public BigPictureStyle setSummaryText(CharSequence cs) { 6222 internalSetSummaryText(safeCharSequence(cs)); 6223 return this; 6224 } 6225 6226 /** 6227 * @hide 6228 */ 6229 public Bitmap getBigPicture() { 6230 return mPicture; 6231 } 6232 6233 /** 6234 * Provide the bitmap to be used as the payload for the BigPicture notification. 6235 */ 6236 public BigPictureStyle bigPicture(Bitmap b) { 6237 mPicture = b; 6238 return this; 6239 } 6240 6241 /** 6242 * Override the large icon when the big notification is shown. 6243 */ 6244 public BigPictureStyle bigLargeIcon(Bitmap b) { 6245 return bigLargeIcon(b != null ? Icon.createWithBitmap(b) : null); 6246 } 6247 6248 /** 6249 * Override the large icon when the big notification is shown. 6250 */ 6251 public BigPictureStyle bigLargeIcon(Icon icon) { 6252 mBigLargeIconSet = true; 6253 mBigLargeIcon = icon; 6254 return this; 6255 } 6256 6257 /** @hide */ 6258 public static final int MIN_ASHMEM_BITMAP_SIZE = 128 * (1 << 10); 6259 6260 /** 6261 * @hide 6262 */ 6263 @Override 6264 public void purgeResources() { 6265 super.purgeResources(); 6266 if (mPicture != null && 6267 mPicture.isMutable() && 6268 mPicture.getAllocationByteCount() >= MIN_ASHMEM_BITMAP_SIZE) { 6269 mPicture = mPicture.createAshmemBitmap(); 6270 } 6271 if (mBigLargeIcon != null) { 6272 mBigLargeIcon.convertToAshmem(); 6273 } 6274 } 6275 6276 /** 6277 * @hide 6278 */ 6279 @Override 6280 public void reduceImageSizes(Context context) { 6281 super.reduceImageSizes(context); 6282 Resources resources = context.getResources(); 6283 boolean isLowRam = ActivityManager.isLowRamDeviceStatic(); 6284 if (mPicture != null) { 6285 int maxPictureWidth = resources.getDimensionPixelSize(isLowRam 6286 ? R.dimen.notification_big_picture_max_height_low_ram 6287 : R.dimen.notification_big_picture_max_height); 6288 int maxPictureHeight = resources.getDimensionPixelSize(isLowRam 6289 ? R.dimen.notification_big_picture_max_width_low_ram 6290 : R.dimen.notification_big_picture_max_width); 6291 mPicture = Icon.scaleDownIfNecessary(mPicture, maxPictureWidth, maxPictureHeight); 6292 } 6293 if (mBigLargeIcon != null) { 6294 int rightIconSize = resources.getDimensionPixelSize(isLowRam 6295 ? R.dimen.notification_right_icon_size_low_ram 6296 : R.dimen.notification_right_icon_size); 6297 mBigLargeIcon.scaleDownIfNecessary(rightIconSize, rightIconSize); 6298 } 6299 } 6300 6301 /** 6302 * @hide 6303 */ 6304 public RemoteViews makeBigContentView() { 6305 // Replace mN.mLargeIcon with mBigLargeIcon if mBigLargeIconSet 6306 // This covers the following cases: 6307 // 1. mBigLargeIconSet -> mBigLargeIcon (null or non-null) applies, overrides 6308 // mN.mLargeIcon 6309 // 2. !mBigLargeIconSet -> mN.mLargeIcon applies 6310 Icon oldLargeIcon = null; 6311 Bitmap largeIconLegacy = null; 6312 if (mBigLargeIconSet) { 6313 oldLargeIcon = mBuilder.mN.mLargeIcon; 6314 mBuilder.mN.mLargeIcon = mBigLargeIcon; 6315 // The legacy largeIcon might not allow us to clear the image, as it's taken in 6316 // replacement if the other one is null. Because we're restoring these legacy icons 6317 // for old listeners, this is in general non-null. 6318 largeIconLegacy = mBuilder.mN.largeIcon; 6319 mBuilder.mN.largeIcon = null; 6320 } 6321 6322 RemoteViews contentView = getStandardView(mBuilder.getBigPictureLayoutResource(), 6323 null /* result */); 6324 if (mSummaryTextSet) { 6325 contentView.setTextViewText(R.id.text, mBuilder.processTextSpans( 6326 mBuilder.processLegacyText(mSummaryText))); 6327 mBuilder.setTextViewColorSecondary(contentView, R.id.text); 6328 contentView.setViewVisibility(R.id.text, View.VISIBLE); 6329 } 6330 mBuilder.setContentMinHeight(contentView, mBuilder.mN.hasLargeIcon()); 6331 6332 if (mBigLargeIconSet) { 6333 mBuilder.mN.mLargeIcon = oldLargeIcon; 6334 mBuilder.mN.largeIcon = largeIconLegacy; 6335 } 6336 6337 contentView.setImageViewBitmap(R.id.big_picture, mPicture); 6338 return contentView; 6339 } 6340 6341 /** 6342 * @hide 6343 */ 6344 public void addExtras(Bundle extras) { 6345 super.addExtras(extras); 6346 6347 if (mBigLargeIconSet) { 6348 extras.putParcelable(EXTRA_LARGE_ICON_BIG, mBigLargeIcon); 6349 } 6350 extras.putParcelable(EXTRA_PICTURE, mPicture); 6351 } 6352 6353 /** 6354 * @hide 6355 */ 6356 @Override 6357 protected void restoreFromExtras(Bundle extras) { 6358 super.restoreFromExtras(extras); 6359 6360 if (extras.containsKey(EXTRA_LARGE_ICON_BIG)) { 6361 mBigLargeIconSet = true; 6362 mBigLargeIcon = extras.getParcelable(EXTRA_LARGE_ICON_BIG); 6363 } 6364 mPicture = extras.getParcelable(EXTRA_PICTURE); 6365 } 6366 6367 /** 6368 * @hide 6369 */ 6370 @Override 6371 public boolean hasSummaryInHeader() { 6372 return false; 6373 } 6374 6375 /** 6376 * @hide 6377 * Note that we aren't actually comparing the contents of the bitmaps here, so this 6378 * is only doing a cursory inspection. Bitmaps of equal size will appear the same. 6379 */ 6380 @Override 6381 public boolean areNotificationsVisiblyDifferent(Style other) { 6382 if (other == null || getClass() != other.getClass()) { 6383 return true; 6384 } 6385 BigPictureStyle otherS = (BigPictureStyle) other; 6386 return areBitmapsObviouslyDifferent(getBigPicture(), otherS.getBigPicture()); 6387 } 6388 6389 private static boolean areBitmapsObviouslyDifferent(Bitmap a, Bitmap b) { 6390 if (a == b) { 6391 return false; 6392 } 6393 if (a == null || b == null) { 6394 return true; 6395 } 6396 return a.getWidth() != b.getWidth() 6397 || a.getHeight() != b.getHeight() 6398 || a.getConfig() != b.getConfig() 6399 || a.getGenerationId() != b.getGenerationId(); 6400 } 6401 } 6402 6403 /** 6404 * Helper class for generating large-format notifications that include a lot of text. 6405 * 6406 * Here's how you'd set the <code>BigTextStyle</code> on a notification: 6407 * <pre class="prettyprint"> 6408 * Notification notif = new Notification.Builder(mContext) 6409 * .setContentTitle("New mail from " + sender.toString()) 6410 * .setContentText(subject) 6411 * .setSmallIcon(R.drawable.new_mail) 6412 * .setLargeIcon(aBitmap) 6413 * .setStyle(new Notification.BigTextStyle() 6414 * .bigText(aVeryLongString)) 6415 * .build(); 6416 * </pre> 6417 * 6418 * @see Notification#bigContentView 6419 */ 6420 public static class BigTextStyle extends Style { 6421 6422 private CharSequence mBigText; 6423 6424 public BigTextStyle() { 6425 } 6426 6427 /** 6428 * @deprecated use {@code BigTextStyle()}. 6429 */ 6430 @Deprecated 6431 public BigTextStyle(Builder builder) { 6432 setBuilder(builder); 6433 } 6434 6435 /** 6436 * Overrides ContentTitle in the big form of the template. 6437 * This defaults to the value passed to setContentTitle(). 6438 */ 6439 public BigTextStyle setBigContentTitle(CharSequence title) { 6440 internalSetBigContentTitle(safeCharSequence(title)); 6441 return this; 6442 } 6443 6444 /** 6445 * Set the first line of text after the detail section in the big form of the template. 6446 */ 6447 public BigTextStyle setSummaryText(CharSequence cs) { 6448 internalSetSummaryText(safeCharSequence(cs)); 6449 return this; 6450 } 6451 6452 /** 6453 * Provide the longer text to be displayed in the big form of the 6454 * template in place of the content text. 6455 */ 6456 public BigTextStyle bigText(CharSequence cs) { 6457 mBigText = safeCharSequence(cs); 6458 return this; 6459 } 6460 6461 /** 6462 * @hide 6463 */ 6464 public CharSequence getBigText() { 6465 return mBigText; 6466 } 6467 6468 /** 6469 * @hide 6470 */ 6471 public void addExtras(Bundle extras) { 6472 super.addExtras(extras); 6473 6474 extras.putCharSequence(EXTRA_BIG_TEXT, mBigText); 6475 } 6476 6477 /** 6478 * @hide 6479 */ 6480 @Override 6481 protected void restoreFromExtras(Bundle extras) { 6482 super.restoreFromExtras(extras); 6483 6484 mBigText = extras.getCharSequence(EXTRA_BIG_TEXT); 6485 } 6486 6487 /** 6488 * @param increasedHeight true if this layout be created with an increased height. 6489 * 6490 * @hide 6491 */ 6492 @Override 6493 public RemoteViews makeContentView(boolean increasedHeight) { 6494 if (increasedHeight) { 6495 mBuilder.mOriginalActions = mBuilder.mActions; 6496 mBuilder.mActions = new ArrayList<>(); 6497 RemoteViews remoteViews = makeBigContentView(); 6498 mBuilder.mActions = mBuilder.mOriginalActions; 6499 mBuilder.mOriginalActions = null; 6500 return remoteViews; 6501 } 6502 return super.makeContentView(increasedHeight); 6503 } 6504 6505 /** 6506 * @hide 6507 */ 6508 @Override 6509 public RemoteViews makeHeadsUpContentView(boolean increasedHeight) { 6510 if (increasedHeight && mBuilder.mActions.size() > 0) { 6511 return makeBigContentView(); 6512 } 6513 return super.makeHeadsUpContentView(increasedHeight); 6514 } 6515 6516 /** 6517 * @hide 6518 */ 6519 public RemoteViews makeBigContentView() { 6520 6521 // Nasty 6522 CharSequence text = mBuilder.getAllExtras().getCharSequence(EXTRA_TEXT); 6523 mBuilder.getAllExtras().putCharSequence(EXTRA_TEXT, null); 6524 6525 TemplateBindResult result = new TemplateBindResult(); 6526 RemoteViews contentView = getStandardView(mBuilder.getBigTextLayoutResource(), result); 6527 contentView.setInt(R.id.big_text, "setImageEndMargin", result.getIconMarginEnd()); 6528 6529 mBuilder.getAllExtras().putCharSequence(EXTRA_TEXT, text); 6530 6531 CharSequence bigTextText = mBuilder.processLegacyText(mBigText); 6532 if (TextUtils.isEmpty(bigTextText)) { 6533 // In case the bigtext is null / empty fall back to the normal text to avoid a weird 6534 // experience 6535 bigTextText = mBuilder.processLegacyText(text); 6536 } 6537 applyBigTextContentView(mBuilder, contentView, bigTextText); 6538 6539 return contentView; 6540 } 6541 6542 /** 6543 * @hide 6544 * Spans are ignored when comparing text for visual difference. 6545 */ 6546 @Override 6547 public boolean areNotificationsVisiblyDifferent(Style other) { 6548 if (other == null || getClass() != other.getClass()) { 6549 return true; 6550 } 6551 BigTextStyle newS = (BigTextStyle) other; 6552 return !Objects.equals(String.valueOf(getBigText()), String.valueOf(newS.getBigText())); 6553 } 6554 6555 static void applyBigTextContentView(Builder builder, 6556 RemoteViews contentView, CharSequence bigTextText) { 6557 contentView.setTextViewText(R.id.big_text, builder.processTextSpans(bigTextText)); 6558 builder.setTextViewColorSecondary(contentView, R.id.big_text); 6559 contentView.setViewVisibility(R.id.big_text, 6560 TextUtils.isEmpty(bigTextText) ? View.GONE : View.VISIBLE); 6561 contentView.setBoolean(R.id.big_text, "setHasImage", builder.mN.hasLargeIcon()); 6562 } 6563 } 6564 6565 /** 6566 * Helper class for generating large-format notifications that include multiple back-and-forth 6567 * messages of varying types between any number of people. 6568 * 6569 * <p> 6570 * If the platform does not provide large-format notifications, this method has no effect. The 6571 * user will always see the normal notification view. 6572 * 6573 * <p> 6574 * If the app is targeting Android P and above, it is required to use the {@link Person} 6575 * class in order to get an optimal rendering of the notification and its avatars. For 6576 * conversations involving multiple people, the app should also make sure that it marks the 6577 * conversation as a group with {@link #setGroupConversation(boolean)}. 6578 * 6579 * <p> 6580 * This class is a "rebuilder": It attaches to a Builder object and modifies its behavior. 6581 * Here's an example of how this may be used: 6582 * <pre class="prettyprint"> 6583 * 6584 * Person user = new Person.Builder().setIcon(userIcon).setName(userName).build(); 6585 * MessagingStyle style = new MessagingStyle(user) 6586 * .addMessage(messages[1].getText(), messages[1].getTime(), messages[1].getPerson()) 6587 * .addMessage(messages[2].getText(), messages[2].getTime(), messages[2].getPerson()) 6588 * .setGroupConversation(hasMultiplePeople()); 6589 * 6590 * Notification noti = new Notification.Builder() 6591 * .setContentTitle("2 new messages with " + sender.toString()) 6592 * .setContentText(subject) 6593 * .setSmallIcon(R.drawable.new_message) 6594 * .setLargeIcon(aBitmap) 6595 * .setStyle(style) 6596 * .build(); 6597 * </pre> 6598 */ 6599 public static class MessagingStyle extends Style { 6600 6601 /** 6602 * The maximum number of messages that will be retained in the Notification itself (the 6603 * number displayed is up to the platform). 6604 */ 6605 public static final int MAXIMUM_RETAINED_MESSAGES = 25; 6606 6607 @NonNull Person mUser; 6608 @Nullable CharSequence mConversationTitle; 6609 List<Message> mMessages = new ArrayList<>(); 6610 List<Message> mHistoricMessages = new ArrayList<>(); 6611 boolean mIsGroupConversation; 6612 6613 MessagingStyle() { 6614 } 6615 6616 /** 6617 * @param userDisplayName Required - the name to be displayed for any replies sent by the 6618 * user before the posting app reposts the notification with those messages after they've 6619 * been actually sent and in previous messages sent by the user added in 6620 * {@link #addMessage(Notification.MessagingStyle.Message)} 6621 * 6622 * @deprecated use {@code MessagingStyle(Person)} 6623 */ 6624 public MessagingStyle(@NonNull CharSequence userDisplayName) { 6625 this(new Person.Builder().setName(userDisplayName).build()); 6626 } 6627 6628 /** 6629 * @param user Required - The person displayed for any messages that are sent by the 6630 * user. Any messages added with {@link #addMessage(Notification.MessagingStyle.Message)} 6631 * who don't have a Person associated with it will be displayed as if they were sent 6632 * by this user. The user also needs to have a valid name associated with it, which will 6633 * be enforced starting in Android P. 6634 */ 6635 public MessagingStyle(@NonNull Person user) { 6636 mUser = user; 6637 } 6638 6639 /** 6640 * Validate that this style was properly composed. This is called at build time. 6641 * @hide 6642 */ 6643 @Override 6644 public void validate(Context context) { 6645 super.validate(context); 6646 if (context.getApplicationInfo().targetSdkVersion 6647 >= Build.VERSION_CODES.P && (mUser == null || mUser.getName() == null)) { 6648 throw new RuntimeException("User must be valid and have a name."); 6649 } 6650 } 6651 6652 /** 6653 * @return the the text that should be displayed in the statusBar when heads upped. 6654 * If {@code null} is returned, the default implementation will be used. 6655 * 6656 * @hide 6657 */ 6658 @Override 6659 public CharSequence getHeadsUpStatusBarText() { 6660 CharSequence conversationTitle = !TextUtils.isEmpty(super.mBigContentTitle) 6661 ? super.mBigContentTitle 6662 : mConversationTitle; 6663 if (!TextUtils.isEmpty(conversationTitle) && !hasOnlyWhiteSpaceSenders()) { 6664 return conversationTitle; 6665 } 6666 return null; 6667 } 6668 6669 /** 6670 * @return the user to be displayed for any replies sent by the user 6671 */ 6672 @NonNull 6673 public Person getUser() { 6674 return mUser; 6675 } 6676 6677 /** 6678 * Returns the name to be displayed for any replies sent by the user 6679 * 6680 * @deprecated use {@link #getUser()} instead 6681 */ 6682 public CharSequence getUserDisplayName() { 6683 return mUser.getName(); 6684 } 6685 6686 /** 6687 * Sets the title to be displayed on this conversation. May be set to {@code null}. 6688 * 6689 * <p>This API's behavior was changed in SDK version {@link Build.VERSION_CODES#P}. If your 6690 * application's target version is less than {@link Build.VERSION_CODES#P}, setting a 6691 * conversation title to a non-null value will make {@link #isGroupConversation()} return 6692 * {@code true} and passing {@code null} will make it return {@code false}. In 6693 * {@link Build.VERSION_CODES#P} and beyond, use {@link #setGroupConversation(boolean)} 6694 * to set group conversation status. 6695 * 6696 * @param conversationTitle Title displayed for this conversation 6697 * @return this object for method chaining 6698 */ 6699 public MessagingStyle setConversationTitle(@Nullable CharSequence conversationTitle) { 6700 mConversationTitle = conversationTitle; 6701 return this; 6702 } 6703 6704 /** 6705 * Return the title to be displayed on this conversation. May return {@code null}. 6706 */ 6707 @Nullable 6708 public CharSequence getConversationTitle() { 6709 return mConversationTitle; 6710 } 6711 6712 /** 6713 * Adds a message for display by this notification. Convenience call for a simple 6714 * {@link Message} in {@link #addMessage(Notification.MessagingStyle.Message)}. 6715 * @param text A {@link CharSequence} to be displayed as the message content 6716 * @param timestamp Time at which the message arrived 6717 * @param sender A {@link CharSequence} to be used for displaying the name of the 6718 * sender. Should be <code>null</code> for messages by the current user, in which case 6719 * the platform will insert {@link #getUserDisplayName()}. 6720 * Should be unique amongst all individuals in the conversation, and should be 6721 * consistent during re-posts of the notification. 6722 * 6723 * @see Message#Message(CharSequence, long, CharSequence) 6724 * 6725 * @return this object for method chaining 6726 * 6727 * @deprecated use {@link #addMessage(CharSequence, long, Person)} 6728 */ 6729 public MessagingStyle addMessage(CharSequence text, long timestamp, CharSequence sender) { 6730 return addMessage(text, timestamp, 6731 sender == null ? null : new Person.Builder().setName(sender).build()); 6732 } 6733 6734 /** 6735 * Adds a message for display by this notification. Convenience call for a simple 6736 * {@link Message} in {@link #addMessage(Notification.MessagingStyle.Message)}. 6737 * @param text A {@link CharSequence} to be displayed as the message content 6738 * @param timestamp Time at which the message arrived 6739 * @param sender The {@link Person} who sent the message. 6740 * Should be <code>null</code> for messages by the current user, in which case 6741 * the platform will insert the user set in {@code MessagingStyle(Person)}. 6742 * 6743 * @see Message#Message(CharSequence, long, CharSequence) 6744 * 6745 * @return this object for method chaining 6746 */ 6747 public MessagingStyle addMessage(@NonNull CharSequence text, long timestamp, 6748 @Nullable Person sender) { 6749 return addMessage(new Message(text, timestamp, sender)); 6750 } 6751 6752 /** 6753 * Adds a {@link Message} for display in this notification. 6754 * 6755 * <p>The messages should be added in chronologic order, i.e. the oldest first, 6756 * the newest last. 6757 * 6758 * @param message The {@link Message} to be displayed 6759 * @return this object for method chaining 6760 */ 6761 public MessagingStyle addMessage(Message message) { 6762 mMessages.add(message); 6763 if (mMessages.size() > MAXIMUM_RETAINED_MESSAGES) { 6764 mMessages.remove(0); 6765 } 6766 return this; 6767 } 6768 6769 /** 6770 * Adds a {@link Message} for historic context in this notification. 6771 * 6772 * <p>Messages should be added as historic if they are not the main subject of the 6773 * notification but may give context to a conversation. The system may choose to present 6774 * them only when relevant, e.g. when replying to a message through a {@link RemoteInput}. 6775 * 6776 * <p>The messages should be added in chronologic order, i.e. the oldest first, 6777 * the newest last. 6778 * 6779 * @param message The historic {@link Message} to be added 6780 * @return this object for method chaining 6781 */ 6782 public MessagingStyle addHistoricMessage(Message message) { 6783 mHistoricMessages.add(message); 6784 if (mHistoricMessages.size() > MAXIMUM_RETAINED_MESSAGES) { 6785 mHistoricMessages.remove(0); 6786 } 6787 return this; 6788 } 6789 6790 /** 6791 * Gets the list of {@code Message} objects that represent the notification 6792 */ 6793 public List<Message> getMessages() { 6794 return mMessages; 6795 } 6796 6797 /** 6798 * Gets the list of historic {@code Message}s in the notification. 6799 */ 6800 public List<Message> getHistoricMessages() { 6801 return mHistoricMessages; 6802 } 6803 6804 /** 6805 * Sets whether this conversation notification represents a group. If the app is targeting 6806 * Android P, this is required if the app wants to display the largeIcon set with 6807 * {@link Notification.Builder#setLargeIcon(Bitmap)}, otherwise it will be hidden. 6808 * 6809 * @param isGroupConversation {@code true} if the conversation represents a group, 6810 * {@code false} otherwise. 6811 * @return this object for method chaining 6812 */ 6813 public MessagingStyle setGroupConversation(boolean isGroupConversation) { 6814 mIsGroupConversation = isGroupConversation; 6815 return this; 6816 } 6817 6818 /** 6819 * Returns {@code true} if this notification represents a group conversation, otherwise 6820 * {@code false}. 6821 * 6822 * <p> If the application that generated this {@link MessagingStyle} targets an SDK version 6823 * less than {@link Build.VERSION_CODES#P}, this method becomes dependent on whether or 6824 * not the conversation title is set; returning {@code true} if the conversation title is 6825 * a non-null value, or {@code false} otherwise. From {@link Build.VERSION_CODES#P} forward, 6826 * this method returns what's set by {@link #setGroupConversation(boolean)} allowing for 6827 * named, non-group conversations. 6828 * 6829 * @see #setConversationTitle(CharSequence) 6830 */ 6831 public boolean isGroupConversation() { 6832 // When target SDK version is < P, a non-null conversation title dictates if this is 6833 // as group conversation. 6834 if (mBuilder != null 6835 && mBuilder.mContext.getApplicationInfo().targetSdkVersion 6836 < Build.VERSION_CODES.P) { 6837 return mConversationTitle != null; 6838 } 6839 6840 return mIsGroupConversation; 6841 } 6842 6843 /** 6844 * @hide 6845 */ 6846 @Override 6847 public void addExtras(Bundle extras) { 6848 super.addExtras(extras); 6849 if (mUser != null) { 6850 // For legacy usages 6851 extras.putCharSequence(EXTRA_SELF_DISPLAY_NAME, mUser.getName()); 6852 extras.putParcelable(EXTRA_MESSAGING_PERSON, mUser); 6853 } 6854 if (mConversationTitle != null) { 6855 extras.putCharSequence(EXTRA_CONVERSATION_TITLE, mConversationTitle); 6856 } 6857 if (!mMessages.isEmpty()) { extras.putParcelableArray(EXTRA_MESSAGES, 6858 Message.getBundleArrayForMessages(mMessages)); 6859 } 6860 if (!mHistoricMessages.isEmpty()) { extras.putParcelableArray(EXTRA_HISTORIC_MESSAGES, 6861 Message.getBundleArrayForMessages(mHistoricMessages)); 6862 } 6863 6864 fixTitleAndTextExtras(extras); 6865 extras.putBoolean(EXTRA_IS_GROUP_CONVERSATION, mIsGroupConversation); 6866 } 6867 6868 private void fixTitleAndTextExtras(Bundle extras) { 6869 Message m = findLatestIncomingMessage(); 6870 CharSequence text = (m == null) ? null : m.mText; 6871 CharSequence sender = m == null ? null 6872 : m.mSender == null || TextUtils.isEmpty(m.mSender.getName()) 6873 ? mUser.getName() : m.mSender.getName(); 6874 CharSequence title; 6875 if (!TextUtils.isEmpty(mConversationTitle)) { 6876 if (!TextUtils.isEmpty(sender)) { 6877 BidiFormatter bidi = BidiFormatter.getInstance(); 6878 title = mBuilder.mContext.getString( 6879 com.android.internal.R.string.notification_messaging_title_template, 6880 bidi.unicodeWrap(mConversationTitle), bidi.unicodeWrap(sender)); 6881 } else { 6882 title = mConversationTitle; 6883 } 6884 } else { 6885 title = sender; 6886 } 6887 6888 if (title != null) { 6889 extras.putCharSequence(EXTRA_TITLE, title); 6890 } 6891 if (text != null) { 6892 extras.putCharSequence(EXTRA_TEXT, text); 6893 } 6894 } 6895 6896 /** 6897 * @hide 6898 */ 6899 @Override 6900 protected void restoreFromExtras(Bundle extras) { 6901 super.restoreFromExtras(extras); 6902 6903 mUser = extras.getParcelable(EXTRA_MESSAGING_PERSON); 6904 if (mUser == null) { 6905 CharSequence displayName = extras.getCharSequence(EXTRA_SELF_DISPLAY_NAME); 6906 mUser = new Person.Builder().setName(displayName).build(); 6907 } 6908 mConversationTitle = extras.getCharSequence(EXTRA_CONVERSATION_TITLE); 6909 Parcelable[] messages = extras.getParcelableArray(EXTRA_MESSAGES); 6910 mMessages = Message.getMessagesFromBundleArray(messages); 6911 Parcelable[] histMessages = extras.getParcelableArray(EXTRA_HISTORIC_MESSAGES); 6912 mHistoricMessages = Message.getMessagesFromBundleArray(histMessages); 6913 mIsGroupConversation = extras.getBoolean(EXTRA_IS_GROUP_CONVERSATION); 6914 } 6915 6916 /** 6917 * @hide 6918 */ 6919 @Override 6920 public RemoteViews makeContentView(boolean increasedHeight) { 6921 mBuilder.mOriginalActions = mBuilder.mActions; 6922 mBuilder.mActions = new ArrayList<>(); 6923 RemoteViews remoteViews = makeMessagingView(true /* displayImagesAtEnd */, 6924 false /* hideLargeIcon */); 6925 mBuilder.mActions = mBuilder.mOriginalActions; 6926 mBuilder.mOriginalActions = null; 6927 return remoteViews; 6928 } 6929 6930 /** 6931 * @hide 6932 * Spans are ignored when comparing text for visual difference. 6933 */ 6934 @Override 6935 public boolean areNotificationsVisiblyDifferent(Style other) { 6936 if (other == null || getClass() != other.getClass()) { 6937 return true; 6938 } 6939 MessagingStyle newS = (MessagingStyle) other; 6940 List<MessagingStyle.Message> oldMs = getMessages(); 6941 List<MessagingStyle.Message> newMs = newS.getMessages(); 6942 6943 if (oldMs == null || newMs == null) { 6944 newMs = new ArrayList<>(); 6945 } 6946 6947 int n = oldMs.size(); 6948 if (n != newMs.size()) { 6949 return true; 6950 } 6951 for (int i = 0; i < n; i++) { 6952 MessagingStyle.Message oldM = oldMs.get(i); 6953 MessagingStyle.Message newM = newMs.get(i); 6954 if (!Objects.equals( 6955 String.valueOf(oldM.getText()), 6956 String.valueOf(newM.getText()))) { 6957 return true; 6958 } 6959 if (!Objects.equals(oldM.getDataUri(), newM.getDataUri())) { 6960 return true; 6961 } 6962 String oldSender = String.valueOf(oldM.getSenderPerson() == null 6963 ? oldM.getSender() 6964 : oldM.getSenderPerson().getName()); 6965 String newSender = String.valueOf(newM.getSenderPerson() == null 6966 ? newM.getSender() 6967 : newM.getSenderPerson().getName()); 6968 if (!Objects.equals(oldSender, newSender)) { 6969 return true; 6970 } 6971 6972 String oldKey = oldM.getSenderPerson() == null 6973 ? null : oldM.getSenderPerson().getKey(); 6974 String newKey = newM.getSenderPerson() == null 6975 ? null : newM.getSenderPerson().getKey(); 6976 if (!Objects.equals(oldKey, newKey)) { 6977 return true; 6978 } 6979 // Other fields (like timestamp) intentionally excluded 6980 } 6981 return false; 6982 } 6983 6984 private Message findLatestIncomingMessage() { 6985 return findLatestIncomingMessage(mMessages); 6986 } 6987 6988 /** 6989 * @hide 6990 */ 6991 @Nullable 6992 public static Message findLatestIncomingMessage( 6993 List<Message> messages) { 6994 for (int i = messages.size() - 1; i >= 0; i--) { 6995 Message m = messages.get(i); 6996 // Incoming messages have a non-empty sender. 6997 if (m.mSender != null && !TextUtils.isEmpty(m.mSender.getName())) { 6998 return m; 6999 } 7000 } 7001 if (!messages.isEmpty()) { 7002 // No incoming messages, fall back to outgoing message 7003 return messages.get(messages.size() - 1); 7004 } 7005 return null; 7006 } 7007 7008 /** 7009 * @hide 7010 */ 7011 @Override 7012 public RemoteViews makeBigContentView() { 7013 return makeMessagingView(false /* displayImagesAtEnd */, true /* hideLargeIcon */); 7014 } 7015 7016 /** 7017 * Create a messaging layout. 7018 * 7019 * @param displayImagesAtEnd should images be displayed at the end of the content instead 7020 * of inline. 7021 * @param hideRightIcons Should the reply affordance be shown at the end of the notification 7022 * @return the created remoteView. 7023 */ 7024 @NonNull 7025 private RemoteViews makeMessagingView(boolean displayImagesAtEnd, boolean hideRightIcons) { 7026 CharSequence conversationTitle = !TextUtils.isEmpty(super.mBigContentTitle) 7027 ? super.mBigContentTitle 7028 : mConversationTitle; 7029 boolean atLeastP = mBuilder.mContext.getApplicationInfo().targetSdkVersion 7030 >= Build.VERSION_CODES.P; 7031 boolean isOneToOne; 7032 CharSequence nameReplacement = null; 7033 Icon avatarReplacement = null; 7034 if (!atLeastP) { 7035 isOneToOne = TextUtils.isEmpty(conversationTitle); 7036 avatarReplacement = mBuilder.mN.mLargeIcon; 7037 if (hasOnlyWhiteSpaceSenders()) { 7038 isOneToOne = true; 7039 nameReplacement = conversationTitle; 7040 conversationTitle = null; 7041 } 7042 } else { 7043 isOneToOne = !isGroupConversation(); 7044 } 7045 TemplateBindResult bindResult = new TemplateBindResult(); 7046 RemoteViews contentView = mBuilder.applyStandardTemplateWithActions( 7047 mBuilder.getMessagingLayoutResource(), 7048 mBuilder.mParams.reset().hasProgress(false).title(conversationTitle).text(null) 7049 .hideLargeIcon(hideRightIcons || isOneToOne) 7050 .hideReplyIcon(hideRightIcons) 7051 .headerTextSecondary(conversationTitle), 7052 bindResult); 7053 addExtras(mBuilder.mN.extras); 7054 // also update the end margin if there is an image 7055 contentView.setViewLayoutMarginEnd(R.id.notification_messaging, 7056 bindResult.getIconMarginEnd()); 7057 contentView.setInt(R.id.status_bar_latest_event_content, "setLayoutColor", 7058 mBuilder.isColorized() ? mBuilder.getPrimaryTextColor() 7059 : mBuilder.resolveContrastColor()); 7060 contentView.setInt(R.id.status_bar_latest_event_content, "setSenderTextColor", 7061 mBuilder.getPrimaryTextColor()); 7062 contentView.setInt(R.id.status_bar_latest_event_content, "setMessageTextColor", 7063 mBuilder.getSecondaryTextColor()); 7064 contentView.setBoolean(R.id.status_bar_latest_event_content, "setDisplayImagesAtEnd", 7065 displayImagesAtEnd); 7066 contentView.setIcon(R.id.status_bar_latest_event_content, "setAvatarReplacement", 7067 avatarReplacement); 7068 contentView.setCharSequence(R.id.status_bar_latest_event_content, "setNameReplacement", 7069 nameReplacement); 7070 contentView.setBoolean(R.id.status_bar_latest_event_content, "setIsOneToOne", 7071 isOneToOne); 7072 contentView.setBundle(R.id.status_bar_latest_event_content, "setData", 7073 mBuilder.mN.extras); 7074 return contentView; 7075 } 7076 7077 private boolean hasOnlyWhiteSpaceSenders() { 7078 for (int i = 0; i < mMessages.size(); i++) { 7079 Message m = mMessages.get(i); 7080 Person sender = m.getSenderPerson(); 7081 if (sender != null && !isWhiteSpace(sender.getName())) { 7082 return false; 7083 } 7084 } 7085 return true; 7086 } 7087 7088 private boolean isWhiteSpace(CharSequence sender) { 7089 if (TextUtils.isEmpty(sender)) { 7090 return true; 7091 } 7092 if (sender.toString().matches("^\\s*$")) { 7093 return true; 7094 } 7095 // Let's check if we only have 0 whitespace chars. Some apps did this as a workaround 7096 // For the presentation that we had. 7097 for (int i = 0; i < sender.length(); i++) { 7098 char c = sender.charAt(i); 7099 if (c != '\u200B') { 7100 return false; 7101 } 7102 } 7103 return true; 7104 } 7105 7106 private CharSequence createConversationTitleFromMessages() { 7107 ArraySet<CharSequence> names = new ArraySet<>(); 7108 for (int i = 0; i < mMessages.size(); i++) { 7109 Message m = mMessages.get(i); 7110 Person sender = m.getSenderPerson(); 7111 if (sender != null) { 7112 names.add(sender.getName()); 7113 } 7114 } 7115 SpannableStringBuilder title = new SpannableStringBuilder(); 7116 int size = names.size(); 7117 for (int i = 0; i < size; i++) { 7118 CharSequence name = names.valueAt(i); 7119 if (!TextUtils.isEmpty(title)) { 7120 title.append(", "); 7121 } 7122 title.append(BidiFormatter.getInstance().unicodeWrap(name)); 7123 } 7124 return title; 7125 } 7126 7127 /** 7128 * @hide 7129 */ 7130 @Override 7131 public RemoteViews makeHeadsUpContentView(boolean increasedHeight) { 7132 RemoteViews remoteViews = makeMessagingView(true /* displayImagesAtEnd */, 7133 true /* hideLargeIcon */); 7134 remoteViews.setInt(R.id.notification_messaging, "setMaxDisplayedLines", 1); 7135 return remoteViews; 7136 } 7137 7138 private static TextAppearanceSpan makeFontColorSpan(int color) { 7139 return new TextAppearanceSpan(null, 0, 0, 7140 ColorStateList.valueOf(color), null); 7141 } 7142 7143 public static final class Message { 7144 7145 static final String KEY_TEXT = "text"; 7146 static final String KEY_TIMESTAMP = "time"; 7147 static final String KEY_SENDER = "sender"; 7148 static final String KEY_SENDER_PERSON = "sender_person"; 7149 static final String KEY_DATA_MIME_TYPE = "type"; 7150 static final String KEY_DATA_URI= "uri"; 7151 static final String KEY_EXTRAS_BUNDLE = "extras"; 7152 static final String KEY_REMOTE_INPUT_HISTORY = "remote_input_history"; 7153 7154 private final CharSequence mText; 7155 private final long mTimestamp; 7156 @Nullable 7157 private final Person mSender; 7158 /** True if this message was generated from the extra 7159 * {@link Notification#EXTRA_REMOTE_INPUT_HISTORY} 7160 */ 7161 private final boolean mRemoteInputHistory; 7162 7163 private Bundle mExtras = new Bundle(); 7164 private String mDataMimeType; 7165 private Uri mDataUri; 7166 7167 /** 7168 * Constructor 7169 * @param text A {@link CharSequence} to be displayed as the message content 7170 * @param timestamp Time at which the message arrived 7171 * @param sender A {@link CharSequence} to be used for displaying the name of the 7172 * sender. Should be <code>null</code> for messages by the current user, in which case 7173 * the platform will insert {@link MessagingStyle#getUserDisplayName()}. 7174 * Should be unique amongst all individuals in the conversation, and should be 7175 * consistent during re-posts of the notification. 7176 * 7177 * @deprecated use {@code Message(CharSequence, long, Person)} 7178 */ 7179 public Message(CharSequence text, long timestamp, CharSequence sender){ 7180 this(text, timestamp, sender == null ? null 7181 : new Person.Builder().setName(sender).build()); 7182 } 7183 7184 /** 7185 * Constructor 7186 * @param text A {@link CharSequence} to be displayed as the message content 7187 * @param timestamp Time at which the message arrived 7188 * @param sender The {@link Person} who sent the message. 7189 * Should be <code>null</code> for messages by the current user, in which case 7190 * the platform will insert the user set in {@code MessagingStyle(Person)}. 7191 * <p> 7192 * The person provided should contain an Icon, set with 7193 * {@link Person.Builder#setIcon(Icon)} and also have a name provided 7194 * with {@link Person.Builder#setName(CharSequence)}. If multiple users have the same 7195 * name, consider providing a key with {@link Person.Builder#setKey(String)} in order 7196 * to differentiate between the different users. 7197 * </p> 7198 */ 7199 public Message(@NonNull CharSequence text, long timestamp, @Nullable Person sender) { 7200 this(text, timestamp, sender, false /* remoteHistory */); 7201 } 7202 7203 /** 7204 * Constructor 7205 * @param text A {@link CharSequence} to be displayed as the message content 7206 * @param timestamp Time at which the message arrived 7207 * @param sender The {@link Person} who sent the message. 7208 * Should be <code>null</code> for messages by the current user, in which case 7209 * the platform will insert the user set in {@code MessagingStyle(Person)}. 7210 * @param remoteInputHistory True if the messages was generated from the extra 7211 * {@link Notification#EXTRA_REMOTE_INPUT_HISTORY}. 7212 * <p> 7213 * The person provided should contain an Icon, set with 7214 * {@link Person.Builder#setIcon(Icon)} and also have a name provided 7215 * with {@link Person.Builder#setName(CharSequence)}. If multiple users have the same 7216 * name, consider providing a key with {@link Person.Builder#setKey(String)} in order 7217 * to differentiate between the different users. 7218 * </p> 7219 * @hide 7220 */ 7221 public Message(@NonNull CharSequence text, long timestamp, @Nullable Person sender, 7222 boolean remoteInputHistory) { 7223 mText = text; 7224 mTimestamp = timestamp; 7225 mSender = sender; 7226 mRemoteInputHistory = remoteInputHistory; 7227 } 7228 7229 /** 7230 * Sets a binary blob of data and an associated MIME type for a message. In the case 7231 * where the platform doesn't support the MIME type, the original text provided in the 7232 * constructor will be used. 7233 * @param dataMimeType The MIME type of the content. See 7234 * <a href="{@docRoot}notifications/messaging.html"> for the list of supported MIME 7235 * types on Android and Android Wear. 7236 * @param dataUri The uri containing the content whose type is given by the MIME type. 7237 * <p class="note"> 7238 * <ol> 7239 * <li>Notification Listeners including the System UI need permission to access the 7240 * data the Uri points to. The recommended ways to do this are:</li> 7241 * <li>Store the data in your own ContentProvider, making sure that other apps have 7242 * the correct permission to access your provider. The preferred mechanism for 7243 * providing access is to use per-URI permissions which are temporary and only 7244 * grant access to the receiving application. An easy way to create a 7245 * ContentProvider like this is to use the FileProvider helper class.</li> 7246 * <li>Use the system MediaStore. The MediaStore is primarily aimed at video, audio 7247 * and image MIME types, however beginning with Android 3.0 (API level 11) it can 7248 * also store non-media types (see MediaStore.Files for more info). Files can be 7249 * inserted into the MediaStore using scanFile() after which a content:// style 7250 * Uri suitable for sharing is passed to the provided onScanCompleted() callback. 7251 * Note that once added to the system MediaStore the content is accessible to any 7252 * app on the device.</li> 7253 * </ol> 7254 * @return this object for method chaining 7255 */ 7256 public Message setData(String dataMimeType, Uri dataUri) { 7257 mDataMimeType = dataMimeType; 7258 mDataUri = dataUri; 7259 return this; 7260 } 7261 7262 /** 7263 * Get the text to be used for this message, or the fallback text if a type and content 7264 * Uri have been set 7265 */ 7266 public CharSequence getText() { 7267 return mText; 7268 } 7269 7270 /** 7271 * Get the time at which this message arrived 7272 */ 7273 public long getTimestamp() { 7274 return mTimestamp; 7275 } 7276 7277 /** 7278 * Get the extras Bundle for this message. 7279 */ 7280 public Bundle getExtras() { 7281 return mExtras; 7282 } 7283 7284 /** 7285 * Get the text used to display the contact's name in the messaging experience 7286 * 7287 * @deprecated use {@link #getSenderPerson()} 7288 */ 7289 public CharSequence getSender() { 7290 return mSender == null ? null : mSender.getName(); 7291 } 7292 7293 /** 7294 * Get the sender associated with this message. 7295 */ 7296 @Nullable 7297 public Person getSenderPerson() { 7298 return mSender; 7299 } 7300 7301 /** 7302 * Get the MIME type of the data pointed to by the Uri 7303 */ 7304 public String getDataMimeType() { 7305 return mDataMimeType; 7306 } 7307 7308 /** 7309 * Get the the Uri pointing to the content of the message. Can be null, in which case 7310 * {@see #getText()} is used. 7311 */ 7312 public Uri getDataUri() { 7313 return mDataUri; 7314 } 7315 7316 /** 7317 * @return True if the message was generated from 7318 * {@link Notification#EXTRA_REMOTE_INPUT_HISTORY}. 7319 * @hide 7320 */ 7321 public boolean isRemoteInputHistory() { 7322 return mRemoteInputHistory; 7323 } 7324 7325 private Bundle toBundle() { 7326 Bundle bundle = new Bundle(); 7327 if (mText != null) { 7328 bundle.putCharSequence(KEY_TEXT, mText); 7329 } 7330 bundle.putLong(KEY_TIMESTAMP, mTimestamp); 7331 if (mSender != null) { 7332 // Legacy listeners need this 7333 bundle.putCharSequence(KEY_SENDER, mSender.getName()); 7334 bundle.putParcelable(KEY_SENDER_PERSON, mSender); 7335 } 7336 if (mDataMimeType != null) { 7337 bundle.putString(KEY_DATA_MIME_TYPE, mDataMimeType); 7338 } 7339 if (mDataUri != null) { 7340 bundle.putParcelable(KEY_DATA_URI, mDataUri); 7341 } 7342 if (mExtras != null) { 7343 bundle.putBundle(KEY_EXTRAS_BUNDLE, mExtras); 7344 } 7345 if (mRemoteInputHistory) { 7346 bundle.putBoolean(KEY_REMOTE_INPUT_HISTORY, mRemoteInputHistory); 7347 } 7348 return bundle; 7349 } 7350 7351 static Bundle[] getBundleArrayForMessages(List<Message> messages) { 7352 Bundle[] bundles = new Bundle[messages.size()]; 7353 final int N = messages.size(); 7354 for (int i = 0; i < N; i++) { 7355 bundles[i] = messages.get(i).toBundle(); 7356 } 7357 return bundles; 7358 } 7359 7360 /** 7361 * @return A list of messages read from the bundles. 7362 * 7363 * @hide 7364 */ 7365 public static List<Message> getMessagesFromBundleArray(Parcelable[] bundles) { 7366 if (bundles == null) { 7367 return new ArrayList<>(); 7368 } 7369 List<Message> messages = new ArrayList<>(bundles.length); 7370 for (int i = 0; i < bundles.length; i++) { 7371 if (bundles[i] instanceof Bundle) { 7372 Message message = getMessageFromBundle((Bundle)bundles[i]); 7373 if (message != null) { 7374 messages.add(message); 7375 } 7376 } 7377 } 7378 return messages; 7379 } 7380 7381 static Message getMessageFromBundle(Bundle bundle) { 7382 try { 7383 if (!bundle.containsKey(KEY_TEXT) || !bundle.containsKey(KEY_TIMESTAMP)) { 7384 return null; 7385 } else { 7386 7387 Person senderPerson = bundle.getParcelable(KEY_SENDER_PERSON); 7388 if (senderPerson == null) { 7389 // Legacy apps that use compat don't actually provide the sender objects 7390 // We need to fix the compat version to provide people / use 7391 // the native api instead 7392 CharSequence senderName = bundle.getCharSequence(KEY_SENDER); 7393 if (senderName != null) { 7394 senderPerson = new Person.Builder().setName(senderName).build(); 7395 } 7396 } 7397 Message message = new Message(bundle.getCharSequence(KEY_TEXT), 7398 bundle.getLong(KEY_TIMESTAMP), 7399 senderPerson, 7400 bundle.getBoolean(KEY_REMOTE_INPUT_HISTORY, false)); 7401 if (bundle.containsKey(KEY_DATA_MIME_TYPE) && 7402 bundle.containsKey(KEY_DATA_URI)) { 7403 message.setData(bundle.getString(KEY_DATA_MIME_TYPE), 7404 (Uri) bundle.getParcelable(KEY_DATA_URI)); 7405 } 7406 if (bundle.containsKey(KEY_EXTRAS_BUNDLE)) { 7407 message.getExtras().putAll(bundle.getBundle(KEY_EXTRAS_BUNDLE)); 7408 } 7409 return message; 7410 } 7411 } catch (ClassCastException e) { 7412 return null; 7413 } 7414 } 7415 } 7416 } 7417 7418 /** 7419 * Helper class for generating large-format notifications that include a list of (up to 5) strings. 7420 * 7421 * Here's how you'd set the <code>InboxStyle</code> on a notification: 7422 * <pre class="prettyprint"> 7423 * Notification notif = new Notification.Builder(mContext) 7424 * .setContentTitle("5 New mails from " + sender.toString()) 7425 * .setContentText(subject) 7426 * .setSmallIcon(R.drawable.new_mail) 7427 * .setLargeIcon(aBitmap) 7428 * .setStyle(new Notification.InboxStyle() 7429 * .addLine(str1) 7430 * .addLine(str2) 7431 * .setContentTitle("") 7432 * .setSummaryText("+3 more")) 7433 * .build(); 7434 * </pre> 7435 * 7436 * @see Notification#bigContentView 7437 */ 7438 public static class InboxStyle extends Style { 7439 private ArrayList<CharSequence> mTexts = new ArrayList<CharSequence>(5); 7440 7441 public InboxStyle() { 7442 } 7443 7444 /** 7445 * @deprecated use {@code InboxStyle()}. 7446 */ 7447 @Deprecated 7448 public InboxStyle(Builder builder) { 7449 setBuilder(builder); 7450 } 7451 7452 /** 7453 * Overrides ContentTitle in the big form of the template. 7454 * This defaults to the value passed to setContentTitle(). 7455 */ 7456 public InboxStyle setBigContentTitle(CharSequence title) { 7457 internalSetBigContentTitle(safeCharSequence(title)); 7458 return this; 7459 } 7460 7461 /** 7462 * Set the first line of text after the detail section in the big form of the template. 7463 */ 7464 public InboxStyle setSummaryText(CharSequence cs) { 7465 internalSetSummaryText(safeCharSequence(cs)); 7466 return this; 7467 } 7468 7469 /** 7470 * Append a line to the digest section of the Inbox notification. 7471 */ 7472 public InboxStyle addLine(CharSequence cs) { 7473 mTexts.add(safeCharSequence(cs)); 7474 return this; 7475 } 7476 7477 /** 7478 * @hide 7479 */ 7480 public ArrayList<CharSequence> getLines() { 7481 return mTexts; 7482 } 7483 7484 /** 7485 * @hide 7486 */ 7487 public void addExtras(Bundle extras) { 7488 super.addExtras(extras); 7489 7490 CharSequence[] a = new CharSequence[mTexts.size()]; 7491 extras.putCharSequenceArray(EXTRA_TEXT_LINES, mTexts.toArray(a)); 7492 } 7493 7494 /** 7495 * @hide 7496 */ 7497 @Override 7498 protected void restoreFromExtras(Bundle extras) { 7499 super.restoreFromExtras(extras); 7500 7501 mTexts.clear(); 7502 if (extras.containsKey(EXTRA_TEXT_LINES)) { 7503 Collections.addAll(mTexts, extras.getCharSequenceArray(EXTRA_TEXT_LINES)); 7504 } 7505 } 7506 7507 /** 7508 * @hide 7509 */ 7510 public RemoteViews makeBigContentView() { 7511 // Remove the content text so it disappears unless you have a summary 7512 // Nasty 7513 CharSequence oldBuilderContentText = mBuilder.mN.extras.getCharSequence(EXTRA_TEXT); 7514 mBuilder.getAllExtras().putCharSequence(EXTRA_TEXT, null); 7515 7516 TemplateBindResult result = new TemplateBindResult(); 7517 RemoteViews contentView = getStandardView(mBuilder.getInboxLayoutResource(), result); 7518 7519 mBuilder.getAllExtras().putCharSequence(EXTRA_TEXT, oldBuilderContentText); 7520 7521 int[] rowIds = {R.id.inbox_text0, R.id.inbox_text1, R.id.inbox_text2, R.id.inbox_text3, 7522 R.id.inbox_text4, R.id.inbox_text5, R.id.inbox_text6}; 7523 7524 // Make sure all rows are gone in case we reuse a view. 7525 for (int rowId : rowIds) { 7526 contentView.setViewVisibility(rowId, View.GONE); 7527 } 7528 7529 int i=0; 7530 int topPadding = mBuilder.mContext.getResources().getDimensionPixelSize( 7531 R.dimen.notification_inbox_item_top_padding); 7532 boolean first = true; 7533 int onlyViewId = 0; 7534 int maxRows = rowIds.length; 7535 if (mBuilder.mActions.size() > 0) { 7536 maxRows--; 7537 } 7538 while (i < mTexts.size() && i < maxRows) { 7539 CharSequence str = mTexts.get(i); 7540 if (!TextUtils.isEmpty(str)) { 7541 contentView.setViewVisibility(rowIds[i], View.VISIBLE); 7542 contentView.setTextViewText(rowIds[i], 7543 mBuilder.processTextSpans(mBuilder.processLegacyText(str))); 7544 mBuilder.setTextViewColorSecondary(contentView, rowIds[i]); 7545 contentView.setViewPadding(rowIds[i], 0, topPadding, 0, 0); 7546 handleInboxImageMargin(contentView, rowIds[i], first, 7547 result.getIconMarginEnd()); 7548 if (first) { 7549 onlyViewId = rowIds[i]; 7550 } else { 7551 onlyViewId = 0; 7552 } 7553 first = false; 7554 } 7555 i++; 7556 } 7557 if (onlyViewId != 0) { 7558 // We only have 1 entry, lets make it look like the normal Text of a Bigtext 7559 topPadding = mBuilder.mContext.getResources().getDimensionPixelSize( 7560 R.dimen.notification_text_margin_top); 7561 contentView.setViewPadding(onlyViewId, 0, topPadding, 0, 0); 7562 } 7563 7564 return contentView; 7565 } 7566 7567 /** 7568 * @hide 7569 */ 7570 @Override 7571 public boolean areNotificationsVisiblyDifferent(Style other) { 7572 if (other == null || getClass() != other.getClass()) { 7573 return true; 7574 } 7575 InboxStyle newS = (InboxStyle) other; 7576 7577 final ArrayList<CharSequence> myLines = getLines(); 7578 final ArrayList<CharSequence> newLines = newS.getLines(); 7579 final int n = myLines.size(); 7580 if (n != newLines.size()) { 7581 return true; 7582 } 7583 7584 for (int i = 0; i < n; i++) { 7585 if (!Objects.equals( 7586 String.valueOf(myLines.get(i)), 7587 String.valueOf(newLines.get(i)))) { 7588 return true; 7589 } 7590 } 7591 return false; 7592 } 7593 7594 private void handleInboxImageMargin(RemoteViews contentView, int id, boolean first, 7595 int marginEndValue) { 7596 int endMargin = 0; 7597 if (first) { 7598 final int max = mBuilder.mN.extras.getInt(EXTRA_PROGRESS_MAX, 0); 7599 final boolean ind = mBuilder.mN.extras.getBoolean(EXTRA_PROGRESS_INDETERMINATE); 7600 boolean hasProgress = max != 0 || ind; 7601 if (!hasProgress) { 7602 endMargin = marginEndValue; 7603 } 7604 } 7605 contentView.setViewLayoutMarginEnd(id, endMargin); 7606 } 7607 } 7608 7609 /** 7610 * Notification style for media playback notifications. 7611 * 7612 * In the expanded form, {@link Notification#bigContentView}, up to 5 7613 * {@link Notification.Action}s specified with 7614 * {@link Notification.Builder#addAction(Action) addAction} will be 7615 * shown as icon-only pushbuttons, suitable for transport controls. The Bitmap given to 7616 * {@link Notification.Builder#setLargeIcon(android.graphics.Bitmap) setLargeIcon()} will be 7617 * treated as album artwork. 7618 * <p> 7619 * Unlike the other styles provided here, MediaStyle can also modify the standard-size 7620 * {@link Notification#contentView}; by providing action indices to 7621 * {@link #setShowActionsInCompactView(int...)} you can promote up to 3 actions to be displayed 7622 * in the standard view alongside the usual content. 7623 * <p> 7624 * Notifications created with MediaStyle will have their category set to 7625 * {@link Notification#CATEGORY_TRANSPORT CATEGORY_TRANSPORT} unless you set a different 7626 * category using {@link Notification.Builder#setCategory(String) setCategory()}. 7627 * <p> 7628 * Finally, if you attach a {@link android.media.session.MediaSession.Token} using 7629 * {@link android.app.Notification.MediaStyle#setMediaSession(MediaSession.Token)}, 7630 * the System UI can identify this as a notification representing an active media session 7631 * and respond accordingly (by showing album artwork in the lockscreen, for example). 7632 * 7633 * <p> 7634 * Starting at {@link android.os.Build.VERSION_CODES#O Android O} any notification that has a 7635 * media session attached with {@link #setMediaSession(MediaSession.Token)} will be colorized. 7636 * You can opt-out of this behavior by using {@link Notification.Builder#setColorized(boolean)}. 7637 * <p> 7638 * 7639 * To use this style with your Notification, feed it to 7640 * {@link Notification.Builder#setStyle(android.app.Notification.Style)} like so: 7641 * <pre class="prettyprint"> 7642 * Notification noti = new Notification.Builder() 7643 * .setSmallIcon(R.drawable.ic_stat_player) 7644 * .setContentTitle("Track title") 7645 * .setContentText("Artist - Album") 7646 * .setLargeIcon(albumArtBitmap)) 7647 * .setStyle(<b>new Notification.MediaStyle()</b> 7648 * .setMediaSession(mySession)) 7649 * .build(); 7650 * </pre> 7651 * 7652 * @see Notification#bigContentView 7653 * @see Notification.Builder#setColorized(boolean) 7654 */ 7655 public static class MediaStyle extends Style { 7656 static final int MAX_MEDIA_BUTTONS_IN_COMPACT = 3; 7657 static final int MAX_MEDIA_BUTTONS = 5; 7658 7659 private int[] mActionsToShowInCompact = null; 7660 private MediaSession.Token mToken; 7661 7662 public MediaStyle() { 7663 } 7664 7665 /** 7666 * @deprecated use {@code MediaStyle()}. 7667 */ 7668 @Deprecated 7669 public MediaStyle(Builder builder) { 7670 setBuilder(builder); 7671 } 7672 7673 /** 7674 * Request up to 3 actions (by index in the order of addition) to be shown in the compact 7675 * notification view. 7676 * 7677 * @param actions the indices of the actions to show in the compact notification view 7678 */ 7679 public MediaStyle setShowActionsInCompactView(int...actions) { 7680 mActionsToShowInCompact = actions; 7681 return this; 7682 } 7683 7684 /** 7685 * Attach a {@link android.media.session.MediaSession.Token} to this Notification 7686 * to provide additional playback information and control to the SystemUI. 7687 */ 7688 public MediaStyle setMediaSession(MediaSession.Token token) { 7689 mToken = token; 7690 return this; 7691 } 7692 7693 /** 7694 * @hide 7695 */ 7696 @Override 7697 public Notification buildStyled(Notification wip) { 7698 super.buildStyled(wip); 7699 if (wip.category == null) { 7700 wip.category = Notification.CATEGORY_TRANSPORT; 7701 } 7702 return wip; 7703 } 7704 7705 /** 7706 * @hide 7707 */ 7708 @Override 7709 public RemoteViews makeContentView(boolean increasedHeight) { 7710 return makeMediaContentView(); 7711 } 7712 7713 /** 7714 * @hide 7715 */ 7716 @Override 7717 public RemoteViews makeBigContentView() { 7718 return makeMediaBigContentView(); 7719 } 7720 7721 /** 7722 * @hide 7723 */ 7724 @Override 7725 public RemoteViews makeHeadsUpContentView(boolean increasedHeight) { 7726 RemoteViews expanded = makeMediaBigContentView(); 7727 return expanded != null ? expanded : makeMediaContentView(); 7728 } 7729 7730 /** @hide */ 7731 @Override 7732 public void addExtras(Bundle extras) { 7733 super.addExtras(extras); 7734 7735 if (mToken != null) { 7736 extras.putParcelable(EXTRA_MEDIA_SESSION, mToken); 7737 } 7738 if (mActionsToShowInCompact != null) { 7739 extras.putIntArray(EXTRA_COMPACT_ACTIONS, mActionsToShowInCompact); 7740 } 7741 } 7742 7743 /** 7744 * @hide 7745 */ 7746 @Override 7747 protected void restoreFromExtras(Bundle extras) { 7748 super.restoreFromExtras(extras); 7749 7750 if (extras.containsKey(EXTRA_MEDIA_SESSION)) { 7751 mToken = extras.getParcelable(EXTRA_MEDIA_SESSION); 7752 } 7753 if (extras.containsKey(EXTRA_COMPACT_ACTIONS)) { 7754 mActionsToShowInCompact = extras.getIntArray(EXTRA_COMPACT_ACTIONS); 7755 } 7756 } 7757 7758 /** 7759 * @hide 7760 */ 7761 @Override 7762 public boolean areNotificationsVisiblyDifferent(Style other) { 7763 if (other == null || getClass() != other.getClass()) { 7764 return true; 7765 } 7766 // All fields to compare are on the Notification object 7767 return false; 7768 } 7769 7770 private RemoteViews generateMediaActionButton(Action action, int color) { 7771 final boolean tombstone = (action.actionIntent == null); 7772 RemoteViews button = new BuilderRemoteViews(mBuilder.mContext.getApplicationInfo(), 7773 R.layout.notification_material_media_action); 7774 button.setImageViewIcon(R.id.action0, action.getIcon()); 7775 7776 // If the action buttons should not be tinted, then just use the default 7777 // notification color. Otherwise, just use the passed-in color. 7778 int tintColor = mBuilder.shouldTintActionButtons() || mBuilder.isColorized() 7779 ? color 7780 : NotificationColorUtil.resolveColor(mBuilder.mContext, 7781 Notification.COLOR_DEFAULT); 7782 7783 button.setDrawableTint(R.id.action0, false, tintColor, 7784 PorterDuff.Mode.SRC_ATOP); 7785 if (!tombstone) { 7786 button.setOnClickPendingIntent(R.id.action0, action.actionIntent); 7787 } 7788 button.setContentDescription(R.id.action0, action.title); 7789 return button; 7790 } 7791 7792 private RemoteViews makeMediaContentView() { 7793 RemoteViews view = mBuilder.applyStandardTemplate( 7794 R.layout.notification_template_material_media, false, /* hasProgress */ 7795 null /* result */); 7796 7797 final int numActions = mBuilder.mActions.size(); 7798 final int N = mActionsToShowInCompact == null 7799 ? 0 7800 : Math.min(mActionsToShowInCompact.length, MAX_MEDIA_BUTTONS_IN_COMPACT); 7801 if (N > 0) { 7802 view.removeAllViews(com.android.internal.R.id.media_actions); 7803 for (int i = 0; i < N; i++) { 7804 if (i >= numActions) { 7805 throw new IllegalArgumentException(String.format( 7806 "setShowActionsInCompactView: action %d out of bounds (max %d)", 7807 i, numActions - 1)); 7808 } 7809 7810 final Action action = mBuilder.mActions.get(mActionsToShowInCompact[i]); 7811 final RemoteViews button = generateMediaActionButton(action, getActionColor()); 7812 view.addView(com.android.internal.R.id.media_actions, button); 7813 } 7814 } 7815 handleImage(view); 7816 // handle the content margin 7817 int endMargin = R.dimen.notification_content_margin_end; 7818 if (mBuilder.mN.hasLargeIcon()) { 7819 endMargin = R.dimen.notification_media_image_margin_end; 7820 } 7821 view.setViewLayoutMarginEndDimen(R.id.notification_main_column, endMargin); 7822 return view; 7823 } 7824 7825 private int getActionColor() { 7826 return mBuilder.isColorized() ? mBuilder.getPrimaryTextColor() 7827 : mBuilder.resolveContrastColor(); 7828 } 7829 7830 private RemoteViews makeMediaBigContentView() { 7831 final int actionCount = Math.min(mBuilder.mActions.size(), MAX_MEDIA_BUTTONS); 7832 // Dont add an expanded view if there is no more content to be revealed 7833 int actionsInCompact = mActionsToShowInCompact == null 7834 ? 0 7835 : Math.min(mActionsToShowInCompact.length, MAX_MEDIA_BUTTONS_IN_COMPACT); 7836 if (!mBuilder.mN.hasLargeIcon() && actionCount <= actionsInCompact) { 7837 return null; 7838 } 7839 RemoteViews big = mBuilder.applyStandardTemplate( 7840 R.layout.notification_template_material_big_media, false, null /* result */); 7841 7842 if (actionCount > 0) { 7843 big.removeAllViews(com.android.internal.R.id.media_actions); 7844 for (int i = 0; i < actionCount; i++) { 7845 final RemoteViews button = generateMediaActionButton(mBuilder.mActions.get(i), 7846 getActionColor()); 7847 big.addView(com.android.internal.R.id.media_actions, button); 7848 } 7849 } 7850 handleImage(big); 7851 return big; 7852 } 7853 7854 private void handleImage(RemoteViews contentView) { 7855 if (mBuilder.mN.hasLargeIcon()) { 7856 contentView.setViewLayoutMarginEndDimen(R.id.line1, 0); 7857 contentView.setViewLayoutMarginEndDimen(R.id.text, 0); 7858 } 7859 } 7860 7861 /** 7862 * @hide 7863 */ 7864 @Override 7865 protected boolean hasProgress() { 7866 return false; 7867 } 7868 } 7869 7870 /** 7871 * Notification style for custom views that are decorated by the system 7872 * 7873 * <p>Instead of providing a notification that is completely custom, a developer can set this 7874 * style and still obtain system decorations like the notification header with the expand 7875 * affordance and actions. 7876 * 7877 * <p>Use {@link android.app.Notification.Builder#setCustomContentView(RemoteViews)}, 7878 * {@link android.app.Notification.Builder#setCustomBigContentView(RemoteViews)} and 7879 * {@link android.app.Notification.Builder#setCustomHeadsUpContentView(RemoteViews)} to set the 7880 * corresponding custom views to display. 7881 * 7882 * To use this style with your Notification, feed it to 7883 * {@link Notification.Builder#setStyle(android.app.Notification.Style)} like so: 7884 * <pre class="prettyprint"> 7885 * Notification noti = new Notification.Builder() 7886 * .setSmallIcon(R.drawable.ic_stat_player) 7887 * .setLargeIcon(albumArtBitmap)) 7888 * .setCustomContentView(contentView); 7889 * .setStyle(<b>new Notification.DecoratedCustomViewStyle()</b>) 7890 * .build(); 7891 * </pre> 7892 */ 7893 public static class DecoratedCustomViewStyle extends Style { 7894 7895 public DecoratedCustomViewStyle() { 7896 } 7897 7898 /** 7899 * @hide 7900 */ 7901 public boolean displayCustomViewInline() { 7902 return true; 7903 } 7904 7905 /** 7906 * @hide 7907 */ 7908 @Override 7909 public RemoteViews makeContentView(boolean increasedHeight) { 7910 return makeStandardTemplateWithCustomContent(mBuilder.mN.contentView); 7911 } 7912 7913 /** 7914 * @hide 7915 */ 7916 @Override 7917 public RemoteViews makeBigContentView() { 7918 return makeDecoratedBigContentView(); 7919 } 7920 7921 /** 7922 * @hide 7923 */ 7924 @Override 7925 public RemoteViews makeHeadsUpContentView(boolean increasedHeight) { 7926 return makeDecoratedHeadsUpContentView(); 7927 } 7928 7929 private RemoteViews makeDecoratedHeadsUpContentView() { 7930 RemoteViews headsUpContentView = mBuilder.mN.headsUpContentView == null 7931 ? mBuilder.mN.contentView 7932 : mBuilder.mN.headsUpContentView; 7933 if (mBuilder.mActions.size() == 0) { 7934 return makeStandardTemplateWithCustomContent(headsUpContentView); 7935 } 7936 TemplateBindResult result = new TemplateBindResult(); 7937 RemoteViews remoteViews = mBuilder.applyStandardTemplateWithActions( 7938 mBuilder.getBigBaseLayoutResource(), result); 7939 buildIntoRemoteViewContent(remoteViews, headsUpContentView, result); 7940 return remoteViews; 7941 } 7942 7943 private RemoteViews makeStandardTemplateWithCustomContent(RemoteViews customContent) { 7944 TemplateBindResult result = new TemplateBindResult(); 7945 RemoteViews remoteViews = mBuilder.applyStandardTemplate( 7946 mBuilder.getBaseLayoutResource(), result); 7947 buildIntoRemoteViewContent(remoteViews, customContent, result); 7948 return remoteViews; 7949 } 7950 7951 private RemoteViews makeDecoratedBigContentView() { 7952 RemoteViews bigContentView = mBuilder.mN.bigContentView == null 7953 ? mBuilder.mN.contentView 7954 : mBuilder.mN.bigContentView; 7955 if (mBuilder.mActions.size() == 0) { 7956 return makeStandardTemplateWithCustomContent(bigContentView); 7957 } 7958 TemplateBindResult result = new TemplateBindResult(); 7959 RemoteViews remoteViews = mBuilder.applyStandardTemplateWithActions( 7960 mBuilder.getBigBaseLayoutResource(), result); 7961 buildIntoRemoteViewContent(remoteViews, bigContentView, result); 7962 return remoteViews; 7963 } 7964 7965 private void buildIntoRemoteViewContent(RemoteViews remoteViews, 7966 RemoteViews customContent, TemplateBindResult result) { 7967 if (customContent != null) { 7968 // Need to clone customContent before adding, because otherwise it can no longer be 7969 // parceled independently of remoteViews. 7970 customContent = customContent.clone(); 7971 remoteViews.removeAllViewsExceptId(R.id.notification_main_column, R.id.progress); 7972 remoteViews.addView(R.id.notification_main_column, customContent, 0 /* index */); 7973 remoteViews.setReapplyDisallowed(); 7974 } 7975 // also update the end margin if there is an image 7976 Resources resources = mBuilder.mContext.getResources(); 7977 int endMargin = resources.getDimensionPixelSize( 7978 R.dimen.notification_content_margin_end) + result.getIconMarginEnd(); 7979 remoteViews.setViewLayoutMarginEnd(R.id.notification_main_column, endMargin); 7980 } 7981 7982 /** 7983 * @hide 7984 */ 7985 @Override 7986 public boolean areNotificationsVisiblyDifferent(Style other) { 7987 if (other == null || getClass() != other.getClass()) { 7988 return true; 7989 } 7990 // Comparison done for all custom RemoteViews, independent of style 7991 return false; 7992 } 7993 } 7994 7995 /** 7996 * Notification style for media custom views that are decorated by the system 7997 * 7998 * <p>Instead of providing a media notification that is completely custom, a developer can set 7999 * this style and still obtain system decorations like the notification header with the expand 8000 * affordance and actions. 8001 * 8002 * <p>Use {@link android.app.Notification.Builder#setCustomContentView(RemoteViews)}, 8003 * {@link android.app.Notification.Builder#setCustomBigContentView(RemoteViews)} and 8004 * {@link android.app.Notification.Builder#setCustomHeadsUpContentView(RemoteViews)} to set the 8005 * corresponding custom views to display. 8006 * <p> 8007 * Contrary to {@link MediaStyle} a developer has to opt-in to the colorizing of the 8008 * notification by using {@link Notification.Builder#setColorized(boolean)}. 8009 * <p> 8010 * To use this style with your Notification, feed it to 8011 * {@link Notification.Builder#setStyle(android.app.Notification.Style)} like so: 8012 * <pre class="prettyprint"> 8013 * Notification noti = new Notification.Builder() 8014 * .setSmallIcon(R.drawable.ic_stat_player) 8015 * .setLargeIcon(albumArtBitmap)) 8016 * .setCustomContentView(contentView); 8017 * .setStyle(<b>new Notification.DecoratedMediaCustomViewStyle()</b> 8018 * .setMediaSession(mySession)) 8019 * .build(); 8020 * </pre> 8021 * 8022 * @see android.app.Notification.DecoratedCustomViewStyle 8023 * @see android.app.Notification.MediaStyle 8024 */ 8025 public static class DecoratedMediaCustomViewStyle extends MediaStyle { 8026 8027 public DecoratedMediaCustomViewStyle() { 8028 } 8029 8030 /** 8031 * @hide 8032 */ 8033 public boolean displayCustomViewInline() { 8034 return true; 8035 } 8036 8037 /** 8038 * @hide 8039 */ 8040 @Override 8041 public RemoteViews makeContentView(boolean increasedHeight) { 8042 RemoteViews remoteViews = super.makeContentView(false /* increasedHeight */); 8043 return buildIntoRemoteView(remoteViews, R.id.notification_content_container, 8044 mBuilder.mN.contentView); 8045 } 8046 8047 /** 8048 * @hide 8049 */ 8050 @Override 8051 public RemoteViews makeBigContentView() { 8052 RemoteViews customRemoteView = mBuilder.mN.bigContentView != null 8053 ? mBuilder.mN.bigContentView 8054 : mBuilder.mN.contentView; 8055 return makeBigContentViewWithCustomContent(customRemoteView); 8056 } 8057 8058 private RemoteViews makeBigContentViewWithCustomContent(RemoteViews customRemoteView) { 8059 RemoteViews remoteViews = super.makeBigContentView(); 8060 if (remoteViews != null) { 8061 return buildIntoRemoteView(remoteViews, R.id.notification_main_column, 8062 customRemoteView); 8063 } else if (customRemoteView != mBuilder.mN.contentView){ 8064 remoteViews = super.makeContentView(false /* increasedHeight */); 8065 return buildIntoRemoteView(remoteViews, R.id.notification_content_container, 8066 customRemoteView); 8067 } else { 8068 return null; 8069 } 8070 } 8071 8072 /** 8073 * @hide 8074 */ 8075 @Override 8076 public RemoteViews makeHeadsUpContentView(boolean increasedHeight) { 8077 RemoteViews customRemoteView = mBuilder.mN.headsUpContentView != null 8078 ? mBuilder.mN.headsUpContentView 8079 : mBuilder.mN.contentView; 8080 return makeBigContentViewWithCustomContent(customRemoteView); 8081 } 8082 8083 /** 8084 * @hide 8085 */ 8086 @Override 8087 public boolean areNotificationsVisiblyDifferent(Style other) { 8088 if (other == null || getClass() != other.getClass()) { 8089 return true; 8090 } 8091 // Comparison done for all custom RemoteViews, independent of style 8092 return false; 8093 } 8094 8095 private RemoteViews buildIntoRemoteView(RemoteViews remoteViews, int id, 8096 RemoteViews customContent) { 8097 if (customContent != null) { 8098 // Need to clone customContent before adding, because otherwise it can no longer be 8099 // parceled independently of remoteViews. 8100 customContent = customContent.clone(); 8101 customContent.overrideTextColors(mBuilder.getPrimaryTextColor()); 8102 remoteViews.removeAllViews(id); 8103 remoteViews.addView(id, customContent); 8104 remoteViews.setReapplyDisallowed(); 8105 } 8106 return remoteViews; 8107 } 8108 } 8109 8110 // When adding a new Style subclass here, don't forget to update 8111 // Builder.getNotificationStyleClass. 8112 8113 /** 8114 * Extender interface for use with {@link Builder#extend}. Extenders may be used to add 8115 * metadata or change options on a notification builder. 8116 */ 8117 public interface Extender { 8118 /** 8119 * Apply this extender to a notification builder. 8120 * @param builder the builder to be modified. 8121 * @return the build object for chaining. 8122 */ 8123 public Builder extend(Builder builder); 8124 } 8125 8126 /** 8127 * Helper class to add wearable extensions to notifications. 8128 * <p class="note"> See 8129 * <a href="{@docRoot}wear/notifications/creating.html">Creating Notifications 8130 * for Android Wear</a> for more information on how to use this class. 8131 * <p> 8132 * To create a notification with wearable extensions: 8133 * <ol> 8134 * <li>Create a {@link android.app.Notification.Builder}, setting any desired 8135 * properties. 8136 * <li>Create a {@link android.app.Notification.WearableExtender}. 8137 * <li>Set wearable-specific properties using the 8138 * {@code add} and {@code set} methods of {@link android.app.Notification.WearableExtender}. 8139 * <li>Call {@link android.app.Notification.Builder#extend} to apply the extensions to a 8140 * notification. 8141 * <li>Post the notification to the notification system with the 8142 * {@code NotificationManager.notify(...)} methods. 8143 * </ol> 8144 * 8145 * <pre class="prettyprint"> 8146 * Notification notif = new Notification.Builder(mContext) 8147 * .setContentTitle("New mail from " + sender.toString()) 8148 * .setContentText(subject) 8149 * .setSmallIcon(R.drawable.new_mail) 8150 * .extend(new Notification.WearableExtender() 8151 * .setContentIcon(R.drawable.new_mail)) 8152 * .build(); 8153 * NotificationManager notificationManger = 8154 * (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 8155 * notificationManger.notify(0, notif);</pre> 8156 * 8157 * <p>Wearable extensions can be accessed on an existing notification by using the 8158 * {@code WearableExtender(Notification)} constructor, 8159 * and then using the {@code get} methods to access values. 8160 * 8161 * <pre class="prettyprint"> 8162 * Notification.WearableExtender wearableExtender = new Notification.WearableExtender( 8163 * notification); 8164 * List<Notification> pages = wearableExtender.getPages();</pre> 8165 */ 8166 public static final class WearableExtender implements Extender { 8167 /** 8168 * Sentinel value for an action index that is unset. 8169 */ 8170 public static final int UNSET_ACTION_INDEX = -1; 8171 8172 /** 8173 * Size value for use with {@link #setCustomSizePreset} to show this notification with 8174 * default sizing. 8175 * <p>For custom display notifications created using {@link #setDisplayIntent}, 8176 * the default is {@link #SIZE_MEDIUM}. All other notifications size automatically based 8177 * on their content. 8178 */ 8179 public static final int SIZE_DEFAULT = 0; 8180 8181 /** 8182 * Size value for use with {@link #setCustomSizePreset} to show this notification 8183 * with an extra small size. 8184 * <p>This value is only applicable for custom display notifications created using 8185 * {@link #setDisplayIntent}. 8186 */ 8187 public static final int SIZE_XSMALL = 1; 8188 8189 /** 8190 * Size value for use with {@link #setCustomSizePreset} to show this notification 8191 * with a small size. 8192 * <p>This value is only applicable for custom display notifications created using 8193 * {@link #setDisplayIntent}. 8194 */ 8195 public static final int SIZE_SMALL = 2; 8196 8197 /** 8198 * Size value for use with {@link #setCustomSizePreset} to show this notification 8199 * with a medium size. 8200 * <p>This value is only applicable for custom display notifications created using 8201 * {@link #setDisplayIntent}. 8202 */ 8203 public static final int SIZE_MEDIUM = 3; 8204 8205 /** 8206 * Size value for use with {@link #setCustomSizePreset} to show this notification 8207 * with a large size. 8208 * <p>This value is only applicable for custom display notifications created using 8209 * {@link #setDisplayIntent}. 8210 */ 8211 public static final int SIZE_LARGE = 4; 8212 8213 /** 8214 * Size value for use with {@link #setCustomSizePreset} to show this notification 8215 * full screen. 8216 * <p>This value is only applicable for custom display notifications created using 8217 * {@link #setDisplayIntent}. 8218 */ 8219 public static final int SIZE_FULL_SCREEN = 5; 8220 8221 /** 8222 * Sentinel value for use with {@link #setHintScreenTimeout} to keep the screen on for a 8223 * short amount of time when this notification is displayed on the screen. This 8224 * is the default value. 8225 */ 8226 public static final int SCREEN_TIMEOUT_SHORT = 0; 8227 8228 /** 8229 * Sentinel value for use with {@link #setHintScreenTimeout} to keep the screen on 8230 * for a longer amount of time when this notification is displayed on the screen. 8231 */ 8232 public static final int SCREEN_TIMEOUT_LONG = -1; 8233 8234 /** Notification extra which contains wearable extensions */ 8235 private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS"; 8236 8237 // Keys within EXTRA_WEARABLE_EXTENSIONS for wearable options. 8238 private static final String KEY_ACTIONS = "actions"; 8239 private static final String KEY_FLAGS = "flags"; 8240 private static final String KEY_DISPLAY_INTENT = "displayIntent"; 8241 private static final String KEY_PAGES = "pages"; 8242 private static final String KEY_BACKGROUND = "background"; 8243 private static final String KEY_CONTENT_ICON = "contentIcon"; 8244 private static final String KEY_CONTENT_ICON_GRAVITY = "contentIconGravity"; 8245 private static final String KEY_CONTENT_ACTION_INDEX = "contentActionIndex"; 8246 private static final String KEY_CUSTOM_SIZE_PRESET = "customSizePreset"; 8247 private static final String KEY_CUSTOM_CONTENT_HEIGHT = "customContentHeight"; 8248 private static final String KEY_GRAVITY = "gravity"; 8249 private static final String KEY_HINT_SCREEN_TIMEOUT = "hintScreenTimeout"; 8250 private static final String KEY_DISMISSAL_ID = "dismissalId"; 8251 private static final String KEY_BRIDGE_TAG = "bridgeTag"; 8252 8253 // Flags bitwise-ored to mFlags 8254 private static final int FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE = 0x1; 8255 private static final int FLAG_HINT_HIDE_ICON = 1 << 1; 8256 private static final int FLAG_HINT_SHOW_BACKGROUND_ONLY = 1 << 2; 8257 private static final int FLAG_START_SCROLL_BOTTOM = 1 << 3; 8258 private static final int FLAG_HINT_AVOID_BACKGROUND_CLIPPING = 1 << 4; 8259 private static final int FLAG_BIG_PICTURE_AMBIENT = 1 << 5; 8260 private static final int FLAG_HINT_CONTENT_INTENT_LAUNCHES_ACTIVITY = 1 << 6; 8261 8262 // Default value for flags integer 8263 private static final int DEFAULT_FLAGS = FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE; 8264 8265 private static final int DEFAULT_CONTENT_ICON_GRAVITY = Gravity.END; 8266 private static final int DEFAULT_GRAVITY = Gravity.BOTTOM; 8267 8268 private ArrayList<Action> mActions = new ArrayList<Action>(); 8269 private int mFlags = DEFAULT_FLAGS; 8270 private PendingIntent mDisplayIntent; 8271 private ArrayList<Notification> mPages = new ArrayList<Notification>(); 8272 private Bitmap mBackground; 8273 private int mContentIcon; 8274 private int mContentIconGravity = DEFAULT_CONTENT_ICON_GRAVITY; 8275 private int mContentActionIndex = UNSET_ACTION_INDEX; 8276 private int mCustomSizePreset = SIZE_DEFAULT; 8277 private int mCustomContentHeight; 8278 private int mGravity = DEFAULT_GRAVITY; 8279 private int mHintScreenTimeout; 8280 private String mDismissalId; 8281 private String mBridgeTag; 8282 8283 /** 8284 * Create a {@link android.app.Notification.WearableExtender} with default 8285 * options. 8286 */ 8287 public WearableExtender() { 8288 } 8289 8290 public WearableExtender(Notification notif) { 8291 Bundle wearableBundle = notif.extras.getBundle(EXTRA_WEARABLE_EXTENSIONS); 8292 if (wearableBundle != null) { 8293 List<Action> actions = wearableBundle.getParcelableArrayList(KEY_ACTIONS); 8294 if (actions != null) { 8295 mActions.addAll(actions); 8296 } 8297 8298 mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS); 8299 mDisplayIntent = wearableBundle.getParcelable(KEY_DISPLAY_INTENT); 8300 8301 Notification[] pages = getNotificationArrayFromBundle( 8302 wearableBundle, KEY_PAGES); 8303 if (pages != null) { 8304 Collections.addAll(mPages, pages); 8305 } 8306 8307 mBackground = wearableBundle.getParcelable(KEY_BACKGROUND); 8308 mContentIcon = wearableBundle.getInt(KEY_CONTENT_ICON); 8309 mContentIconGravity = wearableBundle.getInt(KEY_CONTENT_ICON_GRAVITY, 8310 DEFAULT_CONTENT_ICON_GRAVITY); 8311 mContentActionIndex = wearableBundle.getInt(KEY_CONTENT_ACTION_INDEX, 8312 UNSET_ACTION_INDEX); 8313 mCustomSizePreset = wearableBundle.getInt(KEY_CUSTOM_SIZE_PRESET, 8314 SIZE_DEFAULT); 8315 mCustomContentHeight = wearableBundle.getInt(KEY_CUSTOM_CONTENT_HEIGHT); 8316 mGravity = wearableBundle.getInt(KEY_GRAVITY, DEFAULT_GRAVITY); 8317 mHintScreenTimeout = wearableBundle.getInt(KEY_HINT_SCREEN_TIMEOUT); 8318 mDismissalId = wearableBundle.getString(KEY_DISMISSAL_ID); 8319 mBridgeTag = wearableBundle.getString(KEY_BRIDGE_TAG); 8320 } 8321 } 8322 8323 /** 8324 * Apply wearable extensions to a notification that is being built. This is typically 8325 * called by the {@link android.app.Notification.Builder#extend} method of 8326 * {@link android.app.Notification.Builder}. 8327 */ 8328 @Override 8329 public Notification.Builder extend(Notification.Builder builder) { 8330 Bundle wearableBundle = new Bundle(); 8331 8332 if (!mActions.isEmpty()) { 8333 wearableBundle.putParcelableArrayList(KEY_ACTIONS, mActions); 8334 } 8335 if (mFlags != DEFAULT_FLAGS) { 8336 wearableBundle.putInt(KEY_FLAGS, mFlags); 8337 } 8338 if (mDisplayIntent != null) { 8339 wearableBundle.putParcelable(KEY_DISPLAY_INTENT, mDisplayIntent); 8340 } 8341 if (!mPages.isEmpty()) { 8342 wearableBundle.putParcelableArray(KEY_PAGES, mPages.toArray( 8343 new Notification[mPages.size()])); 8344 } 8345 if (mBackground != null) { 8346 wearableBundle.putParcelable(KEY_BACKGROUND, mBackground); 8347 } 8348 if (mContentIcon != 0) { 8349 wearableBundle.putInt(KEY_CONTENT_ICON, mContentIcon); 8350 } 8351 if (mContentIconGravity != DEFAULT_CONTENT_ICON_GRAVITY) { 8352 wearableBundle.putInt(KEY_CONTENT_ICON_GRAVITY, mContentIconGravity); 8353 } 8354 if (mContentActionIndex != UNSET_ACTION_INDEX) { 8355 wearableBundle.putInt(KEY_CONTENT_ACTION_INDEX, 8356 mContentActionIndex); 8357 } 8358 if (mCustomSizePreset != SIZE_DEFAULT) { 8359 wearableBundle.putInt(KEY_CUSTOM_SIZE_PRESET, mCustomSizePreset); 8360 } 8361 if (mCustomContentHeight != 0) { 8362 wearableBundle.putInt(KEY_CUSTOM_CONTENT_HEIGHT, mCustomContentHeight); 8363 } 8364 if (mGravity != DEFAULT_GRAVITY) { 8365 wearableBundle.putInt(KEY_GRAVITY, mGravity); 8366 } 8367 if (mHintScreenTimeout != 0) { 8368 wearableBundle.putInt(KEY_HINT_SCREEN_TIMEOUT, mHintScreenTimeout); 8369 } 8370 if (mDismissalId != null) { 8371 wearableBundle.putString(KEY_DISMISSAL_ID, mDismissalId); 8372 } 8373 if (mBridgeTag != null) { 8374 wearableBundle.putString(KEY_BRIDGE_TAG, mBridgeTag); 8375 } 8376 8377 builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle); 8378 return builder; 8379 } 8380 8381 @Override 8382 public WearableExtender clone() { 8383 WearableExtender that = new WearableExtender(); 8384 that.mActions = new ArrayList<Action>(this.mActions); 8385 that.mFlags = this.mFlags; 8386 that.mDisplayIntent = this.mDisplayIntent; 8387 that.mPages = new ArrayList<Notification>(this.mPages); 8388 that.mBackground = this.mBackground; 8389 that.mContentIcon = this.mContentIcon; 8390 that.mContentIconGravity = this.mContentIconGravity; 8391 that.mContentActionIndex = this.mContentActionIndex; 8392 that.mCustomSizePreset = this.mCustomSizePreset; 8393 that.mCustomContentHeight = this.mCustomContentHeight; 8394 that.mGravity = this.mGravity; 8395 that.mHintScreenTimeout = this.mHintScreenTimeout; 8396 that.mDismissalId = this.mDismissalId; 8397 that.mBridgeTag = this.mBridgeTag; 8398 return that; 8399 } 8400 8401 /** 8402 * Add a wearable action to this notification. 8403 * 8404 * <p>When wearable actions are added using this method, the set of actions that 8405 * show on a wearable device splits from devices that only show actions added 8406 * using {@link android.app.Notification.Builder#addAction}. This allows for customization 8407 * of which actions display on different devices. 8408 * 8409 * @param action the action to add to this notification 8410 * @return this object for method chaining 8411 * @see android.app.Notification.Action 8412 */ 8413 public WearableExtender addAction(Action action) { 8414 mActions.add(action); 8415 return this; 8416 } 8417 8418 /** 8419 * Adds wearable actions to this notification. 8420 * 8421 * <p>When wearable actions are added using this method, the set of actions that 8422 * show on a wearable device splits from devices that only show actions added 8423 * using {@link android.app.Notification.Builder#addAction}. This allows for customization 8424 * of which actions display on different devices. 8425 * 8426 * @param actions the actions to add to this notification 8427 * @return this object for method chaining 8428 * @see android.app.Notification.Action 8429 */ 8430 public WearableExtender addActions(List<Action> actions) { 8431 mActions.addAll(actions); 8432 return this; 8433 } 8434 8435 /** 8436 * Clear all wearable actions present on this builder. 8437 * @return this object for method chaining. 8438 * @see #addAction 8439 */ 8440 public WearableExtender clearActions() { 8441 mActions.clear(); 8442 return this; 8443 } 8444 8445 /** 8446 * Get the wearable actions present on this notification. 8447 */ 8448 public List<Action> getActions() { 8449 return mActions; 8450 } 8451 8452 /** 8453 * Set an intent to launch inside of an activity view when displaying 8454 * this notification. The {@link PendingIntent} provided should be for an activity. 8455 * 8456 * <pre class="prettyprint"> 8457 * Intent displayIntent = new Intent(context, MyDisplayActivity.class); 8458 * PendingIntent displayPendingIntent = PendingIntent.getActivity(context, 8459 * 0, displayIntent, PendingIntent.FLAG_UPDATE_CURRENT); 8460 * Notification notif = new Notification.Builder(context) 8461 * .extend(new Notification.WearableExtender() 8462 * .setDisplayIntent(displayPendingIntent) 8463 * .setCustomSizePreset(Notification.WearableExtender.SIZE_MEDIUM)) 8464 * .build();</pre> 8465 * 8466 * <p>The activity to launch needs to allow embedding, must be exported, and 8467 * should have an empty task affinity. It is also recommended to use the device 8468 * default light theme. 8469 * 8470 * <p>Example AndroidManifest.xml entry: 8471 * <pre class="prettyprint"> 8472 * <activity android:name="com.example.MyDisplayActivity" 8473 * android:exported="true" 8474 * android:allowEmbedded="true" 8475 * android:taskAffinity="" 8476 * android:theme="@android:style/Theme.DeviceDefault.Light" /></pre> 8477 * 8478 * @param intent the {@link PendingIntent} for an activity 8479 * @return this object for method chaining 8480 * @see android.app.Notification.WearableExtender#getDisplayIntent 8481 */ 8482 public WearableExtender setDisplayIntent(PendingIntent intent) { 8483 mDisplayIntent = intent; 8484 return this; 8485 } 8486 8487 /** 8488 * Get the intent to launch inside of an activity view when displaying this 8489 * notification. This {@code PendingIntent} should be for an activity. 8490 */ 8491 public PendingIntent getDisplayIntent() { 8492 return mDisplayIntent; 8493 } 8494 8495 /** 8496 * Add an additional page of content to display with this notification. The current 8497 * notification forms the first page, and pages added using this function form 8498 * subsequent pages. This field can be used to separate a notification into multiple 8499 * sections. 8500 * 8501 * @param page the notification to add as another page 8502 * @return this object for method chaining 8503 * @see android.app.Notification.WearableExtender#getPages 8504 */ 8505 public WearableExtender addPage(Notification page) { 8506 mPages.add(page); 8507 return this; 8508 } 8509 8510 /** 8511 * Add additional pages of content to display with this notification. The current 8512 * notification forms the first page, and pages added using this function form 8513 * subsequent pages. This field can be used to separate a notification into multiple 8514 * sections. 8515 * 8516 * @param pages a list of notifications 8517 * @return this object for method chaining 8518 * @see android.app.Notification.WearableExtender#getPages 8519 */ 8520 public WearableExtender addPages(List<Notification> pages) { 8521 mPages.addAll(pages); 8522 return this; 8523 } 8524 8525 /** 8526 * Clear all additional pages present on this builder. 8527 * @return this object for method chaining. 8528 * @see #addPage 8529 */ 8530 public WearableExtender clearPages() { 8531 mPages.clear(); 8532 return this; 8533 } 8534 8535 /** 8536 * Get the array of additional pages of content for displaying this notification. The 8537 * current notification forms the first page, and elements within this array form 8538 * subsequent pages. This field can be used to separate a notification into multiple 8539 * sections. 8540 * @return the pages for this notification 8541 */ 8542 public List<Notification> getPages() { 8543 return mPages; 8544 } 8545 8546 /** 8547 * Set a background image to be displayed behind the notification content. 8548 * Contrary to the {@link android.app.Notification.BigPictureStyle}, this background 8549 * will work with any notification style. 8550 * 8551 * @param background the background bitmap 8552 * @return this object for method chaining 8553 * @see android.app.Notification.WearableExtender#getBackground 8554 */ 8555 public WearableExtender setBackground(Bitmap background) { 8556 mBackground = background; 8557 return this; 8558 } 8559 8560 /** 8561 * Get a background image to be displayed behind the notification content. 8562 * Contrary to the {@link android.app.Notification.BigPictureStyle}, this background 8563 * will work with any notification style. 8564 * 8565 * @return the background image 8566 * @see android.app.Notification.WearableExtender#setBackground 8567 */ 8568 public Bitmap getBackground() { 8569 return mBackground; 8570 } 8571 8572 /** 8573 * Set an icon that goes with the content of this notification. 8574 */ 8575 @Deprecated 8576 public WearableExtender setContentIcon(int icon) { 8577 mContentIcon = icon; 8578 return this; 8579 } 8580 8581 /** 8582 * Get an icon that goes with the content of this notification. 8583 */ 8584 @Deprecated 8585 public int getContentIcon() { 8586 return mContentIcon; 8587 } 8588 8589 /** 8590 * Set the gravity that the content icon should have within the notification display. 8591 * Supported values include {@link android.view.Gravity#START} and 8592 * {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}. 8593 * @see #setContentIcon 8594 */ 8595 @Deprecated 8596 public WearableExtender setContentIconGravity(int contentIconGravity) { 8597 mContentIconGravity = contentIconGravity; 8598 return this; 8599 } 8600 8601 /** 8602 * Get the gravity that the content icon should have within the notification display. 8603 * Supported values include {@link android.view.Gravity#START} and 8604 * {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}. 8605 * @see #getContentIcon 8606 */ 8607 @Deprecated 8608 public int getContentIconGravity() { 8609 return mContentIconGravity; 8610 } 8611 8612 /** 8613 * Set an action from this notification's actions to be clickable with the content of 8614 * this notification. This action will no longer display separately from the 8615 * notification's content. 8616 * 8617 * <p>For notifications with multiple pages, child pages can also have content actions 8618 * set, although the list of available actions comes from the main notification and not 8619 * from the child page's notification. 8620 * 8621 * @param actionIndex The index of the action to hoist onto the current notification page. 8622 * If wearable actions were added to the main notification, this index 8623 * will apply to that list, otherwise it will apply to the regular 8624 * actions list. 8625 */ 8626 public WearableExtender setContentAction(int actionIndex) { 8627 mContentActionIndex = actionIndex; 8628 return this; 8629 } 8630 8631 /** 8632 * Get the index of the notification action, if any, that was specified as being clickable 8633 * with the content of this notification. This action will no longer display separately 8634 * from the notification's content. 8635 * 8636 * <p>For notifications with multiple pages, child pages can also have content actions 8637 * set, although the list of available actions comes from the main notification and not 8638 * from the child page's notification. 8639 * 8640 * <p>If wearable specific actions were added to the main notification, this index will 8641 * apply to that list, otherwise it will apply to the regular actions list. 8642 * 8643 * @return the action index or {@link #UNSET_ACTION_INDEX} if no action was selected. 8644 */ 8645 public int getContentAction() { 8646 return mContentActionIndex; 8647 } 8648 8649 /** 8650 * Set the gravity that this notification should have within the available viewport space. 8651 * Supported values include {@link android.view.Gravity#TOP}, 8652 * {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}. 8653 * The default value is {@link android.view.Gravity#BOTTOM}. 8654 */ 8655 @Deprecated 8656 public WearableExtender setGravity(int gravity) { 8657 mGravity = gravity; 8658 return this; 8659 } 8660 8661 /** 8662 * Get the gravity that this notification should have within the available viewport space. 8663 * Supported values include {@link android.view.Gravity#TOP}, 8664 * {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}. 8665 * The default value is {@link android.view.Gravity#BOTTOM}. 8666 */ 8667 @Deprecated 8668 public int getGravity() { 8669 return mGravity; 8670 } 8671 8672 /** 8673 * Set the custom size preset for the display of this notification out of the available 8674 * presets found in {@link android.app.Notification.WearableExtender}, e.g. 8675 * {@link #SIZE_LARGE}. 8676 * <p>Some custom size presets are only applicable for custom display notifications created 8677 * using {@link android.app.Notification.WearableExtender#setDisplayIntent}. Check the 8678 * documentation for the preset in question. See also 8679 * {@link #setCustomContentHeight} and {@link #getCustomSizePreset}. 8680 */ 8681 @Deprecated 8682 public WearableExtender setCustomSizePreset(int sizePreset) { 8683 mCustomSizePreset = sizePreset; 8684 return this; 8685 } 8686 8687 /** 8688 * Get the custom size preset for the display of this notification out of the available 8689 * presets found in {@link android.app.Notification.WearableExtender}, e.g. 8690 * {@link #SIZE_LARGE}. 8691 * <p>Some custom size presets are only applicable for custom display notifications created 8692 * using {@link #setDisplayIntent}. Check the documentation for the preset in question. 8693 * See also {@link #setCustomContentHeight} and {@link #setCustomSizePreset}. 8694 */ 8695 @Deprecated 8696 public int getCustomSizePreset() { 8697 return mCustomSizePreset; 8698 } 8699 8700 /** 8701 * Set the custom height in pixels for the display of this notification's content. 8702 * <p>This option is only available for custom display notifications created 8703 * using {@link android.app.Notification.WearableExtender#setDisplayIntent}. See also 8704 * {@link android.app.Notification.WearableExtender#setCustomSizePreset} and 8705 * {@link #getCustomContentHeight}. 8706 */ 8707 @Deprecated 8708 public WearableExtender setCustomContentHeight(int height) { 8709 mCustomContentHeight = height; 8710 return this; 8711 } 8712 8713 /** 8714 * Get the custom height in pixels for the display of this notification's content. 8715 * <p>This option is only available for custom display notifications created 8716 * using {@link #setDisplayIntent}. See also {@link #setCustomSizePreset} and 8717 * {@link #setCustomContentHeight}. 8718 */ 8719 @Deprecated 8720 public int getCustomContentHeight() { 8721 return mCustomContentHeight; 8722 } 8723 8724 /** 8725 * Set whether the scrolling position for the contents of this notification should start 8726 * at the bottom of the contents instead of the top when the contents are too long to 8727 * display within the screen. Default is false (start scroll at the top). 8728 */ 8729 public WearableExtender setStartScrollBottom(boolean startScrollBottom) { 8730 setFlag(FLAG_START_SCROLL_BOTTOM, startScrollBottom); 8731 return this; 8732 } 8733 8734 /** 8735 * Get whether the scrolling position for the contents of this notification should start 8736 * at the bottom of the contents instead of the top when the contents are too long to 8737 * display within the screen. Default is false (start scroll at the top). 8738 */ 8739 public boolean getStartScrollBottom() { 8740 return (mFlags & FLAG_START_SCROLL_BOTTOM) != 0; 8741 } 8742 8743 /** 8744 * Set whether the content intent is available when the wearable device is not connected 8745 * to a companion device. The user can still trigger this intent when the wearable device 8746 * is offline, but a visual hint will indicate that the content intent may not be available. 8747 * Defaults to true. 8748 */ 8749 public WearableExtender setContentIntentAvailableOffline( 8750 boolean contentIntentAvailableOffline) { 8751 setFlag(FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE, contentIntentAvailableOffline); 8752 return this; 8753 } 8754 8755 /** 8756 * Get whether the content intent is available when the wearable device is not connected 8757 * to a companion device. The user can still trigger this intent when the wearable device 8758 * is offline, but a visual hint will indicate that the content intent may not be available. 8759 * Defaults to true. 8760 */ 8761 public boolean getContentIntentAvailableOffline() { 8762 return (mFlags & FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE) != 0; 8763 } 8764 8765 /** 8766 * Set a hint that this notification's icon should not be displayed. 8767 * @param hintHideIcon {@code true} to hide the icon, {@code false} otherwise. 8768 * @return this object for method chaining 8769 */ 8770 @Deprecated 8771 public WearableExtender setHintHideIcon(boolean hintHideIcon) { 8772 setFlag(FLAG_HINT_HIDE_ICON, hintHideIcon); 8773 return this; 8774 } 8775 8776 /** 8777 * Get a hint that this notification's icon should not be displayed. 8778 * @return {@code true} if this icon should not be displayed, false otherwise. 8779 * The default value is {@code false} if this was never set. 8780 */ 8781 @Deprecated 8782 public boolean getHintHideIcon() { 8783 return (mFlags & FLAG_HINT_HIDE_ICON) != 0; 8784 } 8785 8786 /** 8787 * Set a visual hint that only the background image of this notification should be 8788 * displayed, and other semantic content should be hidden. This hint is only applicable 8789 * to sub-pages added using {@link #addPage}. 8790 */ 8791 @Deprecated 8792 public WearableExtender setHintShowBackgroundOnly(boolean hintShowBackgroundOnly) { 8793 setFlag(FLAG_HINT_SHOW_BACKGROUND_ONLY, hintShowBackgroundOnly); 8794 return this; 8795 } 8796 8797 /** 8798 * Get a visual hint that only the background image of this notification should be 8799 * displayed, and other semantic content should be hidden. This hint is only applicable 8800 * to sub-pages added using {@link android.app.Notification.WearableExtender#addPage}. 8801 */ 8802 @Deprecated 8803 public boolean getHintShowBackgroundOnly() { 8804 return (mFlags & FLAG_HINT_SHOW_BACKGROUND_ONLY) != 0; 8805 } 8806 8807 /** 8808 * Set a hint that this notification's background should not be clipped if possible, 8809 * and should instead be resized to fully display on the screen, retaining the aspect 8810 * ratio of the image. This can be useful for images like barcodes or qr codes. 8811 * @param hintAvoidBackgroundClipping {@code true} to avoid clipping if possible. 8812 * @return this object for method chaining 8813 */ 8814 @Deprecated 8815 public WearableExtender setHintAvoidBackgroundClipping( 8816 boolean hintAvoidBackgroundClipping) { 8817 setFlag(FLAG_HINT_AVOID_BACKGROUND_CLIPPING, hintAvoidBackgroundClipping); 8818 return this; 8819 } 8820 8821 /** 8822 * Get a hint that this notification's background should not be clipped if possible, 8823 * and should instead be resized to fully display on the screen, retaining the aspect 8824 * ratio of the image. This can be useful for images like barcodes or qr codes. 8825 * @return {@code true} if it's ok if the background is clipped on the screen, false 8826 * otherwise. The default value is {@code false} if this was never set. 8827 */ 8828 @Deprecated 8829 public boolean getHintAvoidBackgroundClipping() { 8830 return (mFlags & FLAG_HINT_AVOID_BACKGROUND_CLIPPING) != 0; 8831 } 8832 8833 /** 8834 * Set a hint that the screen should remain on for at least this duration when 8835 * this notification is displayed on the screen. 8836 * @param timeout The requested screen timeout in milliseconds. Can also be either 8837 * {@link #SCREEN_TIMEOUT_SHORT} or {@link #SCREEN_TIMEOUT_LONG}. 8838 * @return this object for method chaining 8839 */ 8840 @Deprecated 8841 public WearableExtender setHintScreenTimeout(int timeout) { 8842 mHintScreenTimeout = timeout; 8843 return this; 8844 } 8845 8846 /** 8847 * Get the duration, in milliseconds, that the screen should remain on for 8848 * when this notification is displayed. 8849 * @return the duration in milliseconds if > 0, or either one of the sentinel values 8850 * {@link #SCREEN_TIMEOUT_SHORT} or {@link #SCREEN_TIMEOUT_LONG}. 8851 */ 8852 @Deprecated 8853 public int getHintScreenTimeout() { 8854 return mHintScreenTimeout; 8855 } 8856 8857 /** 8858 * Set a hint that this notification's {@link BigPictureStyle} (if present) should be 8859 * converted to low-bit and displayed in ambient mode, especially useful for barcodes and 8860 * qr codes, as well as other simple black-and-white tickets. 8861 * @param hintAmbientBigPicture {@code true} to enable converstion and ambient. 8862 * @return this object for method chaining 8863 */ 8864 public WearableExtender setHintAmbientBigPicture(boolean hintAmbientBigPicture) { 8865 setFlag(FLAG_BIG_PICTURE_AMBIENT, hintAmbientBigPicture); 8866 return this; 8867 } 8868 8869 /** 8870 * Get a hint that this notification's {@link BigPictureStyle} (if present) should be 8871 * converted to low-bit and displayed in ambient mode, especially useful for barcodes and 8872 * qr codes, as well as other simple black-and-white tickets. 8873 * @return {@code true} if it should be displayed in ambient, false otherwise 8874 * otherwise. The default value is {@code false} if this was never set. 8875 */ 8876 public boolean getHintAmbientBigPicture() { 8877 return (mFlags & FLAG_BIG_PICTURE_AMBIENT) != 0; 8878 } 8879 8880 /** 8881 * Set a hint that this notification's content intent will launch an {@link Activity} 8882 * directly, telling the platform that it can generate the appropriate transitions. 8883 * @param hintContentIntentLaunchesActivity {@code true} if the content intent will launch 8884 * an activity and transitions should be generated, false otherwise. 8885 * @return this object for method chaining 8886 */ 8887 public WearableExtender setHintContentIntentLaunchesActivity( 8888 boolean hintContentIntentLaunchesActivity) { 8889 setFlag(FLAG_HINT_CONTENT_INTENT_LAUNCHES_ACTIVITY, hintContentIntentLaunchesActivity); 8890 return this; 8891 } 8892 8893 /** 8894 * Get a hint that this notification's content intent will launch an {@link Activity} 8895 * directly, telling the platform that it can generate the appropriate transitions 8896 * @return {@code true} if the content intent will launch an activity and transitions should 8897 * be generated, false otherwise. The default value is {@code false} if this was never set. 8898 */ 8899 public boolean getHintContentIntentLaunchesActivity() { 8900 return (mFlags & FLAG_HINT_CONTENT_INTENT_LAUNCHES_ACTIVITY) != 0; 8901 } 8902 8903 /** 8904 * Sets the dismissal id for this notification. If a notification is posted with a 8905 * dismissal id, then when that notification is canceled, notifications on other wearables 8906 * and the paired Android phone having that same dismissal id will also be canceled. See 8907 * <a href="{@docRoot}wear/notifications/index.html">Adding Wearable Features to 8908 * Notifications</a> for more information. 8909 * @param dismissalId the dismissal id of the notification. 8910 * @return this object for method chaining 8911 */ 8912 public WearableExtender setDismissalId(String dismissalId) { 8913 mDismissalId = dismissalId; 8914 return this; 8915 } 8916 8917 /** 8918 * Returns the dismissal id of the notification. 8919 * @return the dismissal id of the notification or null if it has not been set. 8920 */ 8921 public String getDismissalId() { 8922 return mDismissalId; 8923 } 8924 8925 /** 8926 * Sets a bridge tag for this notification. A bridge tag can be set for notifications 8927 * posted from a phone to provide finer-grained control on what notifications are bridged 8928 * to wearables. See <a href="{@docRoot}wear/notifications/index.html">Adding Wearable 8929 * Features to Notifications</a> for more information. 8930 * @param bridgeTag the bridge tag of the notification. 8931 * @return this object for method chaining 8932 */ 8933 public WearableExtender setBridgeTag(String bridgeTag) { 8934 mBridgeTag = bridgeTag; 8935 return this; 8936 } 8937 8938 /** 8939 * Returns the bridge tag of the notification. 8940 * @return the bridge tag or null if not present. 8941 */ 8942 public String getBridgeTag() { 8943 return mBridgeTag; 8944 } 8945 8946 private void setFlag(int mask, boolean value) { 8947 if (value) { 8948 mFlags |= mask; 8949 } else { 8950 mFlags &= ~mask; 8951 } 8952 } 8953 } 8954 8955 /** 8956 * <p>Helper class to add Android Auto extensions to notifications. To create a notification 8957 * with car extensions: 8958 * 8959 * <ol> 8960 * <li>Create an {@link Notification.Builder}, setting any desired 8961 * properties. 8962 * <li>Create a {@link CarExtender}. 8963 * <li>Set car-specific properties using the {@code add} and {@code set} methods of 8964 * {@link CarExtender}. 8965 * <li>Call {@link Notification.Builder#extend(Notification.Extender)} 8966 * to apply the extensions to a notification. 8967 * </ol> 8968 * 8969 * <pre class="prettyprint"> 8970 * Notification notification = new Notification.Builder(context) 8971 * ... 8972 * .extend(new CarExtender() 8973 * .set*(...)) 8974 * .build(); 8975 * </pre> 8976 * 8977 * <p>Car extensions can be accessed on an existing notification by using the 8978 * {@code CarExtender(Notification)} constructor, and then using the {@code get} methods 8979 * to access values. 8980 */ 8981 public static final class CarExtender implements Extender { 8982 private static final String TAG = "CarExtender"; 8983 8984 private static final String EXTRA_CAR_EXTENDER = "android.car.EXTENSIONS"; 8985 private static final String EXTRA_LARGE_ICON = "large_icon"; 8986 private static final String EXTRA_CONVERSATION = "car_conversation"; 8987 private static final String EXTRA_COLOR = "app_color"; 8988 8989 private Bitmap mLargeIcon; 8990 private UnreadConversation mUnreadConversation; 8991 private int mColor = Notification.COLOR_DEFAULT; 8992 8993 /** 8994 * Create a {@link CarExtender} with default options. 8995 */ 8996 public CarExtender() { 8997 } 8998 8999 /** 9000 * Create a {@link CarExtender} from the CarExtender options of an existing Notification. 9001 * 9002 * @param notif The notification from which to copy options. 9003 */ 9004 public CarExtender(Notification notif) { 9005 Bundle carBundle = notif.extras == null ? 9006 null : notif.extras.getBundle(EXTRA_CAR_EXTENDER); 9007 if (carBundle != null) { 9008 mLargeIcon = carBundle.getParcelable(EXTRA_LARGE_ICON); 9009 mColor = carBundle.getInt(EXTRA_COLOR, Notification.COLOR_DEFAULT); 9010 9011 Bundle b = carBundle.getBundle(EXTRA_CONVERSATION); 9012 mUnreadConversation = UnreadConversation.getUnreadConversationFromBundle(b); 9013 } 9014 } 9015 9016 /** 9017 * Apply car extensions to a notification that is being built. This is typically called by 9018 * the {@link Notification.Builder#extend(Notification.Extender)} 9019 * method of {@link Notification.Builder}. 9020 */ 9021 @Override 9022 public Notification.Builder extend(Notification.Builder builder) { 9023 Bundle carExtensions = new Bundle(); 9024 9025 if (mLargeIcon != null) { 9026 carExtensions.putParcelable(EXTRA_LARGE_ICON, mLargeIcon); 9027 } 9028 if (mColor != Notification.COLOR_DEFAULT) { 9029 carExtensions.putInt(EXTRA_COLOR, mColor); 9030 } 9031 9032 if (mUnreadConversation != null) { 9033 Bundle b = mUnreadConversation.getBundleForUnreadConversation(); 9034 carExtensions.putBundle(EXTRA_CONVERSATION, b); 9035 } 9036 9037 builder.getExtras().putBundle(EXTRA_CAR_EXTENDER, carExtensions); 9038 return builder; 9039 } 9040 9041 /** 9042 * Sets the accent color to use when Android Auto presents the notification. 9043 * 9044 * Android Auto uses the color set with {@link Notification.Builder#setColor(int)} 9045 * to accent the displayed notification. However, not all colors are acceptable in an 9046 * automotive setting. This method can be used to override the color provided in the 9047 * notification in such a situation. 9048 */ 9049 public CarExtender setColor(@ColorInt int color) { 9050 mColor = color; 9051 return this; 9052 } 9053 9054 /** 9055 * Gets the accent color. 9056 * 9057 * @see #setColor 9058 */ 9059 @ColorInt 9060 public int getColor() { 9061 return mColor; 9062 } 9063 9064 /** 9065 * Sets the large icon of the car notification. 9066 * 9067 * If no large icon is set in the extender, Android Auto will display the icon 9068 * specified by {@link Notification.Builder#setLargeIcon(android.graphics.Bitmap)} 9069 * 9070 * @param largeIcon The large icon to use in the car notification. 9071 * @return This object for method chaining. 9072 */ 9073 public CarExtender setLargeIcon(Bitmap largeIcon) { 9074 mLargeIcon = largeIcon; 9075 return this; 9076 } 9077 9078 /** 9079 * Gets the large icon used in this car notification, or null if no icon has been set. 9080 * 9081 * @return The large icon for the car notification. 9082 * @see CarExtender#setLargeIcon 9083 */ 9084 public Bitmap getLargeIcon() { 9085 return mLargeIcon; 9086 } 9087 9088 /** 9089 * Sets the unread conversation in a message notification. 9090 * 9091 * @param unreadConversation The unread part of the conversation this notification conveys. 9092 * @return This object for method chaining. 9093 */ 9094 public CarExtender setUnreadConversation(UnreadConversation unreadConversation) { 9095 mUnreadConversation = unreadConversation; 9096 return this; 9097 } 9098 9099 /** 9100 * Returns the unread conversation conveyed by this notification. 9101 * @see #setUnreadConversation(UnreadConversation) 9102 */ 9103 public UnreadConversation getUnreadConversation() { 9104 return mUnreadConversation; 9105 } 9106 9107 /** 9108 * A class which holds the unread messages from a conversation. 9109 */ 9110 public static class UnreadConversation { 9111 private static final String KEY_AUTHOR = "author"; 9112 private static final String KEY_TEXT = "text"; 9113 private static final String KEY_MESSAGES = "messages"; 9114 private static final String KEY_REMOTE_INPUT = "remote_input"; 9115 private static final String KEY_ON_REPLY = "on_reply"; 9116 private static final String KEY_ON_READ = "on_read"; 9117 private static final String KEY_PARTICIPANTS = "participants"; 9118 private static final String KEY_TIMESTAMP = "timestamp"; 9119 9120 private final String[] mMessages; 9121 private final RemoteInput mRemoteInput; 9122 private final PendingIntent mReplyPendingIntent; 9123 private final PendingIntent mReadPendingIntent; 9124 private final String[] mParticipants; 9125 private final long mLatestTimestamp; 9126 9127 UnreadConversation(String[] messages, RemoteInput remoteInput, 9128 PendingIntent replyPendingIntent, PendingIntent readPendingIntent, 9129 String[] participants, long latestTimestamp) { 9130 mMessages = messages; 9131 mRemoteInput = remoteInput; 9132 mReadPendingIntent = readPendingIntent; 9133 mReplyPendingIntent = replyPendingIntent; 9134 mParticipants = participants; 9135 mLatestTimestamp = latestTimestamp; 9136 } 9137 9138 /** 9139 * Gets the list of messages conveyed by this notification. 9140 */ 9141 public String[] getMessages() { 9142 return mMessages; 9143 } 9144 9145 /** 9146 * Gets the remote input that will be used to convey the response to a message list, or 9147 * null if no such remote input exists. 9148 */ 9149 public RemoteInput getRemoteInput() { 9150 return mRemoteInput; 9151 } 9152 9153 /** 9154 * Gets the pending intent that will be triggered when the user replies to this 9155 * notification. 9156 */ 9157 public PendingIntent getReplyPendingIntent() { 9158 return mReplyPendingIntent; 9159 } 9160 9161 /** 9162 * Gets the pending intent that Android Auto will send after it reads aloud all messages 9163 * in this object's message list. 9164 */ 9165 public PendingIntent getReadPendingIntent() { 9166 return mReadPendingIntent; 9167 } 9168 9169 /** 9170 * Gets the participants in the conversation. 9171 */ 9172 public String[] getParticipants() { 9173 return mParticipants; 9174 } 9175 9176 /** 9177 * Gets the firs participant in the conversation. 9178 */ 9179 public String getParticipant() { 9180 return mParticipants.length > 0 ? mParticipants[0] : null; 9181 } 9182 9183 /** 9184 * Gets the timestamp of the conversation. 9185 */ 9186 public long getLatestTimestamp() { 9187 return mLatestTimestamp; 9188 } 9189 9190 Bundle getBundleForUnreadConversation() { 9191 Bundle b = new Bundle(); 9192 String author = null; 9193 if (mParticipants != null && mParticipants.length > 1) { 9194 author = mParticipants[0]; 9195 } 9196 Parcelable[] messages = new Parcelable[mMessages.length]; 9197 for (int i = 0; i < messages.length; i++) { 9198 Bundle m = new Bundle(); 9199 m.putString(KEY_TEXT, mMessages[i]); 9200 m.putString(KEY_AUTHOR, author); 9201 messages[i] = m; 9202 } 9203 b.putParcelableArray(KEY_MESSAGES, messages); 9204 if (mRemoteInput != null) { 9205 b.putParcelable(KEY_REMOTE_INPUT, mRemoteInput); 9206 } 9207 b.putParcelable(KEY_ON_REPLY, mReplyPendingIntent); 9208 b.putParcelable(KEY_ON_READ, mReadPendingIntent); 9209 b.putStringArray(KEY_PARTICIPANTS, mParticipants); 9210 b.putLong(KEY_TIMESTAMP, mLatestTimestamp); 9211 return b; 9212 } 9213 9214 static UnreadConversation getUnreadConversationFromBundle(Bundle b) { 9215 if (b == null) { 9216 return null; 9217 } 9218 Parcelable[] parcelableMessages = b.getParcelableArray(KEY_MESSAGES); 9219 String[] messages = null; 9220 if (parcelableMessages != null) { 9221 String[] tmp = new String[parcelableMessages.length]; 9222 boolean success = true; 9223 for (int i = 0; i < tmp.length; i++) { 9224 if (!(parcelableMessages[i] instanceof Bundle)) { 9225 success = false; 9226 break; 9227 } 9228 tmp[i] = ((Bundle) parcelableMessages[i]).getString(KEY_TEXT); 9229 if (tmp[i] == null) { 9230 success = false; 9231 break; 9232 } 9233 } 9234 if (success) { 9235 messages = tmp; 9236 } else { 9237 return null; 9238 } 9239 } 9240 9241 PendingIntent onRead = b.getParcelable(KEY_ON_READ); 9242 PendingIntent onReply = b.getParcelable(KEY_ON_REPLY); 9243 9244 RemoteInput remoteInput = b.getParcelable(KEY_REMOTE_INPUT); 9245 9246 String[] participants = b.getStringArray(KEY_PARTICIPANTS); 9247 if (participants == null || participants.length != 1) { 9248 return null; 9249 } 9250 9251 return new UnreadConversation(messages, 9252 remoteInput, 9253 onReply, 9254 onRead, 9255 participants, b.getLong(KEY_TIMESTAMP)); 9256 } 9257 }; 9258 9259 /** 9260 * Builder class for {@link CarExtender.UnreadConversation} objects. 9261 */ 9262 public static class Builder { 9263 private final List<String> mMessages = new ArrayList<String>(); 9264 private final String mParticipant; 9265 private RemoteInput mRemoteInput; 9266 private PendingIntent mReadPendingIntent; 9267 private PendingIntent mReplyPendingIntent; 9268 private long mLatestTimestamp; 9269 9270 /** 9271 * Constructs a new builder for {@link CarExtender.UnreadConversation}. 9272 * 9273 * @param name The name of the other participant in the conversation. 9274 */ 9275 public Builder(String name) { 9276 mParticipant = name; 9277 } 9278 9279 /** 9280 * Appends a new unread message to the list of messages for this conversation. 9281 * 9282 * The messages should be added from oldest to newest. 9283 * 9284 * @param message The text of the new unread message. 9285 * @return This object for method chaining. 9286 */ 9287 public Builder addMessage(String message) { 9288 mMessages.add(message); 9289 return this; 9290 } 9291 9292 /** 9293 * Sets the pending intent and remote input which will convey the reply to this 9294 * notification. 9295 * 9296 * @param pendingIntent The pending intent which will be triggered on a reply. 9297 * @param remoteInput The remote input parcelable which will carry the reply. 9298 * @return This object for method chaining. 9299 * 9300 * @see CarExtender.UnreadConversation#getRemoteInput 9301 * @see CarExtender.UnreadConversation#getReplyPendingIntent 9302 */ 9303 public Builder setReplyAction( 9304 PendingIntent pendingIntent, RemoteInput remoteInput) { 9305 mRemoteInput = remoteInput; 9306 mReplyPendingIntent = pendingIntent; 9307 9308 return this; 9309 } 9310 9311 /** 9312 * Sets the pending intent that will be sent once the messages in this notification 9313 * are read. 9314 * 9315 * @param pendingIntent The pending intent to use. 9316 * @return This object for method chaining. 9317 */ 9318 public Builder setReadPendingIntent(PendingIntent pendingIntent) { 9319 mReadPendingIntent = pendingIntent; 9320 return this; 9321 } 9322 9323 /** 9324 * Sets the timestamp of the most recent message in an unread conversation. 9325 * 9326 * If a messaging notification has been posted by your application and has not 9327 * yet been cancelled, posting a later notification with the same id and tag 9328 * but without a newer timestamp may result in Android Auto not displaying a 9329 * heads up notification for the later notification. 9330 * 9331 * @param timestamp The timestamp of the most recent message in the conversation. 9332 * @return This object for method chaining. 9333 */ 9334 public Builder setLatestTimestamp(long timestamp) { 9335 mLatestTimestamp = timestamp; 9336 return this; 9337 } 9338 9339 /** 9340 * Builds a new unread conversation object. 9341 * 9342 * @return The new unread conversation object. 9343 */ 9344 public UnreadConversation build() { 9345 String[] messages = mMessages.toArray(new String[mMessages.size()]); 9346 String[] participants = { mParticipant }; 9347 return new UnreadConversation(messages, mRemoteInput, mReplyPendingIntent, 9348 mReadPendingIntent, participants, mLatestTimestamp); 9349 } 9350 } 9351 } 9352 9353 /** 9354 * <p>Helper class to add Android TV extensions to notifications. To create a notification 9355 * with a TV extension: 9356 * 9357 * <ol> 9358 * <li>Create an {@link Notification.Builder}, setting any desired properties. 9359 * <li>Create a {@link TvExtender}. 9360 * <li>Set TV-specific properties using the {@code set} methods of 9361 * {@link TvExtender}. 9362 * <li>Call {@link Notification.Builder#extend(Notification.Extender)} 9363 * to apply the extension to a notification. 9364 * </ol> 9365 * 9366 * <pre class="prettyprint"> 9367 * Notification notification = new Notification.Builder(context) 9368 * ... 9369 * .extend(new TvExtender() 9370 * .set*(...)) 9371 * .build(); 9372 * </pre> 9373 * 9374 * <p>TV extensions can be accessed on an existing notification by using the 9375 * {@code TvExtender(Notification)} constructor, and then using the {@code get} methods 9376 * to access values. 9377 * 9378 * @hide 9379 */ 9380 @SystemApi 9381 public static final class TvExtender implements Extender { 9382 private static final String TAG = "TvExtender"; 9383 9384 private static final String EXTRA_TV_EXTENDER = "android.tv.EXTENSIONS"; 9385 private static final String EXTRA_FLAGS = "flags"; 9386 private static final String EXTRA_CONTENT_INTENT = "content_intent"; 9387 private static final String EXTRA_DELETE_INTENT = "delete_intent"; 9388 private static final String EXTRA_CHANNEL_ID = "channel_id"; 9389 private static final String EXTRA_SUPPRESS_SHOW_OVER_APPS = "suppressShowOverApps"; 9390 9391 // Flags bitwise-ored to mFlags 9392 private static final int FLAG_AVAILABLE_ON_TV = 0x1; 9393 9394 private int mFlags; 9395 private String mChannelId; 9396 private PendingIntent mContentIntent; 9397 private PendingIntent mDeleteIntent; 9398 private boolean mSuppressShowOverApps; 9399 9400 /** 9401 * Create a {@link TvExtender} with default options. 9402 */ 9403 public TvExtender() { 9404 mFlags = FLAG_AVAILABLE_ON_TV; 9405 } 9406 9407 /** 9408 * Create a {@link TvExtender} from the TvExtender options of an existing Notification. 9409 * 9410 * @param notif The notification from which to copy options. 9411 */ 9412 public TvExtender(Notification notif) { 9413 Bundle bundle = notif.extras == null ? 9414 null : notif.extras.getBundle(EXTRA_TV_EXTENDER); 9415 if (bundle != null) { 9416 mFlags = bundle.getInt(EXTRA_FLAGS); 9417 mChannelId = bundle.getString(EXTRA_CHANNEL_ID); 9418 mSuppressShowOverApps = bundle.getBoolean(EXTRA_SUPPRESS_SHOW_OVER_APPS); 9419 mContentIntent = bundle.getParcelable(EXTRA_CONTENT_INTENT); 9420 mDeleteIntent = bundle.getParcelable(EXTRA_DELETE_INTENT); 9421 } 9422 } 9423 9424 /** 9425 * Apply a TV extension to a notification that is being built. This is typically called by 9426 * the {@link Notification.Builder#extend(Notification.Extender)} 9427 * method of {@link Notification.Builder}. 9428 */ 9429 @Override 9430 public Notification.Builder extend(Notification.Builder builder) { 9431 Bundle bundle = new Bundle(); 9432 9433 bundle.putInt(EXTRA_FLAGS, mFlags); 9434 bundle.putString(EXTRA_CHANNEL_ID, mChannelId); 9435 bundle.putBoolean(EXTRA_SUPPRESS_SHOW_OVER_APPS, mSuppressShowOverApps); 9436 if (mContentIntent != null) { 9437 bundle.putParcelable(EXTRA_CONTENT_INTENT, mContentIntent); 9438 } 9439 9440 if (mDeleteIntent != null) { 9441 bundle.putParcelable(EXTRA_DELETE_INTENT, mDeleteIntent); 9442 } 9443 9444 builder.getExtras().putBundle(EXTRA_TV_EXTENDER, bundle); 9445 return builder; 9446 } 9447 9448 /** 9449 * Returns true if this notification should be shown on TV. This method return true 9450 * if the notification was extended with a TvExtender. 9451 */ 9452 public boolean isAvailableOnTv() { 9453 return (mFlags & FLAG_AVAILABLE_ON_TV) != 0; 9454 } 9455 9456 /** 9457 * Specifies the channel the notification should be delivered on when shown on TV. 9458 * It can be different from the channel that the notification is delivered to when 9459 * posting on a non-TV device. 9460 */ 9461 public TvExtender setChannel(String channelId) { 9462 mChannelId = channelId; 9463 return this; 9464 } 9465 9466 /** 9467 * Specifies the channel the notification should be delivered on when shown on TV. 9468 * It can be different from the channel that the notification is delivered to when 9469 * posting on a non-TV device. 9470 */ 9471 public TvExtender setChannelId(String channelId) { 9472 mChannelId = channelId; 9473 return this; 9474 } 9475 9476 /** @removed */ 9477 @Deprecated 9478 public String getChannel() { 9479 return mChannelId; 9480 } 9481 9482 /** 9483 * Returns the id of the channel this notification posts to on TV. 9484 */ 9485 public String getChannelId() { 9486 return mChannelId; 9487 } 9488 9489 /** 9490 * Supplies a {@link PendingIntent} to be sent when the notification is selected on TV. 9491 * If provided, it is used instead of the content intent specified 9492 * at the level of Notification. 9493 */ 9494 public TvExtender setContentIntent(PendingIntent intent) { 9495 mContentIntent = intent; 9496 return this; 9497 } 9498 9499 /** 9500 * Returns the TV-specific content intent. If this method returns null, the 9501 * main content intent on the notification should be used. 9502 * 9503 * @see {@link Notification#contentIntent} 9504 */ 9505 public PendingIntent getContentIntent() { 9506 return mContentIntent; 9507 } 9508 9509 /** 9510 * Supplies a {@link PendingIntent} to send when the notification is cleared explicitly 9511 * by the user on TV. If provided, it is used instead of the delete intent specified 9512 * at the level of Notification. 9513 */ 9514 public TvExtender setDeleteIntent(PendingIntent intent) { 9515 mDeleteIntent = intent; 9516 return this; 9517 } 9518 9519 /** 9520 * Returns the TV-specific delete intent. If this method returns null, the 9521 * main delete intent on the notification should be used. 9522 * 9523 * @see {@link Notification#deleteIntent} 9524 */ 9525 public PendingIntent getDeleteIntent() { 9526 return mDeleteIntent; 9527 } 9528 9529 /** 9530 * Specifies whether this notification should suppress showing a message over top of apps 9531 * outside of the launcher. 9532 */ 9533 public TvExtender setSuppressShowOverApps(boolean suppress) { 9534 mSuppressShowOverApps = suppress; 9535 return this; 9536 } 9537 9538 /** 9539 * Returns true if this notification should not show messages over top of apps 9540 * outside of the launcher. 9541 */ 9542 public boolean getSuppressShowOverApps() { 9543 return mSuppressShowOverApps; 9544 } 9545 } 9546 9547 /** 9548 * Get an array of Notification objects from a parcelable array bundle field. 9549 * Update the bundle to have a typed array so fetches in the future don't need 9550 * to do an array copy. 9551 */ 9552 private static Notification[] getNotificationArrayFromBundle(Bundle bundle, String key) { 9553 Parcelable[] array = bundle.getParcelableArray(key); 9554 if (array instanceof Notification[] || array == null) { 9555 return (Notification[]) array; 9556 } 9557 Notification[] typedArray = Arrays.copyOf(array, array.length, 9558 Notification[].class); 9559 bundle.putParcelableArray(key, typedArray); 9560 return typedArray; 9561 } 9562 9563 private static class BuilderRemoteViews extends RemoteViews { 9564 public BuilderRemoteViews(Parcel parcel) { 9565 super(parcel); 9566 } 9567 9568 public BuilderRemoteViews(ApplicationInfo appInfo, int layoutId) { 9569 super(appInfo, layoutId); 9570 } 9571 9572 @Override 9573 public BuilderRemoteViews clone() { 9574 Parcel p = Parcel.obtain(); 9575 writeToParcel(p, 0); 9576 p.setDataPosition(0); 9577 BuilderRemoteViews brv = new BuilderRemoteViews(p); 9578 p.recycle(); 9579 return brv; 9580 } 9581 } 9582 9583 /** 9584 * A result object where information about the template that was created is saved. 9585 */ 9586 private static class TemplateBindResult { 9587 int mIconMarginEnd; 9588 9589 /** 9590 * Get the margin end that needs to be added to any fields that may overlap 9591 * with the right actions. 9592 */ 9593 public int getIconMarginEnd() { 9594 return mIconMarginEnd; 9595 } 9596 9597 public void setIconMarginEnd(int iconMarginEnd) { 9598 this.mIconMarginEnd = iconMarginEnd; 9599 } 9600 } 9601 9602 private static class StandardTemplateParams { 9603 boolean hasProgress = true; 9604 boolean ambient = false; 9605 CharSequence title; 9606 CharSequence text; 9607 CharSequence headerTextSecondary; 9608 boolean hideLargeIcon; 9609 boolean hideReplyIcon; 9610 9611 final StandardTemplateParams reset() { 9612 hasProgress = true; 9613 ambient = false; 9614 title = null; 9615 text = null; 9616 headerTextSecondary = null; 9617 return this; 9618 } 9619 9620 final StandardTemplateParams hasProgress(boolean hasProgress) { 9621 this.hasProgress = hasProgress; 9622 return this; 9623 } 9624 9625 final StandardTemplateParams title(CharSequence title) { 9626 this.title = title; 9627 return this; 9628 } 9629 9630 final StandardTemplateParams text(CharSequence text) { 9631 this.text = text; 9632 return this; 9633 } 9634 9635 final StandardTemplateParams headerTextSecondary(CharSequence text) { 9636 this.headerTextSecondary = text; 9637 return this; 9638 } 9639 9640 final StandardTemplateParams hideLargeIcon(boolean hideLargeIcon) { 9641 this.hideLargeIcon = hideLargeIcon; 9642 return this; 9643 } 9644 9645 final StandardTemplateParams hideReplyIcon(boolean hideReplyIcon) { 9646 this.hideReplyIcon = hideReplyIcon; 9647 return this; 9648 } 9649 9650 final StandardTemplateParams ambient(boolean ambient) { 9651 Preconditions.checkState(title == null && text == null, "must set ambient before text"); 9652 this.ambient = ambient; 9653 return this; 9654 } 9655 9656 final StandardTemplateParams fillTextsFrom(Builder b) { 9657 Bundle extras = b.mN.extras; 9658 this.title = b.processLegacyText(extras.getCharSequence(EXTRA_TITLE), ambient); 9659 9660 // Big text notifications should contain their content when viewed in ambient mode. 9661 CharSequence text = extras.getCharSequence(EXTRA_BIG_TEXT); 9662 if (!ambient || TextUtils.isEmpty(text)) { 9663 text = extras.getCharSequence(EXTRA_TEXT); 9664 } 9665 this.text = b.processLegacyText(text, ambient); 9666 return this; 9667 } 9668 } 9669} 9670