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