Notification.java revision 23b3118f288d2beff0519ca294baac8093995989
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 #mCachedContrastColorIsFor}. 3146 */ 3147 private int mCachedAmbientColor = COLOR_INVALID; 3148 private int mCachedAmbientColorIsFor = COLOR_INVALID; 3149 3150 /** 3151 * Caches an instance of StandardTemplateParams. Note that this may have been used before, 3152 * so make sure to call {@link StandardTemplateParams#reset()} before using it. 3153 */ 3154 StandardTemplateParams mParams = new StandardTemplateParams(); 3155 private int mTextColorsAreForBackground = COLOR_INVALID; 3156 private int mPrimaryTextColor = COLOR_INVALID; 3157 private int mSecondaryTextColor = COLOR_INVALID; 3158 private int mBackgroundColor = COLOR_INVALID; 3159 private int mForegroundColor = COLOR_INVALID; 3160 /** 3161 * A temporary location where actions are stored. If != null the view originally has action 3162 * but doesn't have any for this inflation. 3163 */ 3164 private ArrayList<Action> mOriginalActions; 3165 private boolean mRebuildStyledRemoteViews; 3166 3167 private boolean mTintActionButtons; 3168 private boolean mInNightMode; 3169 3170 /** 3171 * Constructs a new Builder with the defaults: 3172 * 3173 * @param context 3174 * A {@link Context} that will be used by the Builder to construct the 3175 * RemoteViews. The Context will not be held past the lifetime of this Builder 3176 * object. 3177 * @param channelId 3178 * The constructed Notification will be posted on this 3179 * {@link NotificationChannel}. To use a NotificationChannel, it must first be 3180 * created using {@link NotificationManager#createNotificationChannel}. 3181 */ 3182 public Builder(Context context, String channelId) { 3183 this(context, (Notification) null); 3184 mN.mChannelId = channelId; 3185 } 3186 3187 /** 3188 * @deprecated use {@link Notification.Builder#Notification.Builder(Context, String)} 3189 * instead. All posted Notifications must specify a NotificationChannel Id. 3190 */ 3191 @Deprecated 3192 public Builder(Context context) { 3193 this(context, (Notification) null); 3194 } 3195 3196 /** 3197 * @hide 3198 */ 3199 public Builder(Context context, Notification toAdopt) { 3200 mContext = context; 3201 Resources res = mContext.getResources(); 3202 mTintActionButtons = res.getBoolean(R.bool.config_tintNotificationActionButtons); 3203 3204 if (res.getBoolean(R.bool.config_enableNightMode)) { 3205 Configuration currentConfig = res.getConfiguration(); 3206 mInNightMode = (currentConfig.uiMode & Configuration.UI_MODE_NIGHT_MASK) 3207 == Configuration.UI_MODE_NIGHT_YES; 3208 } 3209 3210 if (toAdopt == null) { 3211 mN = new Notification(); 3212 if (context.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N) { 3213 mN.extras.putBoolean(EXTRA_SHOW_WHEN, true); 3214 } 3215 mN.priority = PRIORITY_DEFAULT; 3216 mN.visibility = VISIBILITY_PRIVATE; 3217 } else { 3218 mN = toAdopt; 3219 if (mN.actions != null) { 3220 Collections.addAll(mActions, mN.actions); 3221 } 3222 3223 if (mN.extras.containsKey(EXTRA_PEOPLE_LIST)) { 3224 ArrayList<Person> people = mN.extras.getParcelableArrayList(EXTRA_PEOPLE_LIST); 3225 mPersonList.addAll(people); 3226 } 3227 3228 if (mN.getSmallIcon() == null && mN.icon != 0) { 3229 setSmallIcon(mN.icon); 3230 } 3231 3232 if (mN.getLargeIcon() == null && mN.largeIcon != null) { 3233 setLargeIcon(mN.largeIcon); 3234 } 3235 3236 String templateClass = mN.extras.getString(EXTRA_TEMPLATE); 3237 if (!TextUtils.isEmpty(templateClass)) { 3238 final Class<? extends Style> styleClass 3239 = getNotificationStyleClass(templateClass); 3240 if (styleClass == null) { 3241 Log.d(TAG, "Unknown style class: " + templateClass); 3242 } else { 3243 try { 3244 final Constructor<? extends Style> ctor = 3245 styleClass.getDeclaredConstructor(); 3246 ctor.setAccessible(true); 3247 final Style style = ctor.newInstance(); 3248 style.restoreFromExtras(mN.extras); 3249 3250 if (style != null) { 3251 setStyle(style); 3252 } 3253 } catch (Throwable t) { 3254 Log.e(TAG, "Could not create Style", t); 3255 } 3256 } 3257 } 3258 3259 } 3260 } 3261 3262 private NotificationColorUtil getColorUtil() { 3263 if (mColorUtil == null) { 3264 mColorUtil = NotificationColorUtil.getInstance(mContext); 3265 } 3266 return mColorUtil; 3267 } 3268 3269 /** 3270 * If this notification is duplicative of a Launcher shortcut, sets the 3271 * {@link ShortcutInfo#getId() id} of the shortcut, in case the Launcher wants to hide 3272 * the shortcut. 3273 * 3274 * This field will be ignored by Launchers that don't support badging, don't show 3275 * notification content, or don't show {@link android.content.pm.ShortcutManager shortcuts}. 3276 * 3277 * @param shortcutId the {@link ShortcutInfo#getId() id} of the shortcut this notification 3278 * supersedes 3279 */ 3280 public Builder setShortcutId(String shortcutId) { 3281 mN.mShortcutId = shortcutId; 3282 return this; 3283 } 3284 3285 /** 3286 * Sets which icon to display as a badge for this notification. 3287 * 3288 * Must be one of {@link #BADGE_ICON_NONE}, {@link #BADGE_ICON_SMALL}, 3289 * {@link #BADGE_ICON_LARGE}. 3290 * 3291 * Note: This value might be ignored, for launchers that don't support badge icons. 3292 */ 3293 public Builder setBadgeIconType(int icon) { 3294 mN.mBadgeIcon = icon; 3295 return this; 3296 } 3297 3298 /** 3299 * Sets the group alert behavior for this notification. Use this method to mute this 3300 * notification if alerts for this notification's group should be handled by a different 3301 * notification. This is only applicable for notifications that belong to a 3302 * {@link #setGroup(String) group}. This must be called on all notifications you want to 3303 * mute. For example, if you want only the summary of your group to make noise, all 3304 * children in the group should have the group alert behavior {@link #GROUP_ALERT_SUMMARY}. 3305 * 3306 * <p> The default value is {@link #GROUP_ALERT_ALL}.</p> 3307 */ 3308 public Builder setGroupAlertBehavior(@GroupAlertBehavior int groupAlertBehavior) { 3309 mN.mGroupAlertBehavior = groupAlertBehavior; 3310 return this; 3311 } 3312 3313 /** @removed */ 3314 @Deprecated 3315 public Builder setChannel(String channelId) { 3316 mN.mChannelId = channelId; 3317 return this; 3318 } 3319 3320 /** 3321 * Specifies the channel the notification should be delivered on. 3322 */ 3323 public Builder setChannelId(String channelId) { 3324 mN.mChannelId = channelId; 3325 return this; 3326 } 3327 3328 /** @removed */ 3329 @Deprecated 3330 public Builder setTimeout(long durationMs) { 3331 mN.mTimeout = durationMs; 3332 return this; 3333 } 3334 3335 /** 3336 * Specifies a duration in milliseconds after which this notification should be canceled, 3337 * if it is not already canceled. 3338 */ 3339 public Builder setTimeoutAfter(long durationMs) { 3340 mN.mTimeout = durationMs; 3341 return this; 3342 } 3343 3344 /** 3345 * Add a timestamp pertaining to the notification (usually the time the event occurred). 3346 * 3347 * For apps targeting {@link android.os.Build.VERSION_CODES#N} and above, this time is not 3348 * shown anymore by default and must be opted into by using 3349 * {@link android.app.Notification.Builder#setShowWhen(boolean)} 3350 * 3351 * @see Notification#when 3352 */ 3353 public Builder setWhen(long when) { 3354 mN.when = when; 3355 return this; 3356 } 3357 3358 /** 3359 * Control whether the timestamp set with {@link #setWhen(long) setWhen} is shown 3360 * in the content view. 3361 * For apps targeting {@link android.os.Build.VERSION_CODES#N} and above, this defaults to 3362 * {@code false}. For earlier apps, the default is {@code true}. 3363 */ 3364 public Builder setShowWhen(boolean show) { 3365 mN.extras.putBoolean(EXTRA_SHOW_WHEN, show); 3366 return this; 3367 } 3368 3369 /** 3370 * Show the {@link Notification#when} field as a stopwatch. 3371 * 3372 * Instead of presenting <code>when</code> as a timestamp, the notification will show an 3373 * automatically updating display of the minutes and seconds since <code>when</code>. 3374 * 3375 * Useful when showing an elapsed time (like an ongoing phone call). 3376 * 3377 * The counter can also be set to count down to <code>when</code> when using 3378 * {@link #setChronometerCountDown(boolean)}. 3379 * 3380 * @see android.widget.Chronometer 3381 * @see Notification#when 3382 * @see #setChronometerCountDown(boolean) 3383 */ 3384 public Builder setUsesChronometer(boolean b) { 3385 mN.extras.putBoolean(EXTRA_SHOW_CHRONOMETER, b); 3386 return this; 3387 } 3388 3389 /** 3390 * Sets the Chronometer to count down instead of counting up. 3391 * 3392 * <p>This is only relevant if {@link #setUsesChronometer(boolean)} has been set to true. 3393 * If it isn't set the chronometer will count up. 3394 * 3395 * @see #setUsesChronometer(boolean) 3396 */ 3397 public Builder setChronometerCountDown(boolean countDown) { 3398 mN.extras.putBoolean(EXTRA_CHRONOMETER_COUNT_DOWN, countDown); 3399 return this; 3400 } 3401 3402 /** 3403 * Set the small icon resource, which will be used to represent the notification in the 3404 * status bar. 3405 * 3406 3407 * The platform template for the expanded view will draw this icon in the left, unless a 3408 * {@link #setLargeIcon(Bitmap) large icon} has also been specified, in which case the small 3409 * icon will be moved to the right-hand side. 3410 * 3411 3412 * @param icon 3413 * A resource ID in the application's package of the drawable to use. 3414 * @see Notification#icon 3415 */ 3416 public Builder setSmallIcon(@DrawableRes int icon) { 3417 return setSmallIcon(icon != 0 3418 ? Icon.createWithResource(mContext, icon) 3419 : null); 3420 } 3421 3422 /** 3423 * A variant of {@link #setSmallIcon(int) setSmallIcon(int)} that takes an additional 3424 * level parameter for when the icon is a {@link android.graphics.drawable.LevelListDrawable 3425 * LevelListDrawable}. 3426 * 3427 * @param icon A resource ID in the application's package of the drawable to use. 3428 * @param level The level to use for the icon. 3429 * 3430 * @see Notification#icon 3431 * @see Notification#iconLevel 3432 */ 3433 public Builder setSmallIcon(@DrawableRes int icon, int level) { 3434 mN.iconLevel = level; 3435 return setSmallIcon(icon); 3436 } 3437 3438 /** 3439 * Set the small icon, which will be used to represent the notification in the 3440 * status bar and content view (unless overriden there by a 3441 * {@link #setLargeIcon(Bitmap) large icon}). 3442 * 3443 * @param icon An Icon object to use. 3444 * @see Notification#icon 3445 */ 3446 public Builder setSmallIcon(Icon icon) { 3447 mN.setSmallIcon(icon); 3448 if (icon != null && icon.getType() == Icon.TYPE_RESOURCE) { 3449 mN.icon = icon.getResId(); 3450 } 3451 return this; 3452 } 3453 3454 /** 3455 * Set the first line of text in the platform notification template. 3456 */ 3457 public Builder setContentTitle(CharSequence title) { 3458 mN.extras.putCharSequence(EXTRA_TITLE, safeCharSequence(title)); 3459 return this; 3460 } 3461 3462 /** 3463 * Set the second line of text in the platform notification template. 3464 */ 3465 public Builder setContentText(CharSequence text) { 3466 mN.extras.putCharSequence(EXTRA_TEXT, safeCharSequence(text)); 3467 return this; 3468 } 3469 3470 /** 3471 * This provides some additional information that is displayed in the notification. No 3472 * guarantees are given where exactly it is displayed. 3473 * 3474 * <p>This information should only be provided if it provides an essential 3475 * benefit to the understanding of the notification. The more text you provide the 3476 * less readable it becomes. For example, an email client should only provide the account 3477 * name here if more than one email account has been added.</p> 3478 * 3479 * <p>As of {@link android.os.Build.VERSION_CODES#N} this information is displayed in the 3480 * notification header area. 3481 * 3482 * On Android versions before {@link android.os.Build.VERSION_CODES#N} 3483 * this will be shown in the third line of text in the platform notification template. 3484 * You should not be using {@link #setProgress(int, int, boolean)} at the 3485 * same time on those versions; they occupy the same place. 3486 * </p> 3487 */ 3488 public Builder setSubText(CharSequence text) { 3489 mN.extras.putCharSequence(EXTRA_SUB_TEXT, safeCharSequence(text)); 3490 return this; 3491 } 3492 3493 /** 3494 * Provides text that will appear as a link to your application's settings. 3495 * 3496 * <p>This text does not appear within notification {@link Style templates} but may 3497 * appear when the user uses an affordance to learn more about the notification. 3498 * Additionally, this text will not appear unless you provide a valid link target by 3499 * handling {@link #INTENT_CATEGORY_NOTIFICATION_PREFERENCES}. 3500 * 3501 * <p>This text is meant to be concise description about what the user can customize 3502 * when they click on this link. The recommended maximum length is 40 characters. 3503 * @param text 3504 * @return 3505 */ 3506 public Builder setSettingsText(CharSequence text) { 3507 mN.mSettingsText = safeCharSequence(text); 3508 return this; 3509 } 3510 3511 /** 3512 * Set the remote input history. 3513 * 3514 * This should be set to the most recent inputs that have been sent 3515 * through a {@link RemoteInput} of this Notification and cleared once the it is no 3516 * longer relevant (e.g. for chat notifications once the other party has responded). 3517 * 3518 * The most recent input must be stored at the 0 index, the second most recent at the 3519 * 1 index, etc. Note that the system will limit both how far back the inputs will be shown 3520 * and how much of each individual input is shown. 3521 * 3522 * <p>Note: The reply text will only be shown on notifications that have least one action 3523 * with a {@code RemoteInput}.</p> 3524 */ 3525 public Builder setRemoteInputHistory(CharSequence[] text) { 3526 if (text == null) { 3527 mN.extras.putCharSequenceArray(EXTRA_REMOTE_INPUT_HISTORY, null); 3528 } else { 3529 final int N = Math.min(MAX_REPLY_HISTORY, text.length); 3530 CharSequence[] safe = new CharSequence[N]; 3531 for (int i = 0; i < N; i++) { 3532 safe[i] = safeCharSequence(text[i]); 3533 } 3534 mN.extras.putCharSequenceArray(EXTRA_REMOTE_INPUT_HISTORY, safe); 3535 } 3536 return this; 3537 } 3538 3539 /** 3540 * Sets the number of items this notification represents. May be displayed as a badge count 3541 * for Launchers that support badging. 3542 */ 3543 public Builder setNumber(int number) { 3544 mN.number = number; 3545 return this; 3546 } 3547 3548 /** 3549 * A small piece of additional information pertaining to this notification. 3550 * 3551 * The platform template will draw this on the last line of the notification, at the far 3552 * right (to the right of a smallIcon if it has been placed there). 3553 * 3554 * @deprecated use {@link #setSubText(CharSequence)} instead to set a text in the header. 3555 * For legacy apps targeting a version below {@link android.os.Build.VERSION_CODES#N} this 3556 * field will still show up, but the subtext will take precedence. 3557 */ 3558 @Deprecated 3559 public Builder setContentInfo(CharSequence info) { 3560 mN.extras.putCharSequence(EXTRA_INFO_TEXT, safeCharSequence(info)); 3561 return this; 3562 } 3563 3564 /** 3565 * Set the progress this notification represents. 3566 * 3567 * The platform template will represent this using a {@link ProgressBar}. 3568 */ 3569 public Builder setProgress(int max, int progress, boolean indeterminate) { 3570 mN.extras.putInt(EXTRA_PROGRESS, progress); 3571 mN.extras.putInt(EXTRA_PROGRESS_MAX, max); 3572 mN.extras.putBoolean(EXTRA_PROGRESS_INDETERMINATE, indeterminate); 3573 return this; 3574 } 3575 3576 /** 3577 * Supply a custom RemoteViews to use instead of the platform template. 3578 * 3579 * Use {@link #setCustomContentView(RemoteViews)} instead. 3580 */ 3581 @Deprecated 3582 public Builder setContent(RemoteViews views) { 3583 return setCustomContentView(views); 3584 } 3585 3586 /** 3587 * Supply custom RemoteViews to use instead of the platform template. 3588 * 3589 * This will override the layout that would otherwise be constructed by this Builder 3590 * object. 3591 */ 3592 public Builder setCustomContentView(RemoteViews contentView) { 3593 mN.contentView = contentView; 3594 return this; 3595 } 3596 3597 /** 3598 * Supply custom RemoteViews to use instead of the platform template in the expanded form. 3599 * 3600 * This will override the expanded layout that would otherwise be constructed by this 3601 * Builder object. 3602 */ 3603 public Builder setCustomBigContentView(RemoteViews contentView) { 3604 mN.bigContentView = contentView; 3605 return this; 3606 } 3607 3608 /** 3609 * Supply custom RemoteViews to use instead of the platform template in the heads up dialog. 3610 * 3611 * This will override the heads-up layout that would otherwise be constructed by this 3612 * Builder object. 3613 */ 3614 public Builder setCustomHeadsUpContentView(RemoteViews contentView) { 3615 mN.headsUpContentView = contentView; 3616 return this; 3617 } 3618 3619 /** 3620 * Supply a {@link PendingIntent} to be sent when the notification is clicked. 3621 * 3622 * As of {@link android.os.Build.VERSION_CODES#HONEYCOMB}, if this field is unset and you 3623 * have specified a custom RemoteViews with {@link #setContent(RemoteViews)}, you can use 3624 * {@link RemoteViews#setOnClickPendingIntent RemoteViews.setOnClickPendingIntent(int,PendingIntent)} 3625 * to assign PendingIntents to individual views in that custom layout (i.e., to create 3626 * clickable buttons inside the notification view). 3627 * 3628 * @see Notification#contentIntent Notification.contentIntent 3629 */ 3630 public Builder setContentIntent(PendingIntent intent) { 3631 mN.contentIntent = intent; 3632 return this; 3633 } 3634 3635 /** 3636 * Supply a {@link PendingIntent} to send when the notification is cleared explicitly by the user. 3637 * 3638 * @see Notification#deleteIntent 3639 */ 3640 public Builder setDeleteIntent(PendingIntent intent) { 3641 mN.deleteIntent = intent; 3642 return this; 3643 } 3644 3645 /** 3646 * An intent to launch instead of posting the notification to the status bar. 3647 * Only for use with extremely high-priority notifications demanding the user's 3648 * <strong>immediate</strong> attention, such as an incoming phone call or 3649 * alarm clock that the user has explicitly set to a particular time. 3650 * If this facility is used for something else, please give the user an option 3651 * to turn it off and use a normal notification, as this can be extremely 3652 * disruptive. 3653 * 3654 * <p> 3655 * The system UI may choose to display a heads-up notification, instead of 3656 * launching this intent, while the user is using the device. 3657 * </p> 3658 * 3659 * @param intent The pending intent to launch. 3660 * @param highPriority Passing true will cause this notification to be sent 3661 * even if other notifications are suppressed. 3662 * 3663 * @see Notification#fullScreenIntent 3664 */ 3665 public Builder setFullScreenIntent(PendingIntent intent, boolean highPriority) { 3666 mN.fullScreenIntent = intent; 3667 setFlag(FLAG_HIGH_PRIORITY, highPriority); 3668 return this; 3669 } 3670 3671 /** 3672 * Set the "ticker" text which is sent to accessibility services. 3673 * 3674 * @see Notification#tickerText 3675 */ 3676 public Builder setTicker(CharSequence tickerText) { 3677 mN.tickerText = safeCharSequence(tickerText); 3678 return this; 3679 } 3680 3681 /** 3682 * Obsolete version of {@link #setTicker(CharSequence)}. 3683 * 3684 */ 3685 @Deprecated 3686 public Builder setTicker(CharSequence tickerText, RemoteViews views) { 3687 setTicker(tickerText); 3688 // views is ignored 3689 return this; 3690 } 3691 3692 /** 3693 * Add a large icon to the notification content view. 3694 * 3695 * In the platform template, this image will be shown on the left of the notification view 3696 * in place of the {@link #setSmallIcon(Icon) small icon} (which will be placed in a small 3697 * badge atop the large icon). 3698 */ 3699 public Builder setLargeIcon(Bitmap b) { 3700 return setLargeIcon(b != null ? Icon.createWithBitmap(b) : null); 3701 } 3702 3703 /** 3704 * Add a large icon to the notification content view. 3705 * 3706 * In the platform template, this image will be shown on the left of the notification view 3707 * in place of the {@link #setSmallIcon(Icon) small icon} (which will be placed in a small 3708 * badge atop the large icon). 3709 */ 3710 public Builder setLargeIcon(Icon icon) { 3711 mN.mLargeIcon = icon; 3712 mN.extras.putParcelable(EXTRA_LARGE_ICON, icon); 3713 return this; 3714 } 3715 3716 /** 3717 * Set the sound to play. 3718 * 3719 * It will be played using the {@link #AUDIO_ATTRIBUTES_DEFAULT default audio attributes} 3720 * for notifications. 3721 * 3722 * @deprecated use {@link NotificationChannel#setSound(Uri, AudioAttributes)} instead. 3723 */ 3724 @Deprecated 3725 public Builder setSound(Uri sound) { 3726 mN.sound = sound; 3727 mN.audioAttributes = AUDIO_ATTRIBUTES_DEFAULT; 3728 return this; 3729 } 3730 3731 /** 3732 * Set the sound to play, along with a specific stream on which to play it. 3733 * 3734 * See {@link android.media.AudioManager} for the <code>STREAM_</code> constants. 3735 * 3736 * @deprecated use {@link NotificationChannel#setSound(Uri, AudioAttributes)}. 3737 */ 3738 @Deprecated 3739 public Builder setSound(Uri sound, int streamType) { 3740 PlayerBase.deprecateStreamTypeForPlayback(streamType, "Notification", "setSound()"); 3741 mN.sound = sound; 3742 mN.audioStreamType = streamType; 3743 return this; 3744 } 3745 3746 /** 3747 * Set the sound to play, along with specific {@link AudioAttributes audio attributes} to 3748 * use during playback. 3749 * 3750 * @deprecated use {@link NotificationChannel#setSound(Uri, AudioAttributes)} instead. 3751 * @see Notification#sound 3752 */ 3753 @Deprecated 3754 public Builder setSound(Uri sound, AudioAttributes audioAttributes) { 3755 mN.sound = sound; 3756 mN.audioAttributes = audioAttributes; 3757 return this; 3758 } 3759 3760 /** 3761 * Set the vibration pattern to use. 3762 * 3763 * See {@link android.os.Vibrator#vibrate(long[], int)} for a discussion of the 3764 * <code>pattern</code> parameter. 3765 * 3766 * <p> 3767 * A notification that vibrates is more likely to be presented as a heads-up notification. 3768 * </p> 3769 * 3770 * @deprecated use {@link NotificationChannel#setVibrationPattern(long[])} instead. 3771 * @see Notification#vibrate 3772 */ 3773 @Deprecated 3774 public Builder setVibrate(long[] pattern) { 3775 mN.vibrate = pattern; 3776 return this; 3777 } 3778 3779 /** 3780 * Set the desired color for the indicator LED on the device, as well as the 3781 * blink duty cycle (specified in milliseconds). 3782 * 3783 3784 * Not all devices will honor all (or even any) of these values. 3785 * 3786 * @deprecated use {@link NotificationChannel#enableLights(boolean)} instead. 3787 * @see Notification#ledARGB 3788 * @see Notification#ledOnMS 3789 * @see Notification#ledOffMS 3790 */ 3791 @Deprecated 3792 public Builder setLights(@ColorInt int argb, int onMs, int offMs) { 3793 mN.ledARGB = argb; 3794 mN.ledOnMS = onMs; 3795 mN.ledOffMS = offMs; 3796 if (onMs != 0 || offMs != 0) { 3797 mN.flags |= FLAG_SHOW_LIGHTS; 3798 } 3799 return this; 3800 } 3801 3802 /** 3803 * Set whether this is an "ongoing" notification. 3804 * 3805 3806 * Ongoing notifications cannot be dismissed by the user, so your application or service 3807 * must take care of canceling them. 3808 * 3809 3810 * They are typically used to indicate a background task that the user is actively engaged 3811 * with (e.g., playing music) or is pending in some way and therefore occupying the device 3812 * (e.g., a file download, sync operation, active network connection). 3813 * 3814 3815 * @see Notification#FLAG_ONGOING_EVENT 3816 * @see Service#setForeground(boolean) 3817 */ 3818 public Builder setOngoing(boolean ongoing) { 3819 setFlag(FLAG_ONGOING_EVENT, ongoing); 3820 return this; 3821 } 3822 3823 /** 3824 * Set whether this notification should be colorized. When set, the color set with 3825 * {@link #setColor(int)} will be used as the background color of this notification. 3826 * <p> 3827 * This should only be used for high priority ongoing tasks like navigation, an ongoing 3828 * call, or other similarly high-priority events for the user. 3829 * <p> 3830 * For most styles, the coloring will only be applied if the notification is for a 3831 * foreground service notification. 3832 * However, for {@link MediaStyle} and {@link DecoratedMediaCustomViewStyle} notifications 3833 * that have a media session attached there is no such requirement. 3834 * 3835 * @see Builder#setColor(int) 3836 * @see MediaStyle#setMediaSession(MediaSession.Token) 3837 */ 3838 public Builder setColorized(boolean colorize) { 3839 mN.extras.putBoolean(EXTRA_COLORIZED, colorize); 3840 return this; 3841 } 3842 3843 /** 3844 * Set this flag if you would only like the sound, vibrate 3845 * and ticker to be played if the notification is not already showing. 3846 * 3847 * @see Notification#FLAG_ONLY_ALERT_ONCE 3848 */ 3849 public Builder setOnlyAlertOnce(boolean onlyAlertOnce) { 3850 setFlag(FLAG_ONLY_ALERT_ONCE, onlyAlertOnce); 3851 return this; 3852 } 3853 3854 /** 3855 * Make this notification automatically dismissed when the user touches it. 3856 * 3857 * @see Notification#FLAG_AUTO_CANCEL 3858 */ 3859 public Builder setAutoCancel(boolean autoCancel) { 3860 setFlag(FLAG_AUTO_CANCEL, autoCancel); 3861 return this; 3862 } 3863 3864 /** 3865 * Set whether or not this notification should not bridge to other devices. 3866 * 3867 * <p>Some notifications can be bridged to other devices for remote display. 3868 * This hint can be set to recommend this notification not be bridged. 3869 */ 3870 public Builder setLocalOnly(boolean localOnly) { 3871 setFlag(FLAG_LOCAL_ONLY, localOnly); 3872 return this; 3873 } 3874 3875 /** 3876 * Set which notification properties will be inherited from system defaults. 3877 * <p> 3878 * The value should be one or more of the following fields combined with 3879 * bitwise-or: 3880 * {@link #DEFAULT_SOUND}, {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}. 3881 * <p> 3882 * For all default values, use {@link #DEFAULT_ALL}. 3883 * 3884 * @deprecated use {@link NotificationChannel#enableVibration(boolean)} and 3885 * {@link NotificationChannel#enableLights(boolean)} and 3886 * {@link NotificationChannel#setSound(Uri, AudioAttributes)} instead. 3887 */ 3888 @Deprecated 3889 public Builder setDefaults(int defaults) { 3890 mN.defaults = defaults; 3891 return this; 3892 } 3893 3894 /** 3895 * Set the priority of this notification. 3896 * 3897 * @see Notification#priority 3898 * @deprecated use {@link NotificationChannel#setImportance(int)} instead. 3899 */ 3900 @Deprecated 3901 public Builder setPriority(@Priority int pri) { 3902 mN.priority = pri; 3903 return this; 3904 } 3905 3906 /** 3907 * Set the notification category. 3908 * 3909 * @see Notification#category 3910 */ 3911 public Builder setCategory(String category) { 3912 mN.category = category; 3913 return this; 3914 } 3915 3916 /** 3917 * Add a person that is relevant to this notification. 3918 * 3919 * <P> 3920 * Depending on user preferences, this annotation may allow the notification to pass 3921 * through interruption filters, if this notification is of category {@link #CATEGORY_CALL} 3922 * or {@link #CATEGORY_MESSAGE}. The addition of people may also cause this notification to 3923 * appear more prominently in the user interface. 3924 * </P> 3925 * 3926 * <P> 3927 * The person should be specified by the {@code String} representation of a 3928 * {@link android.provider.ContactsContract.Contacts#CONTENT_LOOKUP_URI}. 3929 * </P> 3930 * 3931 * <P>The system will also attempt to resolve {@code mailto:} and {@code tel:} schema 3932 * URIs. The path part of these URIs must exist in the contacts database, in the 3933 * appropriate column, or the reference will be discarded as invalid. Telephone schema 3934 * URIs will be resolved by {@link android.provider.ContactsContract.PhoneLookup}. 3935 * It is also possible to provide a URI with the schema {@code name:} in order to uniquely 3936 * identify a person without an entry in the contacts database. 3937 * </P> 3938 * 3939 * @param uri A URI for the person. 3940 * @see Notification#EXTRA_PEOPLE 3941 * @deprecated use {@link #addPerson(Person)} 3942 */ 3943 public Builder addPerson(String uri) { 3944 addPerson(new Person.Builder().setUri(uri).build()); 3945 return this; 3946 } 3947 3948 /** 3949 * Add a person that is relevant to this notification. 3950 * 3951 * <P> 3952 * Depending on user preferences, this annotation may allow the notification to pass 3953 * through interruption filters, if this notification is of category {@link #CATEGORY_CALL} 3954 * or {@link #CATEGORY_MESSAGE}. The addition of people may also cause this notification to 3955 * appear more prominently in the user interface. 3956 * </P> 3957 * 3958 * <P> 3959 * A person should usually contain a uri in order to benefit from the ranking boost. 3960 * However, even if no uri is provided, it's beneficial to provide other people in the 3961 * notification, such that listeners and voice only devices can announce and handle them 3962 * properly. 3963 * </P> 3964 * 3965 * @param person the person to add. 3966 * @see Notification#EXTRA_PEOPLE_LIST 3967 */ 3968 public Builder addPerson(Person person) { 3969 mPersonList.add(person); 3970 return this; 3971 } 3972 3973 /** 3974 * Set this notification to be part of a group of notifications sharing the same key. 3975 * Grouped notifications may display in a cluster or stack on devices which 3976 * support such rendering. 3977 * 3978 * <p>To make this notification the summary for its group, also call 3979 * {@link #setGroupSummary}. A sort order can be specified for group members by using 3980 * {@link #setSortKey}. 3981 * @param groupKey The group key of the group. 3982 * @return this object for method chaining 3983 */ 3984 public Builder setGroup(String groupKey) { 3985 mN.mGroupKey = groupKey; 3986 return this; 3987 } 3988 3989 /** 3990 * Set this notification to be the group summary for a group of notifications. 3991 * Grouped notifications may display in a cluster or stack on devices which 3992 * support such rendering. If thereRequires a group key also be set using {@link #setGroup}. 3993 * The group summary may be suppressed if too few notifications are included in the group. 3994 * @param isGroupSummary Whether this notification should be a group summary. 3995 * @return this object for method chaining 3996 */ 3997 public Builder setGroupSummary(boolean isGroupSummary) { 3998 setFlag(FLAG_GROUP_SUMMARY, isGroupSummary); 3999 return this; 4000 } 4001 4002 /** 4003 * Set a sort key that orders this notification among other notifications from the 4004 * same package. This can be useful if an external sort was already applied and an app 4005 * would like to preserve this. Notifications will be sorted lexicographically using this 4006 * value, although providing different priorities in addition to providing sort key may 4007 * cause this value to be ignored. 4008 * 4009 * <p>This sort key can also be used to order members of a notification group. See 4010 * {@link #setGroup}. 4011 * 4012 * @see String#compareTo(String) 4013 */ 4014 public Builder setSortKey(String sortKey) { 4015 mN.mSortKey = sortKey; 4016 return this; 4017 } 4018 4019 /** 4020 * Merge additional metadata into this notification. 4021 * 4022 * <p>Values within the Bundle will replace existing extras values in this Builder. 4023 * 4024 * @see Notification#extras 4025 */ 4026 public Builder addExtras(Bundle extras) { 4027 if (extras != null) { 4028 mUserExtras.putAll(extras); 4029 } 4030 return this; 4031 } 4032 4033 /** 4034 * Set metadata for this notification. 4035 * 4036 * <p>A reference to the Bundle is held for the lifetime of this Builder, and the Bundle's 4037 * current contents are copied into the Notification each time {@link #build()} is 4038 * called. 4039 * 4040 * <p>Replaces any existing extras values with those from the provided Bundle. 4041 * Use {@link #addExtras} to merge in metadata instead. 4042 * 4043 * @see Notification#extras 4044 */ 4045 public Builder setExtras(Bundle extras) { 4046 if (extras != null) { 4047 mUserExtras = extras; 4048 } 4049 return this; 4050 } 4051 4052 /** 4053 * Get the current metadata Bundle used by this notification Builder. 4054 * 4055 * <p>The returned Bundle is shared with this Builder. 4056 * 4057 * <p>The current contents of this Bundle are copied into the Notification each time 4058 * {@link #build()} is called. 4059 * 4060 * @see Notification#extras 4061 */ 4062 public Bundle getExtras() { 4063 return mUserExtras; 4064 } 4065 4066 private Bundle getAllExtras() { 4067 final Bundle saveExtras = (Bundle) mUserExtras.clone(); 4068 saveExtras.putAll(mN.extras); 4069 return saveExtras; 4070 } 4071 4072 /** 4073 * Add an action to this notification. Actions are typically displayed by 4074 * the system as a button adjacent to the notification content. 4075 * <p> 4076 * Every action must have an icon (32dp square and matching the 4077 * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo 4078 * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}. 4079 * <p> 4080 * A notification in its expanded form can display up to 3 actions, from left to right in 4081 * the order they were added. Actions will not be displayed when the notification is 4082 * collapsed, however, so be sure that any essential functions may be accessed by the user 4083 * in some other way (for example, in the Activity pointed to by {@link #contentIntent}). 4084 * 4085 * @param icon Resource ID of a drawable that represents the action. 4086 * @param title Text describing the action. 4087 * @param intent PendingIntent to be fired when the action is invoked. 4088 * 4089 * @deprecated Use {@link #addAction(Action)} instead. 4090 */ 4091 @Deprecated 4092 public Builder addAction(int icon, CharSequence title, PendingIntent intent) { 4093 mActions.add(new Action(icon, safeCharSequence(title), intent)); 4094 return this; 4095 } 4096 4097 /** 4098 * Add an action to this notification. Actions are typically displayed by 4099 * the system as a button adjacent to the notification content. 4100 * <p> 4101 * Every action must have an icon (32dp square and matching the 4102 * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo 4103 * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}. 4104 * <p> 4105 * A notification in its expanded form can display up to 3 actions, from left to right in 4106 * the order they were added. Actions will not be displayed when the notification is 4107 * collapsed, however, so be sure that any essential functions may be accessed by the user 4108 * in some other way (for example, in the Activity pointed to by {@link #contentIntent}). 4109 * 4110 * @param action The action to add. 4111 */ 4112 public Builder addAction(Action action) { 4113 if (action != null) { 4114 mActions.add(action); 4115 } 4116 return this; 4117 } 4118 4119 /** 4120 * Alter the complete list of actions attached to this notification. 4121 * @see #addAction(Action). 4122 * 4123 * @param actions 4124 * @return 4125 */ 4126 public Builder setActions(Action... actions) { 4127 mActions.clear(); 4128 for (int i = 0; i < actions.length; i++) { 4129 if (actions[i] != null) { 4130 mActions.add(actions[i]); 4131 } 4132 } 4133 return this; 4134 } 4135 4136 /** 4137 * Add a rich notification style to be applied at build time. 4138 * 4139 * @param style Object responsible for modifying the notification style. 4140 */ 4141 public Builder setStyle(Style style) { 4142 if (mStyle != style) { 4143 mStyle = style; 4144 if (mStyle != null) { 4145 mStyle.setBuilder(this); 4146 mN.extras.putString(EXTRA_TEMPLATE, style.getClass().getName()); 4147 } else { 4148 mN.extras.remove(EXTRA_TEMPLATE); 4149 } 4150 } 4151 return this; 4152 } 4153 4154 /** 4155 * Returns the style set by {@link #setStyle(Style)}. 4156 */ 4157 public Style getStyle() { 4158 return mStyle; 4159 } 4160 4161 /** 4162 * Specify the value of {@link #visibility}. 4163 * 4164 * @return The same Builder. 4165 */ 4166 public Builder setVisibility(@Visibility int visibility) { 4167 mN.visibility = visibility; 4168 return this; 4169 } 4170 4171 /** 4172 * Supply a replacement Notification whose contents should be shown in insecure contexts 4173 * (i.e. atop the secure lockscreen). See {@link #visibility} and {@link #VISIBILITY_PUBLIC}. 4174 * @param n A replacement notification, presumably with some or all info redacted. 4175 * @return The same Builder. 4176 */ 4177 public Builder setPublicVersion(Notification n) { 4178 if (n != null) { 4179 mN.publicVersion = new Notification(); 4180 n.cloneInto(mN.publicVersion, /*heavy=*/ true); 4181 } else { 4182 mN.publicVersion = null; 4183 } 4184 return this; 4185 } 4186 4187 /** 4188 * Apply an extender to this notification builder. Extenders may be used to add 4189 * metadata or change options on this builder. 4190 */ 4191 public Builder extend(Extender extender) { 4192 extender.extend(this); 4193 return this; 4194 } 4195 4196 /** 4197 * @hide 4198 */ 4199 public Builder setFlag(int mask, boolean value) { 4200 if (value) { 4201 mN.flags |= mask; 4202 } else { 4203 mN.flags &= ~mask; 4204 } 4205 return this; 4206 } 4207 4208 /** 4209 * Sets {@link Notification#color}. 4210 * 4211 * @param argb The accent color to use 4212 * 4213 * @return The same Builder. 4214 */ 4215 public Builder setColor(@ColorInt int argb) { 4216 mN.color = argb; 4217 sanitizeColor(); 4218 return this; 4219 } 4220 4221 private Drawable getProfileBadgeDrawable() { 4222 if (mContext.getUserId() == UserHandle.USER_SYSTEM) { 4223 // This user can never be a badged profile, 4224 // and also includes USER_ALL system notifications. 4225 return null; 4226 } 4227 // Note: This assumes that the current user can read the profile badge of the 4228 // originating user. 4229 return mContext.getPackageManager().getUserBadgeForDensityNoBackground( 4230 new UserHandle(mContext.getUserId()), 0); 4231 } 4232 4233 private Bitmap getProfileBadge() { 4234 Drawable badge = getProfileBadgeDrawable(); 4235 if (badge == null) { 4236 return null; 4237 } 4238 final int size = mContext.getResources().getDimensionPixelSize( 4239 R.dimen.notification_badge_size); 4240 Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); 4241 Canvas canvas = new Canvas(bitmap); 4242 badge.setBounds(0, 0, size, size); 4243 badge.draw(canvas); 4244 return bitmap; 4245 } 4246 4247 private void bindProfileBadge(RemoteViews contentView) { 4248 Bitmap profileBadge = getProfileBadge(); 4249 4250 if (profileBadge != null) { 4251 contentView.setImageViewBitmap(R.id.profile_badge, profileBadge); 4252 contentView.setViewVisibility(R.id.profile_badge, View.VISIBLE); 4253 if (isColorized()) { 4254 contentView.setDrawableTint(R.id.profile_badge, false, 4255 getPrimaryTextColor(), PorterDuff.Mode.SRC_ATOP); 4256 } 4257 } 4258 } 4259 4260 /** 4261 * @hide 4262 */ 4263 public boolean usesStandardHeader() { 4264 if (mN.mUsesStandardHeader) { 4265 return true; 4266 } 4267 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.N) { 4268 if (mN.contentView == null && mN.bigContentView == null) { 4269 return true; 4270 } 4271 } 4272 boolean contentViewUsesHeader = mN.contentView == null 4273 || STANDARD_LAYOUTS.contains(mN.contentView.getLayoutId()); 4274 boolean bigContentViewUsesHeader = mN.bigContentView == null 4275 || STANDARD_LAYOUTS.contains(mN.bigContentView.getLayoutId()); 4276 return contentViewUsesHeader && bigContentViewUsesHeader; 4277 } 4278 4279 private void resetStandardTemplate(RemoteViews contentView) { 4280 resetNotificationHeader(contentView); 4281 resetContentMargins(contentView); 4282 contentView.setViewVisibility(R.id.right_icon, View.GONE); 4283 contentView.setViewVisibility(R.id.title, View.GONE); 4284 contentView.setTextViewText(R.id.title, null); 4285 contentView.setViewVisibility(R.id.text, View.GONE); 4286 contentView.setTextViewText(R.id.text, null); 4287 contentView.setViewVisibility(R.id.text_line_1, View.GONE); 4288 contentView.setTextViewText(R.id.text_line_1, null); 4289 } 4290 4291 /** 4292 * Resets the notification header to its original state 4293 */ 4294 private void resetNotificationHeader(RemoteViews contentView) { 4295 // Small icon doesn't need to be reset, as it's always set. Resetting would prevent 4296 // re-using the drawable when the notification is updated. 4297 contentView.setBoolean(R.id.notification_header, "setExpanded", false); 4298 contentView.setTextViewText(R.id.app_name_text, null); 4299 contentView.setViewVisibility(R.id.chronometer, View.GONE); 4300 contentView.setViewVisibility(R.id.header_text, View.GONE); 4301 contentView.setTextViewText(R.id.header_text, null); 4302 contentView.setViewVisibility(R.id.header_text_secondary, View.GONE); 4303 contentView.setTextViewText(R.id.header_text_secondary, null); 4304 contentView.setViewVisibility(R.id.header_text_divider, View.GONE); 4305 contentView.setViewVisibility(R.id.header_text_secondary_divider, View.GONE); 4306 contentView.setViewVisibility(R.id.time_divider, View.GONE); 4307 contentView.setViewVisibility(R.id.time, View.GONE); 4308 contentView.setImageViewIcon(R.id.profile_badge, null); 4309 contentView.setViewVisibility(R.id.profile_badge, View.GONE); 4310 mN.mUsesStandardHeader = false; 4311 } 4312 4313 private void resetContentMargins(RemoteViews contentView) { 4314 contentView.setViewLayoutMarginEndDimen(R.id.line1, 0); 4315 contentView.setViewLayoutMarginEndDimen(R.id.text, 0); 4316 } 4317 4318 private RemoteViews applyStandardTemplate(int resId) { 4319 return applyStandardTemplate(resId, mParams.reset().fillTextsFrom(this)); 4320 } 4321 4322 /** 4323 * @param hasProgress whether the progress bar should be shown and set 4324 */ 4325 private RemoteViews applyStandardTemplate(int resId, boolean hasProgress) { 4326 return applyStandardTemplate(resId, mParams.reset().hasProgress(hasProgress) 4327 .fillTextsFrom(this)); 4328 } 4329 4330 private RemoteViews applyStandardTemplate(int resId, StandardTemplateParams p) { 4331 RemoteViews contentView = new BuilderRemoteViews(mContext.getApplicationInfo(), resId); 4332 4333 resetStandardTemplate(contentView); 4334 4335 final Bundle ex = mN.extras; 4336 updateBackgroundColor(contentView); 4337 bindNotificationHeader(contentView, p.ambient, p.headerTextSecondary); 4338 bindLargeIcon(contentView, p.hideLargeIcon || p.ambient, p.alwaysShowReply); 4339 boolean showProgress = handleProgressBar(p.hasProgress, contentView, ex); 4340 if (p.title != null) { 4341 contentView.setViewVisibility(R.id.title, View.VISIBLE); 4342 contentView.setTextViewText(R.id.title, processTextSpans(p.title)); 4343 if (!p.ambient) { 4344 setTextViewColorPrimary(contentView, R.id.title); 4345 } 4346 contentView.setViewLayoutWidth(R.id.title, showProgress 4347 ? ViewGroup.LayoutParams.WRAP_CONTENT 4348 : ViewGroup.LayoutParams.MATCH_PARENT); 4349 } 4350 if (p.text != null) { 4351 int textId = showProgress ? com.android.internal.R.id.text_line_1 4352 : com.android.internal.R.id.text; 4353 contentView.setTextViewText(textId, processTextSpans(p.text)); 4354 if (!p.ambient) { 4355 setTextViewColorSecondary(contentView, textId); 4356 } 4357 contentView.setViewVisibility(textId, View.VISIBLE); 4358 } 4359 4360 setContentMinHeight(contentView, showProgress || mN.hasLargeIcon()); 4361 4362 return contentView; 4363 } 4364 4365 private CharSequence processTextSpans(CharSequence text) { 4366 if (hasForegroundColor()) { 4367 return NotificationColorUtil.clearColorSpans(text); 4368 } 4369 return text; 4370 } 4371 4372 private void setTextViewColorPrimary(RemoteViews contentView, int id) { 4373 ensureColors(); 4374 contentView.setTextColor(id, mPrimaryTextColor); 4375 } 4376 4377 private boolean hasForegroundColor() { 4378 return mForegroundColor != COLOR_INVALID; 4379 } 4380 4381 /** 4382 * @return the primary text color 4383 * @hide 4384 */ 4385 @VisibleForTesting 4386 public int getPrimaryTextColor() { 4387 ensureColors(); 4388 return mPrimaryTextColor; 4389 } 4390 4391 /** 4392 * @return the secondary text color 4393 * @hide 4394 */ 4395 @VisibleForTesting 4396 public int getSecondaryTextColor() { 4397 ensureColors(); 4398 return mSecondaryTextColor; 4399 } 4400 4401 private void setTextViewColorSecondary(RemoteViews contentView, int id) { 4402 ensureColors(); 4403 contentView.setTextColor(id, mSecondaryTextColor); 4404 } 4405 4406 private void ensureColors() { 4407 int backgroundColor = getBackgroundColor(); 4408 if (mPrimaryTextColor == COLOR_INVALID 4409 || mSecondaryTextColor == COLOR_INVALID 4410 || mTextColorsAreForBackground != backgroundColor) { 4411 mTextColorsAreForBackground = backgroundColor; 4412 if (!hasForegroundColor() || !isColorized()) { 4413 mPrimaryTextColor = NotificationColorUtil.resolvePrimaryColor(mContext, 4414 backgroundColor); 4415 mSecondaryTextColor = NotificationColorUtil.resolveSecondaryColor(mContext, 4416 backgroundColor); 4417 if (backgroundColor != COLOR_DEFAULT && isColorized()) { 4418 mPrimaryTextColor = NotificationColorUtil.findAlphaToMeetContrast( 4419 mPrimaryTextColor, backgroundColor, 4.5); 4420 mSecondaryTextColor = NotificationColorUtil.findAlphaToMeetContrast( 4421 mSecondaryTextColor, backgroundColor, 4.5); 4422 } 4423 } else { 4424 double backLum = NotificationColorUtil.calculateLuminance(backgroundColor); 4425 double textLum = NotificationColorUtil.calculateLuminance(mForegroundColor); 4426 double contrast = NotificationColorUtil.calculateContrast(mForegroundColor, 4427 backgroundColor); 4428 // We only respect the given colors if worst case Black or White still has 4429 // contrast 4430 boolean backgroundLight = backLum > textLum 4431 && satisfiesTextContrast(backgroundColor, Color.BLACK) 4432 || backLum <= textLum 4433 && !satisfiesTextContrast(backgroundColor, Color.WHITE); 4434 if (contrast < 4.5f) { 4435 if (backgroundLight) { 4436 mSecondaryTextColor = NotificationColorUtil.findContrastColor( 4437 mForegroundColor, 4438 backgroundColor, 4439 true /* findFG */, 4440 4.5f); 4441 mPrimaryTextColor = NotificationColorUtil.changeColorLightness( 4442 mSecondaryTextColor, -LIGHTNESS_TEXT_DIFFERENCE_LIGHT); 4443 } else { 4444 mSecondaryTextColor = 4445 NotificationColorUtil.findContrastColorAgainstDark( 4446 mForegroundColor, 4447 backgroundColor, 4448 true /* findFG */, 4449 4.5f); 4450 mPrimaryTextColor = NotificationColorUtil.changeColorLightness( 4451 mSecondaryTextColor, -LIGHTNESS_TEXT_DIFFERENCE_DARK); 4452 } 4453 } else { 4454 mPrimaryTextColor = mForegroundColor; 4455 mSecondaryTextColor = NotificationColorUtil.changeColorLightness( 4456 mPrimaryTextColor, backgroundLight ? LIGHTNESS_TEXT_DIFFERENCE_LIGHT 4457 : LIGHTNESS_TEXT_DIFFERENCE_DARK); 4458 if (NotificationColorUtil.calculateContrast(mSecondaryTextColor, 4459 backgroundColor) < 4.5f) { 4460 // oh well the secondary is not good enough 4461 if (backgroundLight) { 4462 mSecondaryTextColor = NotificationColorUtil.findContrastColor( 4463 mSecondaryTextColor, 4464 backgroundColor, 4465 true /* findFG */, 4466 4.5f); 4467 } else { 4468 mSecondaryTextColor 4469 = NotificationColorUtil.findContrastColorAgainstDark( 4470 mSecondaryTextColor, 4471 backgroundColor, 4472 true /* findFG */, 4473 4.5f); 4474 } 4475 mPrimaryTextColor = NotificationColorUtil.changeColorLightness( 4476 mSecondaryTextColor, backgroundLight 4477 ? -LIGHTNESS_TEXT_DIFFERENCE_LIGHT 4478 : -LIGHTNESS_TEXT_DIFFERENCE_DARK); 4479 } 4480 } 4481 } 4482 } 4483 } 4484 4485 private void updateBackgroundColor(RemoteViews contentView) { 4486 if (isColorized()) { 4487 contentView.setInt(R.id.status_bar_latest_event_content, "setBackgroundColor", 4488 getBackgroundColor()); 4489 } else { 4490 // Clear it! 4491 contentView.setInt(R.id.status_bar_latest_event_content, "setBackgroundResource", 4492 0); 4493 } 4494 } 4495 4496 /** 4497 * @param remoteView the remote view to update the minheight in 4498 * @param hasMinHeight does it have a mimHeight 4499 * @hide 4500 */ 4501 void setContentMinHeight(RemoteViews remoteView, boolean hasMinHeight) { 4502 int minHeight = 0; 4503 if (hasMinHeight) { 4504 // we need to set the minHeight of the notification 4505 minHeight = mContext.getResources().getDimensionPixelSize( 4506 com.android.internal.R.dimen.notification_min_content_height); 4507 } 4508 remoteView.setInt(R.id.notification_main_column, "setMinimumHeight", minHeight); 4509 } 4510 4511 private boolean handleProgressBar(boolean hasProgress, RemoteViews contentView, Bundle ex) { 4512 final int max = ex.getInt(EXTRA_PROGRESS_MAX, 0); 4513 final int progress = ex.getInt(EXTRA_PROGRESS, 0); 4514 final boolean ind = ex.getBoolean(EXTRA_PROGRESS_INDETERMINATE); 4515 if (hasProgress && (max != 0 || ind)) { 4516 contentView.setViewVisibility(com.android.internal.R.id.progress, View.VISIBLE); 4517 contentView.setProgressBar( 4518 R.id.progress, max, progress, ind); 4519 contentView.setProgressBackgroundTintList( 4520 R.id.progress, ColorStateList.valueOf(mContext.getColor( 4521 R.color.notification_progress_background_color))); 4522 if (mN.color != COLOR_DEFAULT) { 4523 ColorStateList colorStateList = ColorStateList.valueOf(resolveContrastColor()); 4524 contentView.setProgressTintList(R.id.progress, colorStateList); 4525 contentView.setProgressIndeterminateTintList(R.id.progress, colorStateList); 4526 } 4527 return true; 4528 } else { 4529 contentView.setViewVisibility(R.id.progress, View.GONE); 4530 return false; 4531 } 4532 } 4533 4534 private void bindLargeIcon(RemoteViews contentView, boolean hideLargeIcon, 4535 boolean alwaysShowReply) { 4536 if (mN.mLargeIcon == null && mN.largeIcon != null) { 4537 mN.mLargeIcon = Icon.createWithBitmap(mN.largeIcon); 4538 } 4539 boolean showLargeIcon = mN.mLargeIcon != null && !hideLargeIcon; 4540 if (showLargeIcon) { 4541 contentView.setViewVisibility(R.id.right_icon, View.VISIBLE); 4542 contentView.setImageViewIcon(R.id.right_icon, mN.mLargeIcon); 4543 processLargeLegacyIcon(mN.mLargeIcon, contentView); 4544 int endMargin = R.dimen.notification_content_picture_margin; 4545 contentView.setViewLayoutMarginEndDimen(R.id.line1, endMargin); 4546 contentView.setViewLayoutMarginEndDimen(R.id.text, endMargin); 4547 contentView.setViewLayoutMarginEndDimen(R.id.progress, endMargin); 4548 } 4549 // Bind the reply action 4550 Action action = findReplyAction(); 4551 4552 boolean actionVisible = action != null && (showLargeIcon || alwaysShowReply); 4553 int replyId = showLargeIcon ? R.id.reply_icon_action : R.id.right_icon; 4554 if (actionVisible) { 4555 // We're only showing the icon as big if we're hiding the large icon 4556 int contrastColor = resolveContrastColor(); 4557 int iconColor; 4558 if (showLargeIcon) { 4559 contentView.setDrawableTint(R.id.reply_icon_action, 4560 true /* targetBackground */, 4561 contrastColor, PorterDuff.Mode.SRC_ATOP); 4562 contentView.setOnClickPendingIntent(R.id.right_icon, 4563 action.actionIntent); 4564 contentView.setRemoteInputs(R.id.right_icon, action.mRemoteInputs); 4565 iconColor = NotificationColorUtil.isColorLight(contrastColor) 4566 ? Color.BLACK : Color.WHITE; 4567 } else { 4568 contentView.setImageViewResource(R.id.right_icon, 4569 R.drawable.ic_reply_notification_large); 4570 contentView.setViewVisibility(R.id.right_icon, View.VISIBLE); 4571 iconColor = contrastColor; 4572 } 4573 contentView.setDrawableTint(replyId, 4574 false /* targetBackground */, 4575 iconColor, 4576 PorterDuff.Mode.SRC_ATOP); 4577 contentView.setOnClickPendingIntent(replyId, 4578 action.actionIntent); 4579 contentView.setRemoteInputs(replyId, action.mRemoteInputs); 4580 } else { 4581 contentView.setRemoteInputs(R.id.right_icon, null); 4582 } 4583 contentView.setViewVisibility(R.id.reply_icon_action, actionVisible && showLargeIcon 4584 ? View.VISIBLE 4585 : View.GONE); 4586 contentView.setViewVisibility(R.id.right_icon_container, actionVisible || showLargeIcon 4587 ? View.VISIBLE 4588 : View.GONE); 4589 } 4590 4591 private Action findReplyAction() { 4592 ArrayList<Action> actions = mActions; 4593 if (mOriginalActions != null) { 4594 actions = mOriginalActions; 4595 } 4596 int numActions = actions.size(); 4597 for (int i = 0; i < numActions; i++) { 4598 Action action = actions.get(i); 4599 if (hasValidRemoteInput(action)) { 4600 return action; 4601 } 4602 } 4603 return null; 4604 } 4605 4606 private void bindNotificationHeader(RemoteViews contentView, boolean ambient, 4607 CharSequence secondaryHeaderText) { 4608 bindSmallIcon(contentView, ambient); 4609 bindHeaderAppName(contentView, ambient); 4610 if (!ambient) { 4611 // Ambient view does not have these 4612 bindHeaderText(contentView); 4613 bindHeaderTextSecondary(contentView, secondaryHeaderText); 4614 bindHeaderChronometerAndTime(contentView); 4615 bindProfileBadge(contentView); 4616 } 4617 bindActivePermissions(contentView, ambient); 4618 bindExpandButton(contentView); 4619 mN.mUsesStandardHeader = true; 4620 } 4621 4622 private void bindActivePermissions(RemoteViews contentView, boolean ambient) { 4623 int color = ambient ? resolveAmbientColor() 4624 : isColorized() ? getPrimaryTextColor() : resolveContrastColor(); 4625 contentView.setDrawableTint(R.id.camera, false, color, PorterDuff.Mode.SRC_ATOP); 4626 contentView.setDrawableTint(R.id.mic, false, color, PorterDuff.Mode.SRC_ATOP); 4627 contentView.setDrawableTint(R.id.overlay, false, color, PorterDuff.Mode.SRC_ATOP); 4628 } 4629 4630 private void bindExpandButton(RemoteViews contentView) { 4631 int color = isColorized() ? getPrimaryTextColor() : getSecondaryTextColor(); 4632 contentView.setDrawableTint(R.id.expand_button, false, color, 4633 PorterDuff.Mode.SRC_ATOP); 4634 contentView.setInt(R.id.notification_header, "setOriginalNotificationColor", 4635 color); 4636 } 4637 4638 private void bindHeaderChronometerAndTime(RemoteViews contentView) { 4639 if (showsTimeOrChronometer()) { 4640 contentView.setViewVisibility(R.id.time_divider, View.VISIBLE); 4641 setTextViewColorSecondary(contentView, R.id.time_divider); 4642 if (mN.extras.getBoolean(EXTRA_SHOW_CHRONOMETER)) { 4643 contentView.setViewVisibility(R.id.chronometer, View.VISIBLE); 4644 contentView.setLong(R.id.chronometer, "setBase", 4645 mN.when + (SystemClock.elapsedRealtime() - System.currentTimeMillis())); 4646 contentView.setBoolean(R.id.chronometer, "setStarted", true); 4647 boolean countsDown = mN.extras.getBoolean(EXTRA_CHRONOMETER_COUNT_DOWN); 4648 contentView.setChronometerCountDown(R.id.chronometer, countsDown); 4649 setTextViewColorSecondary(contentView, R.id.chronometer); 4650 } else { 4651 contentView.setViewVisibility(R.id.time, View.VISIBLE); 4652 contentView.setLong(R.id.time, "setTime", mN.when); 4653 setTextViewColorSecondary(contentView, R.id.time); 4654 } 4655 } else { 4656 // We still want a time to be set but gone, such that we can show and hide it 4657 // on demand in case it's a child notification without anything in the header 4658 contentView.setLong(R.id.time, "setTime", mN.when != 0 ? mN.when : mN.creationTime); 4659 } 4660 } 4661 4662 private void bindHeaderText(RemoteViews contentView) { 4663 CharSequence headerText = mN.extras.getCharSequence(EXTRA_SUB_TEXT); 4664 if (headerText == null && mStyle != null && mStyle.mSummaryTextSet 4665 && mStyle.hasSummaryInHeader()) { 4666 headerText = mStyle.mSummaryText; 4667 } 4668 if (headerText == null 4669 && mContext.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N 4670 && mN.extras.getCharSequence(EXTRA_INFO_TEXT) != null) { 4671 headerText = mN.extras.getCharSequence(EXTRA_INFO_TEXT); 4672 } 4673 if (headerText != null) { 4674 // TODO: Remove the span entirely to only have the string with propper formating. 4675 contentView.setTextViewText(R.id.header_text, processTextSpans( 4676 processLegacyText(headerText))); 4677 setTextViewColorSecondary(contentView, R.id.header_text); 4678 contentView.setViewVisibility(R.id.header_text, View.VISIBLE); 4679 contentView.setViewVisibility(R.id.header_text_divider, View.VISIBLE); 4680 setTextViewColorSecondary(contentView, R.id.header_text_divider); 4681 } 4682 } 4683 4684 private void bindHeaderTextSecondary(RemoteViews contentView, CharSequence secondaryText) { 4685 if (!TextUtils.isEmpty(secondaryText)) { 4686 contentView.setTextViewText(R.id.header_text_secondary, processTextSpans( 4687 processLegacyText(secondaryText))); 4688 setTextViewColorSecondary(contentView, R.id.header_text_secondary); 4689 contentView.setViewVisibility(R.id.header_text_secondary, View.VISIBLE); 4690 contentView.setViewVisibility(R.id.header_text_secondary_divider, View.VISIBLE); 4691 setTextViewColorSecondary(contentView, R.id.header_text_secondary_divider); 4692 } 4693 } 4694 4695 /** 4696 * @hide 4697 */ 4698 public String loadHeaderAppName() { 4699 CharSequence name = null; 4700 final PackageManager pm = mContext.getPackageManager(); 4701 if (mN.extras.containsKey(EXTRA_SUBSTITUTE_APP_NAME)) { 4702 // only system packages which lump together a bunch of unrelated stuff 4703 // may substitute a different name to make the purpose of the 4704 // notification more clear. the correct package label should always 4705 // be accessible via SystemUI. 4706 final String pkg = mContext.getPackageName(); 4707 final String subName = mN.extras.getString(EXTRA_SUBSTITUTE_APP_NAME); 4708 if (PackageManager.PERMISSION_GRANTED == pm.checkPermission( 4709 android.Manifest.permission.SUBSTITUTE_NOTIFICATION_APP_NAME, pkg)) { 4710 name = subName; 4711 } else { 4712 Log.w(TAG, "warning: pkg " 4713 + pkg + " attempting to substitute app name '" + subName 4714 + "' without holding perm " 4715 + android.Manifest.permission.SUBSTITUTE_NOTIFICATION_APP_NAME); 4716 } 4717 } 4718 if (TextUtils.isEmpty(name)) { 4719 name = pm.getApplicationLabel(mContext.getApplicationInfo()); 4720 } 4721 if (TextUtils.isEmpty(name)) { 4722 // still nothing? 4723 return null; 4724 } 4725 4726 return String.valueOf(name); 4727 } 4728 private void bindHeaderAppName(RemoteViews contentView, boolean ambient) { 4729 contentView.setTextViewText(R.id.app_name_text, loadHeaderAppName()); 4730 if (isColorized() && !ambient) { 4731 setTextViewColorPrimary(contentView, R.id.app_name_text); 4732 } else { 4733 contentView.setTextColor(R.id.app_name_text, 4734 ambient ? resolveAmbientColor() : getSecondaryTextColor()); 4735 } 4736 } 4737 4738 private void bindSmallIcon(RemoteViews contentView, boolean ambient) { 4739 if (mN.mSmallIcon == null && mN.icon != 0) { 4740 mN.mSmallIcon = Icon.createWithResource(mContext, mN.icon); 4741 } 4742 contentView.setImageViewIcon(R.id.icon, mN.mSmallIcon); 4743 contentView.setInt(R.id.icon, "setImageLevel", mN.iconLevel); 4744 processSmallIconColor(mN.mSmallIcon, contentView, ambient); 4745 } 4746 4747 /** 4748 * @return true if the built notification will show the time or the chronometer; false 4749 * otherwise 4750 */ 4751 private boolean showsTimeOrChronometer() { 4752 return mN.showsTime() || mN.showsChronometer(); 4753 } 4754 4755 private void resetStandardTemplateWithActions(RemoteViews big) { 4756 // actions_container is only reset when there are no actions to avoid focus issues with 4757 // remote inputs. 4758 big.setViewVisibility(R.id.actions, View.GONE); 4759 big.removeAllViews(R.id.actions); 4760 4761 big.setViewVisibility(R.id.notification_material_reply_container, View.GONE); 4762 big.setTextViewText(R.id.notification_material_reply_text_1, null); 4763 4764 big.setViewVisibility(R.id.notification_material_reply_text_2, View.GONE); 4765 big.setTextViewText(R.id.notification_material_reply_text_2, null); 4766 big.setViewVisibility(R.id.notification_material_reply_text_3, View.GONE); 4767 big.setTextViewText(R.id.notification_material_reply_text_3, null); 4768 4769 big.setViewLayoutMarginBottomDimen(R.id.notification_action_list_margin_target, 4770 R.dimen.notification_content_margin); 4771 } 4772 4773 private RemoteViews applyStandardTemplateWithActions(int layoutId) { 4774 return applyStandardTemplateWithActions(layoutId, mParams.reset().fillTextsFrom(this)); 4775 } 4776 4777 private RemoteViews applyStandardTemplateWithActions(int layoutId, 4778 StandardTemplateParams p) { 4779 RemoteViews big = applyStandardTemplate(layoutId, p); 4780 4781 resetStandardTemplateWithActions(big); 4782 4783 boolean validRemoteInput = false; 4784 4785 int N = mActions.size(); 4786 boolean emphazisedMode = mN.fullScreenIntent != null && !p.ambient; 4787 big.setBoolean(R.id.actions, "setEmphasizedMode", emphazisedMode); 4788 if (N > 0) { 4789 big.setViewVisibility(R.id.actions_container, View.VISIBLE); 4790 big.setViewVisibility(R.id.actions, View.VISIBLE); 4791 big.setViewLayoutMarginBottomDimen(R.id.notification_action_list_margin_target, 0); 4792 if (N>MAX_ACTION_BUTTONS) N=MAX_ACTION_BUTTONS; 4793 for (int i=0; i<N; i++) { 4794 Action action = mActions.get(i); 4795 boolean actionHasValidInput = hasValidRemoteInput(action); 4796 validRemoteInput |= actionHasValidInput; 4797 4798 final RemoteViews button = generateActionButton(action, emphazisedMode, 4799 p.ambient); 4800 if (actionHasValidInput && !emphazisedMode) { 4801 // Clear the drawable 4802 button.setInt(R.id.action0, "setBackgroundResource", 0); 4803 } 4804 big.addView(R.id.actions, button); 4805 } 4806 } else { 4807 big.setViewVisibility(R.id.actions_container, View.GONE); 4808 } 4809 4810 CharSequence[] replyText = mN.extras.getCharSequenceArray(EXTRA_REMOTE_INPUT_HISTORY); 4811 if (!p.ambient && validRemoteInput && replyText != null 4812 && replyText.length > 0 && !TextUtils.isEmpty(replyText[0])) { 4813 big.setViewVisibility(R.id.notification_material_reply_container, View.VISIBLE); 4814 big.setTextViewText(R.id.notification_material_reply_text_1, 4815 processTextSpans(replyText[0])); 4816 setTextViewColorSecondary(big, R.id.notification_material_reply_text_1); 4817 4818 if (replyText.length > 1 && !TextUtils.isEmpty(replyText[1])) { 4819 big.setViewVisibility(R.id.notification_material_reply_text_2, View.VISIBLE); 4820 big.setTextViewText(R.id.notification_material_reply_text_2, 4821 processTextSpans(replyText[1])); 4822 setTextViewColorSecondary(big, R.id.notification_material_reply_text_2); 4823 4824 if (replyText.length > 2 && !TextUtils.isEmpty(replyText[2])) { 4825 big.setViewVisibility( 4826 R.id.notification_material_reply_text_3, View.VISIBLE); 4827 big.setTextViewText(R.id.notification_material_reply_text_3, 4828 processTextSpans(replyText[2])); 4829 setTextViewColorSecondary(big, R.id.notification_material_reply_text_3); 4830 } 4831 } 4832 } 4833 4834 return big; 4835 } 4836 4837 private boolean hasValidRemoteInput(Action action) { 4838 if (TextUtils.isEmpty(action.title) || action.actionIntent == null) { 4839 // Weird actions 4840 return false; 4841 } 4842 4843 RemoteInput[] remoteInputs = action.getRemoteInputs(); 4844 if (remoteInputs == null) { 4845 return false; 4846 } 4847 4848 for (RemoteInput r : remoteInputs) { 4849 CharSequence[] choices = r.getChoices(); 4850 if (r.getAllowFreeFormInput() || (choices != null && choices.length != 0)) { 4851 return true; 4852 } 4853 } 4854 return false; 4855 } 4856 4857 /** 4858 * Construct a RemoteViews for the final 1U notification layout. In order: 4859 * 1. Custom contentView from the caller 4860 * 2. Style's proposed content view 4861 * 3. Standard template view 4862 */ 4863 public RemoteViews createContentView() { 4864 return createContentView(false /* increasedheight */ ); 4865 } 4866 4867 /** 4868 * Construct a RemoteViews for the smaller content view. 4869 * 4870 * @param increasedHeight true if this layout be created with an increased height. Some 4871 * styles may support showing more then just that basic 1U size 4872 * and the system may decide to render important notifications 4873 * slightly bigger even when collapsed. 4874 * 4875 * @hide 4876 */ 4877 public RemoteViews createContentView(boolean increasedHeight) { 4878 if (mN.contentView != null && useExistingRemoteView()) { 4879 return mN.contentView; 4880 } else if (mStyle != null) { 4881 final RemoteViews styleView = mStyle.makeContentView(increasedHeight); 4882 if (styleView != null) { 4883 return styleView; 4884 } 4885 } 4886 return applyStandardTemplate(getBaseLayoutResource()); 4887 } 4888 4889 private boolean useExistingRemoteView() { 4890 return mStyle == null || (!mStyle.displayCustomViewInline() 4891 && !mRebuildStyledRemoteViews); 4892 } 4893 4894 /** 4895 * Construct a RemoteViews for the final big notification layout. 4896 */ 4897 public RemoteViews createBigContentView() { 4898 RemoteViews result = null; 4899 if (mN.bigContentView != null && useExistingRemoteView()) { 4900 return mN.bigContentView; 4901 } else if (mStyle != null) { 4902 result = mStyle.makeBigContentView(); 4903 hideLine1Text(result); 4904 } else if (mActions.size() != 0) { 4905 result = applyStandardTemplateWithActions(getBigBaseLayoutResource()); 4906 } 4907 makeHeaderExpanded(result); 4908 return result; 4909 } 4910 4911 /** 4912 * Construct a RemoteViews for the final notification header only. This will not be 4913 * colorized. 4914 * 4915 * @param ambient if true, generate the header for the ambient display layout. 4916 * @hide 4917 */ 4918 public RemoteViews makeNotificationHeader(boolean ambient) { 4919 Boolean colorized = (Boolean) mN.extras.get(EXTRA_COLORIZED); 4920 mN.extras.putBoolean(EXTRA_COLORIZED, false); 4921 RemoteViews header = new BuilderRemoteViews(mContext.getApplicationInfo(), 4922 ambient ? R.layout.notification_template_ambient_header 4923 : R.layout.notification_template_header); 4924 resetNotificationHeader(header); 4925 bindNotificationHeader(header, ambient, null); 4926 if (colorized != null) { 4927 mN.extras.putBoolean(EXTRA_COLORIZED, colorized); 4928 } else { 4929 mN.extras.remove(EXTRA_COLORIZED); 4930 } 4931 return header; 4932 } 4933 4934 /** 4935 * Construct a RemoteViews for the ambient version of the notification. 4936 * 4937 * @hide 4938 */ 4939 public RemoteViews makeAmbientNotification() { 4940 RemoteViews ambient = applyStandardTemplateWithActions( 4941 R.layout.notification_template_material_ambient, 4942 mParams.reset().ambient(true).fillTextsFrom(this).hasProgress(false)); 4943 return ambient; 4944 } 4945 4946 private void hideLine1Text(RemoteViews result) { 4947 if (result != null) { 4948 result.setViewVisibility(R.id.text_line_1, View.GONE); 4949 } 4950 } 4951 4952 /** 4953 * Adapt the Notification header if this view is used as an expanded view. 4954 * 4955 * @hide 4956 */ 4957 public static void makeHeaderExpanded(RemoteViews result) { 4958 if (result != null) { 4959 result.setBoolean(R.id.notification_header, "setExpanded", true); 4960 } 4961 } 4962 4963 /** 4964 * Construct a RemoteViews for the final heads-up notification layout. 4965 * 4966 * @param increasedHeight true if this layout be created with an increased height. Some 4967 * styles may support showing more then just that basic 1U size 4968 * and the system may decide to render important notifications 4969 * slightly bigger even when collapsed. 4970 * 4971 * @hide 4972 */ 4973 public RemoteViews createHeadsUpContentView(boolean increasedHeight) { 4974 if (mN.headsUpContentView != null && useExistingRemoteView()) { 4975 return mN.headsUpContentView; 4976 } else if (mStyle != null) { 4977 final RemoteViews styleView = mStyle.makeHeadsUpContentView(increasedHeight); 4978 if (styleView != null) { 4979 return styleView; 4980 } 4981 } else if (mActions.size() == 0) { 4982 return null; 4983 } 4984 4985 return applyStandardTemplateWithActions(getBigBaseLayoutResource()); 4986 } 4987 4988 /** 4989 * Construct a RemoteViews for the final heads-up notification layout. 4990 */ 4991 public RemoteViews createHeadsUpContentView() { 4992 return createHeadsUpContentView(false /* useIncreasedHeight */); 4993 } 4994 4995 /** 4996 * Construct a RemoteViews for the display in public contexts like on the lockscreen. 4997 * 4998 * @hide 4999 */ 5000 public RemoteViews makePublicContentView() { 5001 return makePublicView(false /* ambient */); 5002 } 5003 5004 /** 5005 * Construct a RemoteViews for the display in public contexts like on the lockscreen. 5006 * 5007 * @hide 5008 */ 5009 public RemoteViews makePublicAmbientNotification() { 5010 return makePublicView(true /* ambient */); 5011 } 5012 5013 private RemoteViews makePublicView(boolean ambient) { 5014 if (mN.publicVersion != null) { 5015 final Builder builder = recoverBuilder(mContext, mN.publicVersion); 5016 return ambient ? builder.makeAmbientNotification() : builder.createContentView(); 5017 } 5018 Bundle savedBundle = mN.extras; 5019 Style style = mStyle; 5020 mStyle = null; 5021 Icon largeIcon = mN.mLargeIcon; 5022 mN.mLargeIcon = null; 5023 Bitmap largeIconLegacy = mN.largeIcon; 5024 mN.largeIcon = null; 5025 ArrayList<Action> actions = mActions; 5026 mActions = new ArrayList<>(); 5027 Bundle publicExtras = new Bundle(); 5028 publicExtras.putBoolean(EXTRA_SHOW_WHEN, 5029 savedBundle.getBoolean(EXTRA_SHOW_WHEN)); 5030 publicExtras.putBoolean(EXTRA_SHOW_CHRONOMETER, 5031 savedBundle.getBoolean(EXTRA_SHOW_CHRONOMETER)); 5032 publicExtras.putBoolean(EXTRA_CHRONOMETER_COUNT_DOWN, 5033 savedBundle.getBoolean(EXTRA_CHRONOMETER_COUNT_DOWN)); 5034 mN.extras = publicExtras; 5035 RemoteViews view; 5036 if (ambient) { 5037 publicExtras.putCharSequence(EXTRA_TITLE, 5038 mContext.getString(com.android.internal.R.string.notification_hidden_text)); 5039 view = makeAmbientNotification(); 5040 } else{ 5041 view = makeNotificationHeader(false /* ambient */); 5042 view.setBoolean(R.id.notification_header, "setExpandOnlyOnButton", true); 5043 } 5044 mN.extras = savedBundle; 5045 mN.mLargeIcon = largeIcon; 5046 mN.largeIcon = largeIconLegacy; 5047 mActions = actions; 5048 mStyle = style; 5049 return view; 5050 } 5051 5052 /** 5053 * Construct a content view for the display when low - priority 5054 * 5055 * @param useRegularSubtext uses the normal subtext set if there is one available. Otherwise 5056 * a new subtext is created consisting of the content of the 5057 * notification. 5058 * @hide 5059 */ 5060 public RemoteViews makeLowPriorityContentView(boolean useRegularSubtext) { 5061 int color = mN.color; 5062 mN.color = COLOR_DEFAULT; 5063 CharSequence summary = mN.extras.getCharSequence(EXTRA_SUB_TEXT); 5064 if (!useRegularSubtext || TextUtils.isEmpty(summary)) { 5065 CharSequence newSummary = createSummaryText(); 5066 if (!TextUtils.isEmpty(newSummary)) { 5067 mN.extras.putCharSequence(EXTRA_SUB_TEXT, newSummary); 5068 } 5069 } 5070 5071 RemoteViews header = makeNotificationHeader(false /* ambient */); 5072 header.setBoolean(R.id.notification_header, "setAcceptAllTouches", true); 5073 if (summary != null) { 5074 mN.extras.putCharSequence(EXTRA_SUB_TEXT, summary); 5075 } else { 5076 mN.extras.remove(EXTRA_SUB_TEXT); 5077 } 5078 mN.color = color; 5079 return header; 5080 } 5081 5082 private CharSequence createSummaryText() { 5083 CharSequence titleText = mN.extras.getCharSequence(Notification.EXTRA_TITLE); 5084 if (USE_ONLY_TITLE_IN_LOW_PRIORITY_SUMMARY) { 5085 return titleText; 5086 } 5087 SpannableStringBuilder summary = new SpannableStringBuilder(); 5088 if (titleText == null) { 5089 titleText = mN.extras.getCharSequence(Notification.EXTRA_TITLE_BIG); 5090 } 5091 BidiFormatter bidi = BidiFormatter.getInstance(); 5092 if (titleText != null) { 5093 summary.append(bidi.unicodeWrap(titleText)); 5094 } 5095 CharSequence contentText = mN.extras.getCharSequence(Notification.EXTRA_TEXT); 5096 if (titleText != null && contentText != null) { 5097 summary.append(bidi.unicodeWrap(mContext.getText( 5098 R.string.notification_header_divider_symbol_with_spaces))); 5099 } 5100 if (contentText != null) { 5101 summary.append(bidi.unicodeWrap(contentText)); 5102 } 5103 return summary; 5104 } 5105 5106 private RemoteViews generateActionButton(Action action, boolean emphazisedMode, 5107 boolean ambient) { 5108 final boolean tombstone = (action.actionIntent == null); 5109 RemoteViews button = new BuilderRemoteViews(mContext.getApplicationInfo(), 5110 emphazisedMode ? getEmphasizedActionLayoutResource() 5111 : tombstone ? getActionTombstoneLayoutResource() 5112 : getActionLayoutResource()); 5113 if (!tombstone) { 5114 button.setOnClickPendingIntent(R.id.action0, action.actionIntent); 5115 } 5116 button.setContentDescription(R.id.action0, action.title); 5117 if (action.mRemoteInputs != null) { 5118 button.setRemoteInputs(R.id.action0, action.mRemoteInputs); 5119 } 5120 if (emphazisedMode) { 5121 // change the background bgColor 5122 CharSequence title = action.title; 5123 ColorStateList[] outResultColor = null; 5124 int background = resolveBackgroundColor(); 5125 if (isLegacy()) { 5126 title = NotificationColorUtil.clearColorSpans(title); 5127 } else { 5128 outResultColor = new ColorStateList[1]; 5129 title = ensureColorSpanContrast(title, background, outResultColor); 5130 } 5131 button.setTextViewText(R.id.action0, processTextSpans(title)); 5132 setTextViewColorPrimary(button, R.id.action0); 5133 int rippleColor; 5134 boolean hasColorOverride = outResultColor != null && outResultColor[0] != null; 5135 if (hasColorOverride) { 5136 // There's a span spanning the full text, let's take it and use it as the 5137 // background color 5138 background = outResultColor[0].getDefaultColor(); 5139 int textColor = NotificationColorUtil.resolvePrimaryColor(mContext, 5140 background); 5141 button.setTextColor(R.id.action0, textColor); 5142 rippleColor = textColor; 5143 } else if (mN.color != COLOR_DEFAULT && !isColorized() && mTintActionButtons) { 5144 rippleColor = resolveContrastColor(); 5145 button.setTextColor(R.id.action0, rippleColor); 5146 } else { 5147 rippleColor = getPrimaryTextColor(); 5148 } 5149 // We only want about 20% alpha for the ripple 5150 rippleColor = (rippleColor & 0x00ffffff) | 0x33000000; 5151 button.setColorStateList(R.id.action0, "setRippleColor", 5152 ColorStateList.valueOf(rippleColor)); 5153 button.setColorStateList(R.id.action0, "setButtonBackground", 5154 ColorStateList.valueOf(background)); 5155 button.setBoolean(R.id.action0, "setHasStroke", !hasColorOverride); 5156 } else { 5157 button.setTextViewText(R.id.action0, processTextSpans( 5158 processLegacyText(action.title))); 5159 if (isColorized() && !ambient) { 5160 setTextViewColorPrimary(button, R.id.action0); 5161 } else if (mN.color != COLOR_DEFAULT && mTintActionButtons) { 5162 button.setTextColor(R.id.action0, 5163 ambient ? resolveAmbientColor() : resolveContrastColor()); 5164 } 5165 } 5166 return button; 5167 } 5168 5169 /** 5170 * Ensures contrast on color spans against a background color. also returns the color of the 5171 * text if a span was found that spans over the whole text. 5172 * 5173 * @param charSequence the charSequence on which the spans are 5174 * @param background the background color to ensure the contrast against 5175 * @param outResultColor an array in which a color will be returned as the first element if 5176 * there exists a full length color span. 5177 * @return the contrasted charSequence 5178 */ 5179 private CharSequence ensureColorSpanContrast(CharSequence charSequence, int background, 5180 ColorStateList[] outResultColor) { 5181 if (charSequence instanceof Spanned) { 5182 Spanned ss = (Spanned) charSequence; 5183 Object[] spans = ss.getSpans(0, ss.length(), Object.class); 5184 SpannableStringBuilder builder = new SpannableStringBuilder(ss.toString()); 5185 for (Object span : spans) { 5186 Object resultSpan = span; 5187 int spanStart = ss.getSpanStart(span); 5188 int spanEnd = ss.getSpanEnd(span); 5189 boolean fullLength = (spanEnd - spanStart) == charSequence.length(); 5190 if (resultSpan instanceof CharacterStyle) { 5191 resultSpan = ((CharacterStyle) span).getUnderlying(); 5192 } 5193 if (resultSpan instanceof TextAppearanceSpan) { 5194 TextAppearanceSpan originalSpan = (TextAppearanceSpan) resultSpan; 5195 ColorStateList textColor = originalSpan.getTextColor(); 5196 if (textColor != null) { 5197 int[] colors = textColor.getColors(); 5198 int[] newColors = new int[colors.length]; 5199 for (int i = 0; i < newColors.length; i++) { 5200 newColors[i] = NotificationColorUtil.ensureLargeTextContrast( 5201 colors[i], background, mInNightMode); 5202 } 5203 textColor = new ColorStateList(textColor.getStates().clone(), 5204 newColors); 5205 if (fullLength) { 5206 outResultColor[0] = textColor; 5207 // Let's drop the color from the span 5208 textColor = null; 5209 } 5210 resultSpan = new TextAppearanceSpan( 5211 originalSpan.getFamily(), 5212 originalSpan.getTextStyle(), 5213 originalSpan.getTextSize(), 5214 textColor, 5215 originalSpan.getLinkTextColor()); 5216 } 5217 } else if (resultSpan instanceof ForegroundColorSpan) { 5218 ForegroundColorSpan originalSpan = (ForegroundColorSpan) resultSpan; 5219 int foregroundColor = originalSpan.getForegroundColor(); 5220 foregroundColor = NotificationColorUtil.ensureLargeTextContrast( 5221 foregroundColor, background, mInNightMode); 5222 if (fullLength) { 5223 outResultColor[0] = ColorStateList.valueOf(foregroundColor); 5224 resultSpan = null; 5225 } else { 5226 resultSpan = new ForegroundColorSpan(foregroundColor); 5227 } 5228 } else { 5229 resultSpan = span; 5230 } 5231 if (resultSpan != null) { 5232 builder.setSpan(resultSpan, spanStart, spanEnd, ss.getSpanFlags(span)); 5233 } 5234 } 5235 return builder; 5236 } 5237 return charSequence; 5238 } 5239 5240 /** 5241 * @return Whether we are currently building a notification from a legacy (an app that 5242 * doesn't create material notifications by itself) app. 5243 */ 5244 private boolean isLegacy() { 5245 if (!mIsLegacyInitialized) { 5246 mIsLegacy = mContext.getApplicationInfo().targetSdkVersion 5247 < Build.VERSION_CODES.LOLLIPOP; 5248 mIsLegacyInitialized = true; 5249 } 5250 return mIsLegacy; 5251 } 5252 5253 private CharSequence processLegacyText(CharSequence charSequence) { 5254 return processLegacyText(charSequence, false /* ambient */); 5255 } 5256 5257 private CharSequence processLegacyText(CharSequence charSequence, boolean ambient) { 5258 boolean isAlreadyLightText = isLegacy() || textColorsNeedInversion(); 5259 boolean wantLightText = ambient; 5260 if (isAlreadyLightText != wantLightText) { 5261 return getColorUtil().invertCharSequenceColors(charSequence); 5262 } else { 5263 return charSequence; 5264 } 5265 } 5266 5267 /** 5268 * Apply any necessariy colors to the small icon 5269 */ 5270 private void processSmallIconColor(Icon smallIcon, RemoteViews contentView, 5271 boolean ambient) { 5272 boolean colorable = !isLegacy() || getColorUtil().isGrayscaleIcon(mContext, smallIcon); 5273 int color; 5274 if (ambient) { 5275 color = resolveAmbientColor(); 5276 } else if (isColorized()) { 5277 color = getPrimaryTextColor(); 5278 } else { 5279 color = resolveContrastColor(); 5280 } 5281 if (colorable) { 5282 contentView.setDrawableTint(R.id.icon, false, color, 5283 PorterDuff.Mode.SRC_ATOP); 5284 5285 } 5286 contentView.setInt(R.id.notification_header, "setOriginalIconColor", 5287 colorable ? color : NotificationHeaderView.NO_COLOR); 5288 } 5289 5290 /** 5291 * Make the largeIcon dark if it's a fake smallIcon (that is, 5292 * if it's grayscale). 5293 */ 5294 // TODO: also check bounds, transparency, that sort of thing. 5295 private void processLargeLegacyIcon(Icon largeIcon, RemoteViews contentView) { 5296 if (largeIcon != null && isLegacy() 5297 && getColorUtil().isGrayscaleIcon(mContext, largeIcon)) { 5298 // resolve color will fall back to the default when legacy 5299 contentView.setDrawableTint(R.id.icon, false, resolveContrastColor(), 5300 PorterDuff.Mode.SRC_ATOP); 5301 } 5302 } 5303 5304 private void sanitizeColor() { 5305 if (mN.color != COLOR_DEFAULT) { 5306 mN.color |= 0xFF000000; // no alpha for custom colors 5307 } 5308 } 5309 5310 int resolveContrastColor() { 5311 if (mCachedContrastColorIsFor == mN.color && mCachedContrastColor != COLOR_INVALID) { 5312 return mCachedContrastColor; 5313 } 5314 5315 int color; 5316 int background = mContext.getColor( 5317 com.android.internal.R.color.notification_material_background_color); 5318 if (mN.color == COLOR_DEFAULT) { 5319 ensureColors(); 5320 color = NotificationColorUtil.resolveDefaultColor(mContext, background); 5321 } else { 5322 color = NotificationColorUtil.resolveContrastColor(mContext, mN.color, 5323 background, mInNightMode); 5324 } 5325 if (Color.alpha(color) < 255) { 5326 // alpha doesn't go well for color filters, so let's blend it manually 5327 color = NotificationColorUtil.compositeColors(color, background); 5328 } 5329 mCachedContrastColorIsFor = mN.color; 5330 return mCachedContrastColor = color; 5331 } 5332 5333 int resolveAmbientColor() { 5334 if (mCachedAmbientColorIsFor == mN.color && mCachedAmbientColorIsFor != COLOR_INVALID) { 5335 return mCachedAmbientColor; 5336 } 5337 final int contrasted = NotificationColorUtil.resolveAmbientColor(mContext, mN.color); 5338 5339 mCachedAmbientColorIsFor = mN.color; 5340 return mCachedAmbientColor = contrasted; 5341 } 5342 5343 /** 5344 * Apply the unstyled operations and return a new {@link Notification} object. 5345 * @hide 5346 */ 5347 public Notification buildUnstyled() { 5348 if (mActions.size() > 0) { 5349 mN.actions = new Action[mActions.size()]; 5350 mActions.toArray(mN.actions); 5351 } 5352 if (!mPersonList.isEmpty()) { 5353 mN.extras.putParcelableArrayList(EXTRA_PEOPLE_LIST, mPersonList); 5354 } 5355 if (mN.bigContentView != null || mN.contentView != null 5356 || mN.headsUpContentView != null) { 5357 mN.extras.putBoolean(EXTRA_CONTAINS_CUSTOM_VIEW, true); 5358 } 5359 return mN; 5360 } 5361 5362 /** 5363 * Creates a Builder from an existing notification so further changes can be made. 5364 * @param context The context for your application / activity. 5365 * @param n The notification to create a Builder from. 5366 */ 5367 public static Notification.Builder recoverBuilder(Context context, Notification n) { 5368 // Re-create notification context so we can access app resources. 5369 ApplicationInfo applicationInfo = n.extras.getParcelable( 5370 EXTRA_BUILDER_APPLICATION_INFO); 5371 Context builderContext; 5372 if (applicationInfo != null) { 5373 try { 5374 builderContext = context.createApplicationContext(applicationInfo, 5375 Context.CONTEXT_RESTRICTED); 5376 } catch (NameNotFoundException e) { 5377 Log.e(TAG, "ApplicationInfo " + applicationInfo + " not found"); 5378 builderContext = context; // try with our context 5379 } 5380 } else { 5381 builderContext = context; // try with given context 5382 } 5383 5384 return new Builder(builderContext, n); 5385 } 5386 5387 /** 5388 * @deprecated Use {@link #build()} instead. 5389 */ 5390 @Deprecated 5391 public Notification getNotification() { 5392 return build(); 5393 } 5394 5395 /** 5396 * Combine all of the options that have been set and return a new {@link Notification} 5397 * object. 5398 */ 5399 public Notification build() { 5400 // first, add any extras from the calling code 5401 if (mUserExtras != null) { 5402 mN.extras = getAllExtras(); 5403 } 5404 5405 mN.creationTime = System.currentTimeMillis(); 5406 5407 // lazy stuff from mContext; see comment in Builder(Context, Notification) 5408 Notification.addFieldsFromContext(mContext, mN); 5409 5410 buildUnstyled(); 5411 5412 if (mStyle != null) { 5413 mStyle.reduceImageSizes(mContext); 5414 mStyle.purgeResources(); 5415 mStyle.validate(mContext); 5416 mStyle.buildStyled(mN); 5417 } 5418 mN.reduceImageSizes(mContext); 5419 5420 if (mContext.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N 5421 && (useExistingRemoteView())) { 5422 if (mN.contentView == null) { 5423 mN.contentView = createContentView(); 5424 mN.extras.putInt(EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT, 5425 mN.contentView.getSequenceNumber()); 5426 } 5427 if (mN.bigContentView == null) { 5428 mN.bigContentView = createBigContentView(); 5429 if (mN.bigContentView != null) { 5430 mN.extras.putInt(EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT, 5431 mN.bigContentView.getSequenceNumber()); 5432 } 5433 } 5434 if (mN.headsUpContentView == null) { 5435 mN.headsUpContentView = createHeadsUpContentView(); 5436 if (mN.headsUpContentView != null) { 5437 mN.extras.putInt(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT, 5438 mN.headsUpContentView.getSequenceNumber()); 5439 } 5440 } 5441 } 5442 5443 if ((mN.defaults & DEFAULT_LIGHTS) != 0) { 5444 mN.flags |= FLAG_SHOW_LIGHTS; 5445 } 5446 5447 mN.allPendingIntents = null; 5448 5449 return mN; 5450 } 5451 5452 /** 5453 * Apply this Builder to an existing {@link Notification} object. 5454 * 5455 * @hide 5456 */ 5457 public Notification buildInto(Notification n) { 5458 build().cloneInto(n, true); 5459 return n; 5460 } 5461 5462 /** 5463 * Removes RemoteViews that were created for compatibility from {@param n}, if they did not 5464 * change. Also removes extenders on low ram devices, as 5465 * {@link android.service.notification.NotificationListenerService} services are disabled. 5466 * 5467 * @return {@param n}, if no stripping is needed, otherwise a stripped clone of {@param n}. 5468 * 5469 * @hide 5470 */ 5471 public static Notification maybeCloneStrippedForDelivery(Notification n, boolean isLowRam) { 5472 String templateClass = n.extras.getString(EXTRA_TEMPLATE); 5473 5474 // Only strip views for known Styles because we won't know how to 5475 // re-create them otherwise. 5476 if (!isLowRam 5477 && !TextUtils.isEmpty(templateClass) 5478 && getNotificationStyleClass(templateClass) == null) { 5479 return n; 5480 } 5481 5482 // Only strip unmodified BuilderRemoteViews. 5483 boolean stripContentView = n.contentView instanceof BuilderRemoteViews && 5484 n.extras.getInt(EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT, -1) == 5485 n.contentView.getSequenceNumber(); 5486 boolean stripBigContentView = n.bigContentView instanceof BuilderRemoteViews && 5487 n.extras.getInt(EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT, -1) == 5488 n.bigContentView.getSequenceNumber(); 5489 boolean stripHeadsUpContentView = n.headsUpContentView instanceof BuilderRemoteViews && 5490 n.extras.getInt(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT, -1) == 5491 n.headsUpContentView.getSequenceNumber(); 5492 5493 // Nothing to do here, no need to clone. 5494 if (!isLowRam 5495 && !stripContentView && !stripBigContentView && !stripHeadsUpContentView) { 5496 return n; 5497 } 5498 5499 Notification clone = n.clone(); 5500 if (stripContentView) { 5501 clone.contentView = null; 5502 clone.extras.remove(EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT); 5503 } 5504 if (stripBigContentView) { 5505 clone.bigContentView = null; 5506 clone.extras.remove(EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT); 5507 } 5508 if (stripHeadsUpContentView) { 5509 clone.headsUpContentView = null; 5510 clone.extras.remove(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT); 5511 } 5512 if (isLowRam) { 5513 clone.extras.remove(Notification.TvExtender.EXTRA_TV_EXTENDER); 5514 clone.extras.remove(WearableExtender.EXTRA_WEARABLE_EXTENSIONS); 5515 clone.extras.remove(CarExtender.EXTRA_CAR_EXTENDER); 5516 } 5517 return clone; 5518 } 5519 5520 private int getBaseLayoutResource() { 5521 return R.layout.notification_template_material_base; 5522 } 5523 5524 private int getBigBaseLayoutResource() { 5525 return R.layout.notification_template_material_big_base; 5526 } 5527 5528 private int getBigPictureLayoutResource() { 5529 return R.layout.notification_template_material_big_picture; 5530 } 5531 5532 private int getBigTextLayoutResource() { 5533 return R.layout.notification_template_material_big_text; 5534 } 5535 5536 private int getInboxLayoutResource() { 5537 return R.layout.notification_template_material_inbox; 5538 } 5539 5540 private int getMessagingLayoutResource() { 5541 return R.layout.notification_template_material_messaging; 5542 } 5543 5544 private int getActionLayoutResource() { 5545 return R.layout.notification_material_action; 5546 } 5547 5548 private int getEmphasizedActionLayoutResource() { 5549 return R.layout.notification_material_action_emphasized; 5550 } 5551 5552 private int getActionTombstoneLayoutResource() { 5553 return R.layout.notification_material_action_tombstone; 5554 } 5555 5556 private int getBackgroundColor() { 5557 if (isColorized()) { 5558 return mBackgroundColor != COLOR_INVALID ? mBackgroundColor : mN.color; 5559 } else { 5560 return COLOR_DEFAULT; 5561 } 5562 } 5563 5564 /** 5565 * Same as getBackgroundColor but also resolved the default color to the background. 5566 */ 5567 private int resolveBackgroundColor() { 5568 int backgroundColor = getBackgroundColor(); 5569 if (backgroundColor == COLOR_DEFAULT) { 5570 backgroundColor = mContext.getColor( 5571 com.android.internal.R.color.notification_material_background_color); 5572 } 5573 return backgroundColor; 5574 } 5575 5576 private boolean isColorized() { 5577 return mN.isColorized(); 5578 } 5579 5580 private boolean shouldTintActionButtons() { 5581 return mTintActionButtons; 5582 } 5583 5584 private boolean textColorsNeedInversion() { 5585 if (mStyle == null || !MediaStyle.class.equals(mStyle.getClass())) { 5586 return false; 5587 } 5588 int targetSdkVersion = mContext.getApplicationInfo().targetSdkVersion; 5589 return targetSdkVersion > Build.VERSION_CODES.M 5590 && targetSdkVersion < Build.VERSION_CODES.O; 5591 } 5592 5593 /** 5594 * Set a color palette to be used as the background and textColors 5595 * 5596 * @param backgroundColor the color to be used as the background 5597 * @param foregroundColor the color to be used as the foreground 5598 * 5599 * @hide 5600 */ 5601 public void setColorPalette(int backgroundColor, int foregroundColor) { 5602 mBackgroundColor = backgroundColor; 5603 mForegroundColor = foregroundColor; 5604 mTextColorsAreForBackground = COLOR_INVALID; 5605 ensureColors(); 5606 } 5607 5608 /** 5609 * Forces all styled remoteViews to be built from scratch and not use any cached 5610 * RemoteViews. 5611 * This is needed for legacy apps that are baking in their remoteviews into the 5612 * notification. 5613 * 5614 * @hide 5615 */ 5616 public void setRebuildStyledRemoteViews(boolean rebuild) { 5617 mRebuildStyledRemoteViews = rebuild; 5618 } 5619 5620 /** 5621 * Get the text that should be displayed in the statusBar when heads upped. This is 5622 * usually just the app name, but may be different depending on the style. 5623 * 5624 * @param publicMode If true, return a text that is safe to display in public. 5625 * 5626 * @hide 5627 */ 5628 public CharSequence getHeadsUpStatusBarText(boolean publicMode) { 5629 if (mStyle != null && !publicMode) { 5630 CharSequence text = mStyle.getHeadsUpStatusBarText(); 5631 if (!TextUtils.isEmpty(text)) { 5632 return text; 5633 } 5634 } 5635 return loadHeaderAppName(); 5636 } 5637 } 5638 5639 /** 5640 * Reduces the image sizes to conform to a maximum allowed size. This also processes all custom 5641 * remote views. 5642 * 5643 * @hide 5644 */ 5645 void reduceImageSizes(Context context) { 5646 if (extras.getBoolean(EXTRA_REDUCED_IMAGES)) { 5647 return; 5648 } 5649 boolean isLowRam = ActivityManager.isLowRamDeviceStatic(); 5650 if (mLargeIcon != null || largeIcon != null) { 5651 Resources resources = context.getResources(); 5652 Class<? extends Style> style = getNotificationStyle(); 5653 int maxWidth = resources.getDimensionPixelSize(isLowRam 5654 ? R.dimen.notification_right_icon_size_low_ram 5655 : R.dimen.notification_right_icon_size); 5656 int maxHeight = maxWidth; 5657 if (MediaStyle.class.equals(style) 5658 || DecoratedMediaCustomViewStyle.class.equals(style)) { 5659 maxHeight = resources.getDimensionPixelSize(isLowRam 5660 ? R.dimen.notification_media_image_max_height_low_ram 5661 : R.dimen.notification_media_image_max_height); 5662 maxWidth = resources.getDimensionPixelSize(isLowRam 5663 ? R.dimen.notification_media_image_max_width_low_ram 5664 : R.dimen.notification_media_image_max_width); 5665 } 5666 if (mLargeIcon != null) { 5667 mLargeIcon.scaleDownIfNecessary(maxWidth, maxHeight); 5668 } 5669 if (largeIcon != null) { 5670 largeIcon = Icon.scaleDownIfNecessary(largeIcon, maxWidth, maxHeight); 5671 } 5672 } 5673 reduceImageSizesForRemoteView(contentView, context, isLowRam); 5674 reduceImageSizesForRemoteView(headsUpContentView, context, isLowRam); 5675 reduceImageSizesForRemoteView(bigContentView, context, isLowRam); 5676 extras.putBoolean(EXTRA_REDUCED_IMAGES, true); 5677 } 5678 5679 private void reduceImageSizesForRemoteView(RemoteViews remoteView, Context context, 5680 boolean isLowRam) { 5681 if (remoteView != null) { 5682 Resources resources = context.getResources(); 5683 int maxWidth = resources.getDimensionPixelSize(isLowRam 5684 ? R.dimen.notification_custom_view_max_image_width_low_ram 5685 : R.dimen.notification_custom_view_max_image_width); 5686 int maxHeight = resources.getDimensionPixelSize(isLowRam 5687 ? R.dimen.notification_custom_view_max_image_height_low_ram 5688 : R.dimen.notification_custom_view_max_image_height); 5689 remoteView.reduceImageSizes(maxWidth, maxHeight); 5690 } 5691 } 5692 5693 /** 5694 * @return whether this notification is a foreground service notification 5695 */ 5696 private boolean isForegroundService() { 5697 return (flags & Notification.FLAG_FOREGROUND_SERVICE) != 0; 5698 } 5699 5700 /** 5701 * @return whether this notification has a media session attached 5702 * @hide 5703 */ 5704 public boolean hasMediaSession() { 5705 return extras.getParcelable(Notification.EXTRA_MEDIA_SESSION) != null; 5706 } 5707 5708 /** 5709 * @return the style class of this notification 5710 * @hide 5711 */ 5712 public Class<? extends Notification.Style> getNotificationStyle() { 5713 String templateClass = extras.getString(Notification.EXTRA_TEMPLATE); 5714 5715 if (!TextUtils.isEmpty(templateClass)) { 5716 return Notification.getNotificationStyleClass(templateClass); 5717 } 5718 return null; 5719 } 5720 5721 /** 5722 * @return true if this notification is colorized. 5723 * 5724 * @hide 5725 */ 5726 public boolean isColorized() { 5727 if (isColorizedMedia()) { 5728 return true; 5729 } 5730 return extras.getBoolean(EXTRA_COLORIZED) 5731 && (hasColorizedPermission() || isForegroundService()); 5732 } 5733 5734 /** 5735 * Returns whether an app can colorize due to the android.permission.USE_COLORIZED_NOTIFICATIONS 5736 * permission. The permission is checked when a notification is enqueued. 5737 */ 5738 private boolean hasColorizedPermission() { 5739 return (flags & Notification.FLAG_CAN_COLORIZE) != 0; 5740 } 5741 5742 /** 5743 * @return true if this notification is colorized and it is a media notification 5744 * 5745 * @hide 5746 */ 5747 public boolean isColorizedMedia() { 5748 Class<? extends Style> style = getNotificationStyle(); 5749 if (MediaStyle.class.equals(style)) { 5750 Boolean colorized = (Boolean) extras.get(EXTRA_COLORIZED); 5751 if ((colorized == null || colorized) && hasMediaSession()) { 5752 return true; 5753 } 5754 } else if (DecoratedMediaCustomViewStyle.class.equals(style)) { 5755 if (extras.getBoolean(EXTRA_COLORIZED) && hasMediaSession()) { 5756 return true; 5757 } 5758 } 5759 return false; 5760 } 5761 5762 5763 /** 5764 * @return true if this is a media notification 5765 * 5766 * @hide 5767 */ 5768 public boolean isMediaNotification() { 5769 Class<? extends Style> style = getNotificationStyle(); 5770 if (MediaStyle.class.equals(style)) { 5771 return true; 5772 } else if (DecoratedMediaCustomViewStyle.class.equals(style)) { 5773 return true; 5774 } 5775 return false; 5776 } 5777 5778 private boolean hasLargeIcon() { 5779 return mLargeIcon != null || largeIcon != null; 5780 } 5781 5782 /** 5783 * @return true if the notification will show the time; false otherwise 5784 * @hide 5785 */ 5786 public boolean showsTime() { 5787 return when != 0 && extras.getBoolean(EXTRA_SHOW_WHEN); 5788 } 5789 5790 /** 5791 * @return true if the notification will show a chronometer; false otherwise 5792 * @hide 5793 */ 5794 public boolean showsChronometer() { 5795 return when != 0 && extras.getBoolean(EXTRA_SHOW_CHRONOMETER); 5796 } 5797 5798 /** 5799 * @removed 5800 */ 5801 @SystemApi 5802 public static Class<? extends Style> getNotificationStyleClass(String templateClass) { 5803 Class<? extends Style>[] classes = new Class[] { 5804 BigTextStyle.class, BigPictureStyle.class, InboxStyle.class, MediaStyle.class, 5805 DecoratedCustomViewStyle.class, DecoratedMediaCustomViewStyle.class, 5806 MessagingStyle.class }; 5807 for (Class<? extends Style> innerClass : classes) { 5808 if (templateClass.equals(innerClass.getName())) { 5809 return innerClass; 5810 } 5811 } 5812 return null; 5813 } 5814 5815 /** 5816 * An object that can apply a rich notification style to a {@link Notification.Builder} 5817 * object. 5818 */ 5819 public static abstract class Style { 5820 private CharSequence mBigContentTitle; 5821 5822 /** 5823 * @hide 5824 */ 5825 protected CharSequence mSummaryText = null; 5826 5827 /** 5828 * @hide 5829 */ 5830 protected boolean mSummaryTextSet = false; 5831 5832 protected Builder mBuilder; 5833 5834 /** 5835 * Overrides ContentTitle in the big form of the template. 5836 * This defaults to the value passed to setContentTitle(). 5837 */ 5838 protected void internalSetBigContentTitle(CharSequence title) { 5839 mBigContentTitle = title; 5840 } 5841 5842 /** 5843 * Set the first line of text after the detail section in the big form of the template. 5844 */ 5845 protected void internalSetSummaryText(CharSequence cs) { 5846 mSummaryText = cs; 5847 mSummaryTextSet = true; 5848 } 5849 5850 public void setBuilder(Builder builder) { 5851 if (mBuilder != builder) { 5852 mBuilder = builder; 5853 if (mBuilder != null) { 5854 mBuilder.setStyle(this); 5855 } 5856 } 5857 } 5858 5859 protected void checkBuilder() { 5860 if (mBuilder == null) { 5861 throw new IllegalArgumentException("Style requires a valid Builder object"); 5862 } 5863 } 5864 5865 protected RemoteViews getStandardView(int layoutId) { 5866 checkBuilder(); 5867 5868 // Nasty. 5869 CharSequence oldBuilderContentTitle = 5870 mBuilder.getAllExtras().getCharSequence(EXTRA_TITLE); 5871 if (mBigContentTitle != null) { 5872 mBuilder.setContentTitle(mBigContentTitle); 5873 } 5874 5875 RemoteViews contentView = mBuilder.applyStandardTemplateWithActions(layoutId); 5876 5877 mBuilder.getAllExtras().putCharSequence(EXTRA_TITLE, oldBuilderContentTitle); 5878 5879 if (mBigContentTitle != null && mBigContentTitle.equals("")) { 5880 contentView.setViewVisibility(R.id.line1, View.GONE); 5881 } else { 5882 contentView.setViewVisibility(R.id.line1, View.VISIBLE); 5883 } 5884 5885 return contentView; 5886 } 5887 5888 /** 5889 * Construct a Style-specific RemoteViews for the collapsed notification layout. 5890 * The default implementation has nothing additional to add. 5891 * 5892 * @param increasedHeight true if this layout be created with an increased height. 5893 * @hide 5894 */ 5895 public RemoteViews makeContentView(boolean increasedHeight) { 5896 return null; 5897 } 5898 5899 /** 5900 * Construct a Style-specific RemoteViews for the final big notification layout. 5901 * @hide 5902 */ 5903 public RemoteViews makeBigContentView() { 5904 return null; 5905 } 5906 5907 /** 5908 * Construct a Style-specific RemoteViews for the final HUN layout. 5909 * 5910 * @param increasedHeight true if this layout be created with an increased height. 5911 * @hide 5912 */ 5913 public RemoteViews makeHeadsUpContentView(boolean increasedHeight) { 5914 return null; 5915 } 5916 5917 /** 5918 * Apply any style-specific extras to this notification before shipping it out. 5919 * @hide 5920 */ 5921 public void addExtras(Bundle extras) { 5922 if (mSummaryTextSet) { 5923 extras.putCharSequence(EXTRA_SUMMARY_TEXT, mSummaryText); 5924 } 5925 if (mBigContentTitle != null) { 5926 extras.putCharSequence(EXTRA_TITLE_BIG, mBigContentTitle); 5927 } 5928 extras.putString(EXTRA_TEMPLATE, this.getClass().getName()); 5929 } 5930 5931 /** 5932 * Reconstruct the internal state of this Style object from extras. 5933 * @hide 5934 */ 5935 protected void restoreFromExtras(Bundle extras) { 5936 if (extras.containsKey(EXTRA_SUMMARY_TEXT)) { 5937 mSummaryText = extras.getCharSequence(EXTRA_SUMMARY_TEXT); 5938 mSummaryTextSet = true; 5939 } 5940 if (extras.containsKey(EXTRA_TITLE_BIG)) { 5941 mBigContentTitle = extras.getCharSequence(EXTRA_TITLE_BIG); 5942 } 5943 } 5944 5945 5946 /** 5947 * @hide 5948 */ 5949 public Notification buildStyled(Notification wip) { 5950 addExtras(wip.extras); 5951 return wip; 5952 } 5953 5954 /** 5955 * @hide 5956 */ 5957 public void purgeResources() {} 5958 5959 /** 5960 * Calls {@link android.app.Notification.Builder#build()} on the Builder this Style is 5961 * attached to. 5962 * 5963 * @return the fully constructed Notification. 5964 */ 5965 public Notification build() { 5966 checkBuilder(); 5967 return mBuilder.build(); 5968 } 5969 5970 /** 5971 * @hide 5972 * @return true if the style positions the progress bar on the second line; false if the 5973 * style hides the progress bar 5974 */ 5975 protected boolean hasProgress() { 5976 return true; 5977 } 5978 5979 /** 5980 * @hide 5981 * @return Whether we should put the summary be put into the notification header 5982 */ 5983 public boolean hasSummaryInHeader() { 5984 return true; 5985 } 5986 5987 /** 5988 * @hide 5989 * @return Whether custom content views are displayed inline in the style 5990 */ 5991 public boolean displayCustomViewInline() { 5992 return false; 5993 } 5994 5995 /** 5996 * Reduces the image sizes contained in this style. 5997 * 5998 * @hide 5999 */ 6000 public void reduceImageSizes(Context context) { 6001 } 6002 6003 /** 6004 * Validate that this style was properly composed. This is called at build time. 6005 * @hide 6006 */ 6007 public void validate(Context context) { 6008 } 6009 6010 /** 6011 * @hide 6012 */ 6013 public abstract boolean areNotificationsVisiblyDifferent(Style other); 6014 6015 /** 6016 * @return the the text that should be displayed in the statusBar when heads-upped. 6017 * If {@code null} is returned, the default implementation will be used. 6018 * 6019 * @hide 6020 */ 6021 public CharSequence getHeadsUpStatusBarText() { 6022 return null; 6023 } 6024 } 6025 6026 /** 6027 * Helper class for generating large-format notifications that include a large image attachment. 6028 * 6029 * Here's how you'd set the <code>BigPictureStyle</code> on a notification: 6030 * <pre class="prettyprint"> 6031 * Notification notif = new Notification.Builder(mContext) 6032 * .setContentTitle("New photo from " + sender.toString()) 6033 * .setContentText(subject) 6034 * .setSmallIcon(R.drawable.new_post) 6035 * .setLargeIcon(aBitmap) 6036 * .setStyle(new Notification.BigPictureStyle() 6037 * .bigPicture(aBigBitmap)) 6038 * .build(); 6039 * </pre> 6040 * 6041 * @see Notification#bigContentView 6042 */ 6043 public static class BigPictureStyle extends Style { 6044 private Bitmap mPicture; 6045 private Icon mBigLargeIcon; 6046 private boolean mBigLargeIconSet = false; 6047 6048 public BigPictureStyle() { 6049 } 6050 6051 /** 6052 * @deprecated use {@code BigPictureStyle()}. 6053 */ 6054 @Deprecated 6055 public BigPictureStyle(Builder builder) { 6056 setBuilder(builder); 6057 } 6058 6059 /** 6060 * Overrides ContentTitle in the big form of the template. 6061 * This defaults to the value passed to setContentTitle(). 6062 */ 6063 public BigPictureStyle setBigContentTitle(CharSequence title) { 6064 internalSetBigContentTitle(safeCharSequence(title)); 6065 return this; 6066 } 6067 6068 /** 6069 * Set the first line of text after the detail section in the big form of the template. 6070 */ 6071 public BigPictureStyle setSummaryText(CharSequence cs) { 6072 internalSetSummaryText(safeCharSequence(cs)); 6073 return this; 6074 } 6075 6076 /** 6077 * @hide 6078 */ 6079 public Bitmap getBigPicture() { 6080 return mPicture; 6081 } 6082 6083 /** 6084 * Provide the bitmap to be used as the payload for the BigPicture notification. 6085 */ 6086 public BigPictureStyle bigPicture(Bitmap b) { 6087 mPicture = b; 6088 return this; 6089 } 6090 6091 /** 6092 * Override the large icon when the big notification is shown. 6093 */ 6094 public BigPictureStyle bigLargeIcon(Bitmap b) { 6095 return bigLargeIcon(b != null ? Icon.createWithBitmap(b) : null); 6096 } 6097 6098 /** 6099 * Override the large icon when the big notification is shown. 6100 */ 6101 public BigPictureStyle bigLargeIcon(Icon icon) { 6102 mBigLargeIconSet = true; 6103 mBigLargeIcon = icon; 6104 return this; 6105 } 6106 6107 /** @hide */ 6108 public static final int MIN_ASHMEM_BITMAP_SIZE = 128 * (1 << 10); 6109 6110 /** 6111 * @hide 6112 */ 6113 @Override 6114 public void purgeResources() { 6115 super.purgeResources(); 6116 if (mPicture != null && 6117 mPicture.isMutable() && 6118 mPicture.getAllocationByteCount() >= MIN_ASHMEM_BITMAP_SIZE) { 6119 mPicture = mPicture.createAshmemBitmap(); 6120 } 6121 if (mBigLargeIcon != null) { 6122 mBigLargeIcon.convertToAshmem(); 6123 } 6124 } 6125 6126 /** 6127 * @hide 6128 */ 6129 @Override 6130 public void reduceImageSizes(Context context) { 6131 super.reduceImageSizes(context); 6132 Resources resources = context.getResources(); 6133 boolean isLowRam = ActivityManager.isLowRamDeviceStatic(); 6134 if (mPicture != null) { 6135 int maxPictureWidth = resources.getDimensionPixelSize(isLowRam 6136 ? R.dimen.notification_big_picture_max_height_low_ram 6137 : R.dimen.notification_big_picture_max_height); 6138 int maxPictureHeight = resources.getDimensionPixelSize(isLowRam 6139 ? R.dimen.notification_big_picture_max_width_low_ram 6140 : R.dimen.notification_big_picture_max_width); 6141 mPicture = Icon.scaleDownIfNecessary(mPicture, maxPictureWidth, maxPictureHeight); 6142 } 6143 if (mBigLargeIcon != null) { 6144 int rightIconSize = resources.getDimensionPixelSize(isLowRam 6145 ? R.dimen.notification_right_icon_size_low_ram 6146 : R.dimen.notification_right_icon_size); 6147 mBigLargeIcon.scaleDownIfNecessary(rightIconSize, rightIconSize); 6148 } 6149 } 6150 6151 /** 6152 * @hide 6153 */ 6154 public RemoteViews makeBigContentView() { 6155 // Replace mN.mLargeIcon with mBigLargeIcon if mBigLargeIconSet 6156 // This covers the following cases: 6157 // 1. mBigLargeIconSet -> mBigLargeIcon (null or non-null) applies, overrides 6158 // mN.mLargeIcon 6159 // 2. !mBigLargeIconSet -> mN.mLargeIcon applies 6160 Icon oldLargeIcon = null; 6161 Bitmap largeIconLegacy = null; 6162 if (mBigLargeIconSet) { 6163 oldLargeIcon = mBuilder.mN.mLargeIcon; 6164 mBuilder.mN.mLargeIcon = mBigLargeIcon; 6165 // The legacy largeIcon might not allow us to clear the image, as it's taken in 6166 // replacement if the other one is null. Because we're restoring these legacy icons 6167 // for old listeners, this is in general non-null. 6168 largeIconLegacy = mBuilder.mN.largeIcon; 6169 mBuilder.mN.largeIcon = null; 6170 } 6171 6172 RemoteViews contentView = getStandardView(mBuilder.getBigPictureLayoutResource()); 6173 if (mSummaryTextSet) { 6174 contentView.setTextViewText(R.id.text, mBuilder.processTextSpans( 6175 mBuilder.processLegacyText(mSummaryText))); 6176 mBuilder.setTextViewColorSecondary(contentView, R.id.text); 6177 contentView.setViewVisibility(R.id.text, View.VISIBLE); 6178 } 6179 mBuilder.setContentMinHeight(contentView, mBuilder.mN.hasLargeIcon()); 6180 6181 if (mBigLargeIconSet) { 6182 mBuilder.mN.mLargeIcon = oldLargeIcon; 6183 mBuilder.mN.largeIcon = largeIconLegacy; 6184 } 6185 6186 contentView.setImageViewBitmap(R.id.big_picture, mPicture); 6187 return contentView; 6188 } 6189 6190 /** 6191 * @hide 6192 */ 6193 public void addExtras(Bundle extras) { 6194 super.addExtras(extras); 6195 6196 if (mBigLargeIconSet) { 6197 extras.putParcelable(EXTRA_LARGE_ICON_BIG, mBigLargeIcon); 6198 } 6199 extras.putParcelable(EXTRA_PICTURE, mPicture); 6200 } 6201 6202 /** 6203 * @hide 6204 */ 6205 @Override 6206 protected void restoreFromExtras(Bundle extras) { 6207 super.restoreFromExtras(extras); 6208 6209 if (extras.containsKey(EXTRA_LARGE_ICON_BIG)) { 6210 mBigLargeIconSet = true; 6211 mBigLargeIcon = extras.getParcelable(EXTRA_LARGE_ICON_BIG); 6212 } 6213 mPicture = extras.getParcelable(EXTRA_PICTURE); 6214 } 6215 6216 /** 6217 * @hide 6218 */ 6219 @Override 6220 public boolean hasSummaryInHeader() { 6221 return false; 6222 } 6223 6224 /** 6225 * @hide 6226 */ 6227 @Override 6228 public boolean areNotificationsVisiblyDifferent(Style other) { 6229 if (other == null || getClass() != other.getClass()) { 6230 return true; 6231 } 6232 BigPictureStyle otherS = (BigPictureStyle) other; 6233 return !Objects.equals(getBigPicture(), otherS.getBigPicture()); 6234 } 6235 } 6236 6237 /** 6238 * Helper class for generating large-format notifications that include a lot of text. 6239 * 6240 * Here's how you'd set the <code>BigTextStyle</code> on a notification: 6241 * <pre class="prettyprint"> 6242 * Notification notif = new Notification.Builder(mContext) 6243 * .setContentTitle("New mail from " + sender.toString()) 6244 * .setContentText(subject) 6245 * .setSmallIcon(R.drawable.new_mail) 6246 * .setLargeIcon(aBitmap) 6247 * .setStyle(new Notification.BigTextStyle() 6248 * .bigText(aVeryLongString)) 6249 * .build(); 6250 * </pre> 6251 * 6252 * @see Notification#bigContentView 6253 */ 6254 public static class BigTextStyle extends Style { 6255 6256 private CharSequence mBigText; 6257 6258 public BigTextStyle() { 6259 } 6260 6261 /** 6262 * @deprecated use {@code BigTextStyle()}. 6263 */ 6264 @Deprecated 6265 public BigTextStyle(Builder builder) { 6266 setBuilder(builder); 6267 } 6268 6269 /** 6270 * Overrides ContentTitle in the big form of the template. 6271 * This defaults to the value passed to setContentTitle(). 6272 */ 6273 public BigTextStyle setBigContentTitle(CharSequence title) { 6274 internalSetBigContentTitle(safeCharSequence(title)); 6275 return this; 6276 } 6277 6278 /** 6279 * Set the first line of text after the detail section in the big form of the template. 6280 */ 6281 public BigTextStyle setSummaryText(CharSequence cs) { 6282 internalSetSummaryText(safeCharSequence(cs)); 6283 return this; 6284 } 6285 6286 /** 6287 * Provide the longer text to be displayed in the big form of the 6288 * template in place of the content text. 6289 */ 6290 public BigTextStyle bigText(CharSequence cs) { 6291 mBigText = safeCharSequence(cs); 6292 return this; 6293 } 6294 6295 /** 6296 * @hide 6297 */ 6298 public CharSequence getBigText() { 6299 return mBigText; 6300 } 6301 6302 /** 6303 * @hide 6304 */ 6305 public void addExtras(Bundle extras) { 6306 super.addExtras(extras); 6307 6308 extras.putCharSequence(EXTRA_BIG_TEXT, mBigText); 6309 } 6310 6311 /** 6312 * @hide 6313 */ 6314 @Override 6315 protected void restoreFromExtras(Bundle extras) { 6316 super.restoreFromExtras(extras); 6317 6318 mBigText = extras.getCharSequence(EXTRA_BIG_TEXT); 6319 } 6320 6321 /** 6322 * @param increasedHeight true if this layout be created with an increased height. 6323 * 6324 * @hide 6325 */ 6326 @Override 6327 public RemoteViews makeContentView(boolean increasedHeight) { 6328 if (increasedHeight) { 6329 mBuilder.mOriginalActions = mBuilder.mActions; 6330 mBuilder.mActions = new ArrayList<>(); 6331 RemoteViews remoteViews = makeBigContentView(); 6332 mBuilder.mActions = mBuilder.mOriginalActions; 6333 mBuilder.mOriginalActions = null; 6334 return remoteViews; 6335 } 6336 return super.makeContentView(increasedHeight); 6337 } 6338 6339 /** 6340 * @hide 6341 */ 6342 @Override 6343 public RemoteViews makeHeadsUpContentView(boolean increasedHeight) { 6344 if (increasedHeight && mBuilder.mActions.size() > 0) { 6345 return makeBigContentView(); 6346 } 6347 return super.makeHeadsUpContentView(increasedHeight); 6348 } 6349 6350 /** 6351 * @hide 6352 */ 6353 public RemoteViews makeBigContentView() { 6354 6355 // Nasty 6356 CharSequence text = mBuilder.getAllExtras().getCharSequence(EXTRA_TEXT); 6357 mBuilder.getAllExtras().putCharSequence(EXTRA_TEXT, null); 6358 6359 RemoteViews contentView = getStandardView(mBuilder.getBigTextLayoutResource()); 6360 6361 mBuilder.getAllExtras().putCharSequence(EXTRA_TEXT, text); 6362 6363 CharSequence bigTextText = mBuilder.processLegacyText(mBigText); 6364 if (TextUtils.isEmpty(bigTextText)) { 6365 // In case the bigtext is null / empty fall back to the normal text to avoid a weird 6366 // experience 6367 bigTextText = mBuilder.processLegacyText(text); 6368 } 6369 applyBigTextContentView(mBuilder, contentView, bigTextText); 6370 6371 return contentView; 6372 } 6373 6374 /** 6375 * @hide 6376 */ 6377 @Override 6378 public boolean areNotificationsVisiblyDifferent(Style other) { 6379 if (other == null || getClass() != other.getClass()) { 6380 return true; 6381 } 6382 BigTextStyle newS = (BigTextStyle) other; 6383 return !Objects.equals(getBigText(), newS.getBigText()); 6384 } 6385 6386 static void applyBigTextContentView(Builder builder, 6387 RemoteViews contentView, CharSequence bigTextText) { 6388 contentView.setTextViewText(R.id.big_text, builder.processTextSpans(bigTextText)); 6389 builder.setTextViewColorSecondary(contentView, R.id.big_text); 6390 contentView.setViewVisibility(R.id.big_text, 6391 TextUtils.isEmpty(bigTextText) ? View.GONE : View.VISIBLE); 6392 contentView.setBoolean(R.id.big_text, "setHasImage", builder.mN.hasLargeIcon()); 6393 } 6394 } 6395 6396 /** 6397 * Helper class for generating large-format notifications that include multiple back-and-forth 6398 * messages of varying types between any number of people. 6399 * 6400 * <br> 6401 * If the platform does not provide large-format notifications, this method has no effect. The 6402 * user will always see the normal notification view. 6403 * <br> 6404 * This class is a "rebuilder": It attaches to a Builder object and modifies its behavior, like 6405 * so: 6406 * <pre class="prettyprint"> 6407 * 6408 * Notification noti = new Notification.Builder() 6409 * .setContentTitle("2 new messages wtih " + sender.toString()) 6410 * .setContentText(subject) 6411 * .setSmallIcon(R.drawable.new_message) 6412 * .setLargeIcon(aBitmap) 6413 * .setStyle(new Notification.MessagingStyle(resources.getString(R.string.reply_name)) 6414 * .addMessage(messages[0].getText(), messages[0].getTime(), messages[0].getSender()) 6415 * .addMessage(messages[1].getText(), messages[1].getTime(), messages[1].getSender())) 6416 * .build(); 6417 * </pre> 6418 */ 6419 public static class MessagingStyle extends Style { 6420 6421 /** 6422 * The maximum number of messages that will be retained in the Notification itself (the 6423 * number displayed is up to the platform). 6424 */ 6425 public static final int MAXIMUM_RETAINED_MESSAGES = 25; 6426 6427 @NonNull Person mUser; 6428 @Nullable CharSequence mConversationTitle; 6429 List<Message> mMessages = new ArrayList<>(); 6430 List<Message> mHistoricMessages = new ArrayList<>(); 6431 boolean mIsGroupConversation; 6432 6433 MessagingStyle() { 6434 } 6435 6436 /** 6437 * @param userDisplayName Required - the name to be displayed for any replies sent by the 6438 * user before the posting app reposts the notification with those messages after they've 6439 * been actually sent and in previous messages sent by the user added in 6440 * {@link #addMessage(Notification.MessagingStyle.Message)} 6441 * 6442 * @deprecated use {@code MessagingStyle(Person)} 6443 */ 6444 public MessagingStyle(@NonNull CharSequence userDisplayName) { 6445 this(new Person.Builder().setName(userDisplayName).build()); 6446 } 6447 6448 /** 6449 * @param user Required - The person displayed for any messages that are sent by the 6450 * user. Any messages added with {@link #addMessage(Notification.MessagingStyle.Message)} 6451 * who don't have a Person associated with it will be displayed as if they were sent 6452 * by this user. The user also needs to have a valid name associated with it, which will 6453 * be enforced starting in Android P. 6454 */ 6455 public MessagingStyle(@NonNull Person user) { 6456 mUser = user; 6457 } 6458 6459 /** 6460 * Validate that this style was properly composed. This is called at build time. 6461 * @hide 6462 */ 6463 @Override 6464 public void validate(Context context) { 6465 super.validate(context); 6466 if (context.getApplicationInfo().targetSdkVersion 6467 >= Build.VERSION_CODES.P && (mUser == null || mUser.getName() == null)) { 6468 throw new RuntimeException("User must be valid and have a name."); 6469 } 6470 } 6471 6472 /** 6473 * @return the the text that should be displayed in the statusBar when heads upped. 6474 * If {@code null} is returned, the default implementation will be used. 6475 * 6476 * @hide 6477 */ 6478 @Override 6479 public CharSequence getHeadsUpStatusBarText() { 6480 CharSequence conversationTitle = !TextUtils.isEmpty(super.mBigContentTitle) 6481 ? super.mBigContentTitle 6482 : mConversationTitle; 6483 if (!TextUtils.isEmpty(conversationTitle) && !hasOnlyWhiteSpaceSenders()) { 6484 return conversationTitle; 6485 } 6486 return null; 6487 } 6488 6489 /** 6490 * @return the user to be displayed for any replies sent by the user 6491 */ 6492 @NonNull 6493 public Person getUser() { 6494 return mUser; 6495 } 6496 6497 /** 6498 * Returns the name to be displayed for any replies sent by the user 6499 * 6500 * @deprecated use {@link #getUser()} instead 6501 */ 6502 public CharSequence getUserDisplayName() { 6503 return mUser.getName(); 6504 } 6505 6506 /** 6507 * Sets the title to be displayed on this conversation. May be set to {@code null}. 6508 * 6509 * <p>This API's behavior was changed in SDK version {@link Build.VERSION_CODES#P}. If your 6510 * application's target version is less than {@link Build.VERSION_CODES#P}, setting a 6511 * conversation title to a non-null value will make {@link #isGroupConversation()} return 6512 * {@code true} and passing {@code null} will make it return {@code false}. In 6513 * {@link Build.VERSION_CODES#P} and beyond, use {@link #setGroupConversation(boolean)} 6514 * to set group conversation status. 6515 * 6516 * @param conversationTitle Title displayed for this conversation 6517 * @return this object for method chaining 6518 */ 6519 public MessagingStyle setConversationTitle(@Nullable CharSequence conversationTitle) { 6520 mConversationTitle = conversationTitle; 6521 return this; 6522 } 6523 6524 /** 6525 * Return the title to be displayed on this conversation. May return {@code null}. 6526 */ 6527 @Nullable 6528 public CharSequence getConversationTitle() { 6529 return mConversationTitle; 6530 } 6531 6532 /** 6533 * Adds a message for display by this notification. Convenience call for a simple 6534 * {@link Message} in {@link #addMessage(Notification.MessagingStyle.Message)}. 6535 * @param text A {@link CharSequence} to be displayed as the message content 6536 * @param timestamp Time at which the message arrived 6537 * @param sender A {@link CharSequence} to be used for displaying the name of the 6538 * sender. Should be <code>null</code> for messages by the current user, in which case 6539 * the platform will insert {@link #getUserDisplayName()}. 6540 * Should be unique amongst all individuals in the conversation, and should be 6541 * consistent during re-posts of the notification. 6542 * 6543 * @see Message#Message(CharSequence, long, CharSequence) 6544 * 6545 * @return this object for method chaining 6546 * 6547 * @deprecated use {@link #addMessage(CharSequence, long, Person)} 6548 */ 6549 public MessagingStyle addMessage(CharSequence text, long timestamp, CharSequence sender) { 6550 return addMessage(text, timestamp, 6551 sender == null ? null : new Person.Builder().setName(sender).build()); 6552 } 6553 6554 /** 6555 * Adds a message for display by this notification. Convenience call for a simple 6556 * {@link Message} in {@link #addMessage(Notification.MessagingStyle.Message)}. 6557 * @param text A {@link CharSequence} to be displayed as the message content 6558 * @param timestamp Time at which the message arrived 6559 * @param sender The {@link Person} who sent the message. 6560 * Should be <code>null</code> for messages by the current user, in which case 6561 * the platform will insert the user set in {@code MessagingStyle(Person)}. 6562 * 6563 * @see Message#Message(CharSequence, long, CharSequence) 6564 * 6565 * @return this object for method chaining 6566 */ 6567 public MessagingStyle addMessage(@NonNull CharSequence text, long timestamp, 6568 @Nullable Person sender) { 6569 return addMessage(new Message(text, timestamp, sender)); 6570 } 6571 6572 /** 6573 * Adds a {@link Message} for display in this notification. 6574 * 6575 * <p>The messages should be added in chronologic order, i.e. the oldest first, 6576 * the newest last. 6577 * 6578 * @param message The {@link Message} to be displayed 6579 * @return this object for method chaining 6580 */ 6581 public MessagingStyle addMessage(Message message) { 6582 mMessages.add(message); 6583 if (mMessages.size() > MAXIMUM_RETAINED_MESSAGES) { 6584 mMessages.remove(0); 6585 } 6586 return this; 6587 } 6588 6589 /** 6590 * Adds a {@link Message} for historic context in this notification. 6591 * 6592 * <p>Messages should be added as historic if they are not the main subject of the 6593 * notification but may give context to a conversation. The system may choose to present 6594 * them only when relevant, e.g. when replying to a message through a {@link RemoteInput}. 6595 * 6596 * <p>The messages should be added in chronologic order, i.e. the oldest first, 6597 * the newest last. 6598 * 6599 * @param message The historic {@link Message} to be added 6600 * @return this object for method chaining 6601 */ 6602 public MessagingStyle addHistoricMessage(Message message) { 6603 mHistoricMessages.add(message); 6604 if (mHistoricMessages.size() > MAXIMUM_RETAINED_MESSAGES) { 6605 mHistoricMessages.remove(0); 6606 } 6607 return this; 6608 } 6609 6610 /** 6611 * Gets the list of {@code Message} objects that represent the notification 6612 */ 6613 public List<Message> getMessages() { 6614 return mMessages; 6615 } 6616 6617 /** 6618 * Gets the list of historic {@code Message}s in the notification. 6619 */ 6620 public List<Message> getHistoricMessages() { 6621 return mHistoricMessages; 6622 } 6623 6624 /** 6625 * Sets whether this conversation notification represents a group. 6626 * 6627 * @param isGroupConversation {@code true} if the conversation represents a group, 6628 * {@code false} otherwise. 6629 * @return this object for method chaining 6630 */ 6631 public MessagingStyle setGroupConversation(boolean isGroupConversation) { 6632 mIsGroupConversation = isGroupConversation; 6633 return this; 6634 } 6635 6636 /** 6637 * Returns {@code true} if this notification represents a group conversation, otherwise 6638 * {@code false}. 6639 * 6640 * <p> If the application that generated this {@link MessagingStyle} targets an SDK version 6641 * less than {@link Build.VERSION_CODES#P}, this method becomes dependent on whether or 6642 * not the conversation title is set; returning {@code true} if the conversation title is 6643 * a non-null value, or {@code false} otherwise. From {@link Build.VERSION_CODES#P} forward, 6644 * this method returns what's set by {@link #setGroupConversation(boolean)} allowing for 6645 * named, non-group conversations. 6646 * 6647 * @see #setConversationTitle(CharSequence) 6648 */ 6649 public boolean isGroupConversation() { 6650 // When target SDK version is < P, a non-null conversation title dictates if this is 6651 // as group conversation. 6652 if (mBuilder != null 6653 && mBuilder.mContext.getApplicationInfo().targetSdkVersion 6654 < Build.VERSION_CODES.P) { 6655 return mConversationTitle != null; 6656 } 6657 6658 return mIsGroupConversation; 6659 } 6660 6661 /** 6662 * @hide 6663 */ 6664 @Override 6665 public void addExtras(Bundle extras) { 6666 super.addExtras(extras); 6667 if (mUser != null) { 6668 // For legacy usages 6669 extras.putCharSequence(EXTRA_SELF_DISPLAY_NAME, mUser.getName()); 6670 extras.putParcelable(EXTRA_MESSAGING_PERSON, mUser); 6671 } 6672 if (mConversationTitle != null) { 6673 extras.putCharSequence(EXTRA_CONVERSATION_TITLE, mConversationTitle); 6674 } 6675 if (!mMessages.isEmpty()) { extras.putParcelableArray(EXTRA_MESSAGES, 6676 Message.getBundleArrayForMessages(mMessages)); 6677 } 6678 if (!mHistoricMessages.isEmpty()) { extras.putParcelableArray(EXTRA_HISTORIC_MESSAGES, 6679 Message.getBundleArrayForMessages(mHistoricMessages)); 6680 } 6681 6682 fixTitleAndTextExtras(extras); 6683 extras.putBoolean(EXTRA_IS_GROUP_CONVERSATION, mIsGroupConversation); 6684 } 6685 6686 private void fixTitleAndTextExtras(Bundle extras) { 6687 Message m = findLatestIncomingMessage(); 6688 CharSequence text = (m == null) ? null : m.mText; 6689 CharSequence sender = m == null ? null 6690 : m.mSender == null || TextUtils.isEmpty(m.mSender.getName()) 6691 ? mUser.getName() : m.mSender.getName(); 6692 CharSequence title; 6693 if (!TextUtils.isEmpty(mConversationTitle)) { 6694 if (!TextUtils.isEmpty(sender)) { 6695 BidiFormatter bidi = BidiFormatter.getInstance(); 6696 title = mBuilder.mContext.getString( 6697 com.android.internal.R.string.notification_messaging_title_template, 6698 bidi.unicodeWrap(mConversationTitle), bidi.unicodeWrap(sender)); 6699 } else { 6700 title = mConversationTitle; 6701 } 6702 } else { 6703 title = sender; 6704 } 6705 6706 if (title != null) { 6707 extras.putCharSequence(EXTRA_TITLE, title); 6708 } 6709 if (text != null) { 6710 extras.putCharSequence(EXTRA_TEXT, text); 6711 } 6712 } 6713 6714 /** 6715 * @hide 6716 */ 6717 @Override 6718 protected void restoreFromExtras(Bundle extras) { 6719 super.restoreFromExtras(extras); 6720 6721 mUser = extras.getParcelable(EXTRA_MESSAGING_PERSON); 6722 if (mUser == null) { 6723 CharSequence displayName = extras.getCharSequence(EXTRA_SELF_DISPLAY_NAME); 6724 mUser = new Person.Builder().setName(displayName).build(); 6725 } 6726 mConversationTitle = extras.getCharSequence(EXTRA_CONVERSATION_TITLE); 6727 Parcelable[] messages = extras.getParcelableArray(EXTRA_MESSAGES); 6728 mMessages = Message.getMessagesFromBundleArray(messages); 6729 Parcelable[] histMessages = extras.getParcelableArray(EXTRA_HISTORIC_MESSAGES); 6730 mHistoricMessages = Message.getMessagesFromBundleArray(histMessages); 6731 mIsGroupConversation = extras.getBoolean(EXTRA_IS_GROUP_CONVERSATION); 6732 } 6733 6734 /** 6735 * @hide 6736 */ 6737 @Override 6738 public RemoteViews makeContentView(boolean increasedHeight) { 6739 mBuilder.mOriginalActions = mBuilder.mActions; 6740 mBuilder.mActions = new ArrayList<>(); 6741 RemoteViews remoteViews = makeMessagingView(true /* displayImagesAtEnd */, 6742 true /* showReplyIcon */); 6743 mBuilder.mActions = mBuilder.mOriginalActions; 6744 mBuilder.mOriginalActions = null; 6745 return remoteViews; 6746 } 6747 6748 /** 6749 * @hide 6750 */ 6751 @Override 6752 public boolean areNotificationsVisiblyDifferent(Style other) { 6753 if (other == null || getClass() != other.getClass()) { 6754 return true; 6755 } 6756 MessagingStyle newS = (MessagingStyle) other; 6757 List<MessagingStyle.Message> oldMs = getMessages(); 6758 List<MessagingStyle.Message> newMs = newS.getMessages(); 6759 6760 if (oldMs == null) { 6761 oldMs = new ArrayList<>(); 6762 } 6763 if (newMs == null) { 6764 newMs = new ArrayList<>(); 6765 } 6766 6767 int n = oldMs.size(); 6768 if (n != newMs.size()) { 6769 return true; 6770 } 6771 for (int i = 0; i < n; i++) { 6772 MessagingStyle.Message oldM = oldMs.get(i); 6773 MessagingStyle.Message newM = newMs.get(i); 6774 if (!Objects.equals(oldM.getText(), newM.getText())) { 6775 return true; 6776 } 6777 if (!Objects.equals(oldM.getDataUri(), newM.getDataUri())) { 6778 return true; 6779 } 6780 CharSequence oldSender = oldM.getSenderPerson() == null ? oldM.getSender() 6781 : oldM.getSenderPerson().getName(); 6782 CharSequence newSender = newM.getSenderPerson() == null ? newM.getSender() 6783 : newM.getSenderPerson().getName(); 6784 if (!Objects.equals(oldSender, newSender)) { 6785 return true; 6786 } 6787 6788 String oldKey = oldM.getSenderPerson() == null 6789 ? null : oldM.getSenderPerson().getKey(); 6790 String newKey = newM.getSenderPerson() == null 6791 ? null : newM.getSenderPerson().getKey(); 6792 if (!Objects.equals(oldKey, newKey)) { 6793 return true; 6794 } 6795 // Other fields (like timestamp) intentionally excluded 6796 } 6797 return false; 6798 } 6799 6800 private Message findLatestIncomingMessage() { 6801 return findLatestIncomingMessage(mMessages); 6802 } 6803 6804 /** 6805 * @hide 6806 */ 6807 @Nullable 6808 public static Message findLatestIncomingMessage( 6809 List<Message> messages) { 6810 for (int i = messages.size() - 1; i >= 0; i--) { 6811 Message m = messages.get(i); 6812 // Incoming messages have a non-empty sender. 6813 if (m.mSender != null && !TextUtils.isEmpty(m.mSender.getName())) { 6814 return m; 6815 } 6816 } 6817 if (!messages.isEmpty()) { 6818 // No incoming messages, fall back to outgoing message 6819 return messages.get(messages.size() - 1); 6820 } 6821 return null; 6822 } 6823 6824 /** 6825 * @hide 6826 */ 6827 @Override 6828 public RemoteViews makeBigContentView() { 6829 return makeMessagingView(false /* displayImagesAtEnd */, false /* showReplyIcon */); 6830 } 6831 6832 /** 6833 * Create a messaging layout. 6834 * 6835 * @param displayImagesAtEnd should images be displayed at the end of the content instead 6836 * of inline. 6837 * @param showReplyIcon Should the reply affordance be shown at the end of the notification 6838 * @return the created remoteView. 6839 */ 6840 @NonNull 6841 private RemoteViews makeMessagingView(boolean displayImagesAtEnd, boolean showReplyIcon) { 6842 CharSequence conversationTitle = !TextUtils.isEmpty(super.mBigContentTitle) 6843 ? super.mBigContentTitle 6844 : mConversationTitle; 6845 boolean isOneToOne = TextUtils.isEmpty(conversationTitle); 6846 CharSequence nameReplacement = null; 6847 if (hasOnlyWhiteSpaceSenders()) { 6848 isOneToOne = true; 6849 nameReplacement = conversationTitle; 6850 conversationTitle = null; 6851 } 6852 boolean hideLargeIcon = !showReplyIcon || isOneToOne; 6853 RemoteViews contentView = mBuilder.applyStandardTemplateWithActions( 6854 mBuilder.getMessagingLayoutResource(), 6855 mBuilder.mParams.reset().hasProgress(false).title(conversationTitle).text(null) 6856 .hideLargeIcon(hideLargeIcon) 6857 .headerTextSecondary(conversationTitle) 6858 .alwaysShowReply(showReplyIcon)); 6859 addExtras(mBuilder.mN.extras); 6860 // also update the end margin if there is an image 6861 int endMargin = R.dimen.notification_content_margin_end; 6862 if (showReplyIcon) { 6863 endMargin = R.dimen.notification_content_plus_picture_margin_end; 6864 } 6865 contentView.setViewLayoutMarginEndDimen(R.id.notification_main_column, endMargin); 6866 contentView.setInt(R.id.status_bar_latest_event_content, "setLayoutColor", 6867 mBuilder.resolveContrastColor()); 6868 contentView.setBoolean(R.id.status_bar_latest_event_content, "setDisplayImagesAtEnd", 6869 displayImagesAtEnd); 6870 contentView.setIcon(R.id.status_bar_latest_event_content, "setLargeIcon", 6871 mBuilder.mN.mLargeIcon); 6872 contentView.setCharSequence(R.id.status_bar_latest_event_content, "setNameReplacement", 6873 nameReplacement); 6874 contentView.setBoolean(R.id.status_bar_latest_event_content, "setIsOneToOne", 6875 isOneToOne); 6876 contentView.setBundle(R.id.status_bar_latest_event_content, "setData", 6877 mBuilder.mN.extras); 6878 return contentView; 6879 } 6880 6881 private boolean hasOnlyWhiteSpaceSenders() { 6882 for (int i = 0; i < mMessages.size(); i++) { 6883 Message m = mMessages.get(i); 6884 Person sender = m.getSenderPerson(); 6885 if (sender != null && !isWhiteSpace(sender.getName())) { 6886 return false; 6887 } 6888 } 6889 return true; 6890 } 6891 6892 private boolean isWhiteSpace(CharSequence sender) { 6893 if (TextUtils.isEmpty(sender)) { 6894 return true; 6895 } 6896 if (sender.toString().matches("^\\s*$")) { 6897 return true; 6898 } 6899 // Let's check if we only have 0 whitespace chars. Some apps did this as a workaround 6900 // For the presentation that we had. 6901 for (int i = 0; i < sender.length(); i++) { 6902 char c = sender.charAt(i); 6903 if (c != '\u200B') { 6904 return false; 6905 } 6906 } 6907 return true; 6908 } 6909 6910 private CharSequence createConversationTitleFromMessages() { 6911 ArraySet<CharSequence> names = new ArraySet<>(); 6912 for (int i = 0; i < mMessages.size(); i++) { 6913 Message m = mMessages.get(i); 6914 Person sender = m.getSenderPerson(); 6915 if (sender != null) { 6916 names.add(sender.getName()); 6917 } 6918 } 6919 SpannableStringBuilder title = new SpannableStringBuilder(); 6920 int size = names.size(); 6921 for (int i = 0; i < size; i++) { 6922 CharSequence name = names.valueAt(i); 6923 if (!TextUtils.isEmpty(title)) { 6924 title.append(", "); 6925 } 6926 title.append(BidiFormatter.getInstance().unicodeWrap(name)); 6927 } 6928 return title; 6929 } 6930 6931 /** 6932 * @hide 6933 */ 6934 @Override 6935 public RemoteViews makeHeadsUpContentView(boolean increasedHeight) { 6936 RemoteViews remoteViews = makeMessagingView(true /* displayImagesAtEnd */, 6937 false /* showReplyIcon */); 6938 remoteViews.setInt(R.id.notification_messaging, "setMaxDisplayedLines", 1); 6939 return remoteViews; 6940 } 6941 6942 private static TextAppearanceSpan makeFontColorSpan(int color) { 6943 return new TextAppearanceSpan(null, 0, 0, 6944 ColorStateList.valueOf(color), null); 6945 } 6946 6947 public static final class Message { 6948 6949 static final String KEY_TEXT = "text"; 6950 static final String KEY_TIMESTAMP = "time"; 6951 static final String KEY_SENDER = "sender"; 6952 static final String KEY_SENDER_PERSON = "sender_person"; 6953 static final String KEY_DATA_MIME_TYPE = "type"; 6954 static final String KEY_DATA_URI= "uri"; 6955 static final String KEY_EXTRAS_BUNDLE = "extras"; 6956 6957 private final CharSequence mText; 6958 private final long mTimestamp; 6959 @Nullable 6960 private final Person mSender; 6961 6962 private Bundle mExtras = new Bundle(); 6963 private String mDataMimeType; 6964 private Uri mDataUri; 6965 6966 /** 6967 * Constructor 6968 * @param text A {@link CharSequence} to be displayed as the message content 6969 * @param timestamp Time at which the message arrived 6970 * @param sender A {@link CharSequence} to be used for displaying the name of the 6971 * sender. Should be <code>null</code> for messages by the current user, in which case 6972 * the platform will insert {@link MessagingStyle#getUserDisplayName()}. 6973 * Should be unique amongst all individuals in the conversation, and should be 6974 * consistent during re-posts of the notification. 6975 * 6976 * @deprecated use {@code Message(CharSequence, long, Person)} 6977 */ 6978 public Message(CharSequence text, long timestamp, CharSequence sender){ 6979 this(text, timestamp, sender == null ? null 6980 : new Person.Builder().setName(sender).build()); 6981 } 6982 6983 /** 6984 * Constructor 6985 * @param text A {@link CharSequence} to be displayed as the message content 6986 * @param timestamp Time at which the message arrived 6987 * @param sender The {@link Person} who sent the message. 6988 * Should be <code>null</code> for messages by the current user, in which case 6989 * the platform will insert the user set in {@code MessagingStyle(Person)}. 6990 * <p> 6991 * The person provided should contain an Icon, set with 6992 * {@link Person.Builder#setIcon(Icon)} and also have a name provided 6993 * with {@link Person.Builder#setName(CharSequence)}. If multiple users have the same 6994 * name, consider providing a key with {@link Person.Builder#setKey(String)} in order 6995 * to differentiate between the different users. 6996 * </p> 6997 */ 6998 public Message(@NonNull CharSequence text, long timestamp, @Nullable Person sender) { 6999 mText = text; 7000 mTimestamp = timestamp; 7001 mSender = sender; 7002 } 7003 7004 /** 7005 * Sets a binary blob of data and an associated MIME type for a message. In the case 7006 * where the platform doesn't support the MIME type, the original text provided in the 7007 * constructor will be used. 7008 * @param dataMimeType The MIME type of the content. See 7009 * <a href="{@docRoot}notifications/messaging.html"> for the list of supported MIME 7010 * types on Android and Android Wear. 7011 * @param dataUri The uri containing the content whose type is given by the MIME type. 7012 * <p class="note"> 7013 * <ol> 7014 * <li>Notification Listeners including the System UI need permission to access the 7015 * data the Uri points to. The recommended ways to do this are:</li> 7016 * <li>Store the data in your own ContentProvider, making sure that other apps have 7017 * the correct permission to access your provider. The preferred mechanism for 7018 * providing access is to use per-URI permissions which are temporary and only 7019 * grant access to the receiving application. An easy way to create a 7020 * ContentProvider like this is to use the FileProvider helper class.</li> 7021 * <li>Use the system MediaStore. The MediaStore is primarily aimed at video, audio 7022 * and image MIME types, however beginning with Android 3.0 (API level 11) it can 7023 * also store non-media types (see MediaStore.Files for more info). Files can be 7024 * inserted into the MediaStore using scanFile() after which a content:// style 7025 * Uri suitable for sharing is passed to the provided onScanCompleted() callback. 7026 * Note that once added to the system MediaStore the content is accessible to any 7027 * app on the device.</li> 7028 * </ol> 7029 * @return this object for method chaining 7030 */ 7031 public Message setData(String dataMimeType, Uri dataUri) { 7032 mDataMimeType = dataMimeType; 7033 mDataUri = dataUri; 7034 return this; 7035 } 7036 7037 /** 7038 * Get the text to be used for this message, or the fallback text if a type and content 7039 * Uri have been set 7040 */ 7041 public CharSequence getText() { 7042 return mText; 7043 } 7044 7045 /** 7046 * Get the time at which this message arrived 7047 */ 7048 public long getTimestamp() { 7049 return mTimestamp; 7050 } 7051 7052 /** 7053 * Get the extras Bundle for this message. 7054 */ 7055 public Bundle getExtras() { 7056 return mExtras; 7057 } 7058 7059 /** 7060 * Get the text used to display the contact's name in the messaging experience 7061 * 7062 * @deprecated use {@link #getSenderPerson()} 7063 */ 7064 public CharSequence getSender() { 7065 return mSender == null ? null : mSender.getName(); 7066 } 7067 7068 /** 7069 * Get the sender associated with this message. 7070 */ 7071 @Nullable 7072 public Person getSenderPerson() { 7073 return mSender; 7074 } 7075 7076 /** 7077 * Get the MIME type of the data pointed to by the Uri 7078 */ 7079 public String getDataMimeType() { 7080 return mDataMimeType; 7081 } 7082 7083 /** 7084 * Get the the Uri pointing to the content of the message. Can be null, in which case 7085 * {@see #getText()} is used. 7086 */ 7087 public Uri getDataUri() { 7088 return mDataUri; 7089 } 7090 7091 private Bundle toBundle() { 7092 Bundle bundle = new Bundle(); 7093 if (mText != null) { 7094 bundle.putCharSequence(KEY_TEXT, mText); 7095 } 7096 bundle.putLong(KEY_TIMESTAMP, mTimestamp); 7097 if (mSender != null) { 7098 // Legacy listeners need this 7099 bundle.putCharSequence(KEY_SENDER, mSender.getName()); 7100 bundle.putParcelable(KEY_SENDER_PERSON, mSender); 7101 } 7102 if (mDataMimeType != null) { 7103 bundle.putString(KEY_DATA_MIME_TYPE, mDataMimeType); 7104 } 7105 if (mDataUri != null) { 7106 bundle.putParcelable(KEY_DATA_URI, mDataUri); 7107 } 7108 if (mExtras != null) { 7109 bundle.putBundle(KEY_EXTRAS_BUNDLE, mExtras); 7110 } 7111 return bundle; 7112 } 7113 7114 static Bundle[] getBundleArrayForMessages(List<Message> messages) { 7115 Bundle[] bundles = new Bundle[messages.size()]; 7116 final int N = messages.size(); 7117 for (int i = 0; i < N; i++) { 7118 bundles[i] = messages.get(i).toBundle(); 7119 } 7120 return bundles; 7121 } 7122 7123 /** 7124 * @return A list of messages read from the bundles. 7125 * 7126 * @hide 7127 */ 7128 public static List<Message> getMessagesFromBundleArray(Parcelable[] bundles) { 7129 if (bundles == null) { 7130 return new ArrayList<>(); 7131 } 7132 List<Message> messages = new ArrayList<>(bundles.length); 7133 for (int i = 0; i < bundles.length; i++) { 7134 if (bundles[i] instanceof Bundle) { 7135 Message message = getMessageFromBundle((Bundle)bundles[i]); 7136 if (message != null) { 7137 messages.add(message); 7138 } 7139 } 7140 } 7141 return messages; 7142 } 7143 7144 static Message getMessageFromBundle(Bundle bundle) { 7145 try { 7146 if (!bundle.containsKey(KEY_TEXT) || !bundle.containsKey(KEY_TIMESTAMP)) { 7147 return null; 7148 } else { 7149 7150 Person senderPerson = bundle.getParcelable(KEY_SENDER_PERSON); 7151 if (senderPerson == null) { 7152 // Legacy apps that use compat don't actually provide the sender objects 7153 // We need to fix the compat version to provide people / use 7154 // the native api instead 7155 CharSequence senderName = bundle.getCharSequence(KEY_SENDER); 7156 if (senderName != null) { 7157 senderPerson = new Person.Builder().setName(senderName).build(); 7158 } 7159 } 7160 Message message = new Message(bundle.getCharSequence(KEY_TEXT), 7161 bundle.getLong(KEY_TIMESTAMP), 7162 senderPerson); 7163 if (bundle.containsKey(KEY_DATA_MIME_TYPE) && 7164 bundle.containsKey(KEY_DATA_URI)) { 7165 message.setData(bundle.getString(KEY_DATA_MIME_TYPE), 7166 (Uri) bundle.getParcelable(KEY_DATA_URI)); 7167 } 7168 if (bundle.containsKey(KEY_EXTRAS_BUNDLE)) { 7169 message.getExtras().putAll(bundle.getBundle(KEY_EXTRAS_BUNDLE)); 7170 } 7171 return message; 7172 } 7173 } catch (ClassCastException e) { 7174 return null; 7175 } 7176 } 7177 } 7178 } 7179 7180 /** 7181 * Helper class for generating large-format notifications that include a list of (up to 5) strings. 7182 * 7183 * Here's how you'd set the <code>InboxStyle</code> on a notification: 7184 * <pre class="prettyprint"> 7185 * Notification notif = new Notification.Builder(mContext) 7186 * .setContentTitle("5 New mails from " + sender.toString()) 7187 * .setContentText(subject) 7188 * .setSmallIcon(R.drawable.new_mail) 7189 * .setLargeIcon(aBitmap) 7190 * .setStyle(new Notification.InboxStyle() 7191 * .addLine(str1) 7192 * .addLine(str2) 7193 * .setContentTitle("") 7194 * .setSummaryText("+3 more")) 7195 * .build(); 7196 * </pre> 7197 * 7198 * @see Notification#bigContentView 7199 */ 7200 public static class InboxStyle extends Style { 7201 private ArrayList<CharSequence> mTexts = new ArrayList<CharSequence>(5); 7202 7203 public InboxStyle() { 7204 } 7205 7206 /** 7207 * @deprecated use {@code InboxStyle()}. 7208 */ 7209 @Deprecated 7210 public InboxStyle(Builder builder) { 7211 setBuilder(builder); 7212 } 7213 7214 /** 7215 * Overrides ContentTitle in the big form of the template. 7216 * This defaults to the value passed to setContentTitle(). 7217 */ 7218 public InboxStyle setBigContentTitle(CharSequence title) { 7219 internalSetBigContentTitle(safeCharSequence(title)); 7220 return this; 7221 } 7222 7223 /** 7224 * Set the first line of text after the detail section in the big form of the template. 7225 */ 7226 public InboxStyle setSummaryText(CharSequence cs) { 7227 internalSetSummaryText(safeCharSequence(cs)); 7228 return this; 7229 } 7230 7231 /** 7232 * Append a line to the digest section of the Inbox notification. 7233 */ 7234 public InboxStyle addLine(CharSequence cs) { 7235 mTexts.add(safeCharSequence(cs)); 7236 return this; 7237 } 7238 7239 /** 7240 * @hide 7241 */ 7242 public ArrayList<CharSequence> getLines() { 7243 return mTexts; 7244 } 7245 7246 /** 7247 * @hide 7248 */ 7249 public void addExtras(Bundle extras) { 7250 super.addExtras(extras); 7251 7252 CharSequence[] a = new CharSequence[mTexts.size()]; 7253 extras.putCharSequenceArray(EXTRA_TEXT_LINES, mTexts.toArray(a)); 7254 } 7255 7256 /** 7257 * @hide 7258 */ 7259 @Override 7260 protected void restoreFromExtras(Bundle extras) { 7261 super.restoreFromExtras(extras); 7262 7263 mTexts.clear(); 7264 if (extras.containsKey(EXTRA_TEXT_LINES)) { 7265 Collections.addAll(mTexts, extras.getCharSequenceArray(EXTRA_TEXT_LINES)); 7266 } 7267 } 7268 7269 /** 7270 * @hide 7271 */ 7272 public RemoteViews makeBigContentView() { 7273 // Remove the content text so it disappears unless you have a summary 7274 // Nasty 7275 CharSequence oldBuilderContentText = mBuilder.mN.extras.getCharSequence(EXTRA_TEXT); 7276 mBuilder.getAllExtras().putCharSequence(EXTRA_TEXT, null); 7277 7278 RemoteViews contentView = getStandardView(mBuilder.getInboxLayoutResource()); 7279 7280 mBuilder.getAllExtras().putCharSequence(EXTRA_TEXT, oldBuilderContentText); 7281 7282 int[] rowIds = {R.id.inbox_text0, R.id.inbox_text1, R.id.inbox_text2, R.id.inbox_text3, 7283 R.id.inbox_text4, R.id.inbox_text5, R.id.inbox_text6}; 7284 7285 // Make sure all rows are gone in case we reuse a view. 7286 for (int rowId : rowIds) { 7287 contentView.setViewVisibility(rowId, View.GONE); 7288 } 7289 7290 int i=0; 7291 int topPadding = mBuilder.mContext.getResources().getDimensionPixelSize( 7292 R.dimen.notification_inbox_item_top_padding); 7293 boolean first = true; 7294 int onlyViewId = 0; 7295 int maxRows = rowIds.length; 7296 if (mBuilder.mActions.size() > 0) { 7297 maxRows--; 7298 } 7299 while (i < mTexts.size() && i < maxRows) { 7300 CharSequence str = mTexts.get(i); 7301 if (!TextUtils.isEmpty(str)) { 7302 contentView.setViewVisibility(rowIds[i], View.VISIBLE); 7303 contentView.setTextViewText(rowIds[i], 7304 mBuilder.processTextSpans(mBuilder.processLegacyText(str))); 7305 mBuilder.setTextViewColorSecondary(contentView, rowIds[i]); 7306 contentView.setViewPadding(rowIds[i], 0, topPadding, 0, 0); 7307 handleInboxImageMargin(contentView, rowIds[i], first); 7308 if (first) { 7309 onlyViewId = rowIds[i]; 7310 } else { 7311 onlyViewId = 0; 7312 } 7313 first = false; 7314 } 7315 i++; 7316 } 7317 if (onlyViewId != 0) { 7318 // We only have 1 entry, lets make it look like the normal Text of a Bigtext 7319 topPadding = mBuilder.mContext.getResources().getDimensionPixelSize( 7320 R.dimen.notification_text_margin_top); 7321 contentView.setViewPadding(onlyViewId, 0, topPadding, 0, 0); 7322 } 7323 7324 return contentView; 7325 } 7326 7327 /** 7328 * @hide 7329 */ 7330 @Override 7331 public boolean areNotificationsVisiblyDifferent(Style other) { 7332 if (other == null || getClass() != other.getClass()) { 7333 return true; 7334 } 7335 InboxStyle newS = (InboxStyle) other; 7336 return !Objects.equals(getLines(), newS.getLines()); 7337 } 7338 7339 private void handleInboxImageMargin(RemoteViews contentView, int id, boolean first) { 7340 int endMargin = 0; 7341 if (first) { 7342 final int max = mBuilder.mN.extras.getInt(EXTRA_PROGRESS_MAX, 0); 7343 final boolean ind = mBuilder.mN.extras.getBoolean(EXTRA_PROGRESS_INDETERMINATE); 7344 boolean hasProgress = max != 0 || ind; 7345 if (mBuilder.mN.hasLargeIcon() && !hasProgress) { 7346 endMargin = R.dimen.notification_content_picture_margin; 7347 } 7348 } 7349 contentView.setViewLayoutMarginEndDimen(id, endMargin); 7350 } 7351 } 7352 7353 /** 7354 * Notification style for media playback notifications. 7355 * 7356 * In the expanded form, {@link Notification#bigContentView}, up to 5 7357 * {@link Notification.Action}s specified with 7358 * {@link Notification.Builder#addAction(Action) addAction} will be 7359 * shown as icon-only pushbuttons, suitable for transport controls. The Bitmap given to 7360 * {@link Notification.Builder#setLargeIcon(android.graphics.Bitmap) setLargeIcon()} will be 7361 * treated as album artwork. 7362 * <p> 7363 * Unlike the other styles provided here, MediaStyle can also modify the standard-size 7364 * {@link Notification#contentView}; by providing action indices to 7365 * {@link #setShowActionsInCompactView(int...)} you can promote up to 3 actions to be displayed 7366 * in the standard view alongside the usual content. 7367 * <p> 7368 * Notifications created with MediaStyle will have their category set to 7369 * {@link Notification#CATEGORY_TRANSPORT CATEGORY_TRANSPORT} unless you set a different 7370 * category using {@link Notification.Builder#setCategory(String) setCategory()}. 7371 * <p> 7372 * Finally, if you attach a {@link android.media.session.MediaSession.Token} using 7373 * {@link android.app.Notification.MediaStyle#setMediaSession(MediaSession.Token)}, 7374 * the System UI can identify this as a notification representing an active media session 7375 * and respond accordingly (by showing album artwork in the lockscreen, for example). 7376 * 7377 * <p> 7378 * Starting at {@link android.os.Build.VERSION_CODES#O Android O} any notification that has a 7379 * media session attached with {@link #setMediaSession(MediaSession.Token)} will be colorized. 7380 * You can opt-out of this behavior by using {@link Notification.Builder#setColorized(boolean)}. 7381 * <p> 7382 * 7383 * To use this style with your Notification, feed it to 7384 * {@link Notification.Builder#setStyle(android.app.Notification.Style)} like so: 7385 * <pre class="prettyprint"> 7386 * Notification noti = new Notification.Builder() 7387 * .setSmallIcon(R.drawable.ic_stat_player) 7388 * .setContentTitle("Track title") 7389 * .setContentText("Artist - Album") 7390 * .setLargeIcon(albumArtBitmap)) 7391 * .setStyle(<b>new Notification.MediaStyle()</b> 7392 * .setMediaSession(mySession)) 7393 * .build(); 7394 * </pre> 7395 * 7396 * @see Notification#bigContentView 7397 * @see Notification.Builder#setColorized(boolean) 7398 */ 7399 public static class MediaStyle extends Style { 7400 static final int MAX_MEDIA_BUTTONS_IN_COMPACT = 3; 7401 static final int MAX_MEDIA_BUTTONS = 5; 7402 7403 private int[] mActionsToShowInCompact = null; 7404 private MediaSession.Token mToken; 7405 7406 public MediaStyle() { 7407 } 7408 7409 /** 7410 * @deprecated use {@code MediaStyle()}. 7411 */ 7412 @Deprecated 7413 public MediaStyle(Builder builder) { 7414 setBuilder(builder); 7415 } 7416 7417 /** 7418 * Request up to 3 actions (by index in the order of addition) to be shown in the compact 7419 * notification view. 7420 * 7421 * @param actions the indices of the actions to show in the compact notification view 7422 */ 7423 public MediaStyle setShowActionsInCompactView(int...actions) { 7424 mActionsToShowInCompact = actions; 7425 return this; 7426 } 7427 7428 /** 7429 * Attach a {@link android.media.session.MediaSession.Token} to this Notification 7430 * to provide additional playback information and control to the SystemUI. 7431 */ 7432 public MediaStyle setMediaSession(MediaSession.Token token) { 7433 mToken = token; 7434 return this; 7435 } 7436 7437 /** 7438 * @hide 7439 */ 7440 @Override 7441 public Notification buildStyled(Notification wip) { 7442 super.buildStyled(wip); 7443 if (wip.category == null) { 7444 wip.category = Notification.CATEGORY_TRANSPORT; 7445 } 7446 return wip; 7447 } 7448 7449 /** 7450 * @hide 7451 */ 7452 @Override 7453 public RemoteViews makeContentView(boolean increasedHeight) { 7454 return makeMediaContentView(); 7455 } 7456 7457 /** 7458 * @hide 7459 */ 7460 @Override 7461 public RemoteViews makeBigContentView() { 7462 return makeMediaBigContentView(); 7463 } 7464 7465 /** 7466 * @hide 7467 */ 7468 @Override 7469 public RemoteViews makeHeadsUpContentView(boolean increasedHeight) { 7470 RemoteViews expanded = makeMediaBigContentView(); 7471 return expanded != null ? expanded : makeMediaContentView(); 7472 } 7473 7474 /** @hide */ 7475 @Override 7476 public void addExtras(Bundle extras) { 7477 super.addExtras(extras); 7478 7479 if (mToken != null) { 7480 extras.putParcelable(EXTRA_MEDIA_SESSION, mToken); 7481 } 7482 if (mActionsToShowInCompact != null) { 7483 extras.putIntArray(EXTRA_COMPACT_ACTIONS, mActionsToShowInCompact); 7484 } 7485 } 7486 7487 /** 7488 * @hide 7489 */ 7490 @Override 7491 protected void restoreFromExtras(Bundle extras) { 7492 super.restoreFromExtras(extras); 7493 7494 if (extras.containsKey(EXTRA_MEDIA_SESSION)) { 7495 mToken = extras.getParcelable(EXTRA_MEDIA_SESSION); 7496 } 7497 if (extras.containsKey(EXTRA_COMPACT_ACTIONS)) { 7498 mActionsToShowInCompact = extras.getIntArray(EXTRA_COMPACT_ACTIONS); 7499 } 7500 } 7501 7502 /** 7503 * @hide 7504 */ 7505 @Override 7506 public boolean areNotificationsVisiblyDifferent(Style other) { 7507 if (other == null || getClass() != other.getClass()) { 7508 return true; 7509 } 7510 // All fields to compare are on the Notification object 7511 return false; 7512 } 7513 7514 private RemoteViews generateMediaActionButton(Action action, int color) { 7515 final boolean tombstone = (action.actionIntent == null); 7516 RemoteViews button = new BuilderRemoteViews(mBuilder.mContext.getApplicationInfo(), 7517 R.layout.notification_material_media_action); 7518 button.setImageViewIcon(R.id.action0, action.getIcon()); 7519 7520 // If the action buttons should not be tinted, then just use the default 7521 // notification color. Otherwise, just use the passed-in color. 7522 int tintColor = mBuilder.shouldTintActionButtons() || mBuilder.isColorized() 7523 ? color 7524 : NotificationColorUtil.resolveColor(mBuilder.mContext, 7525 Notification.COLOR_DEFAULT); 7526 7527 button.setDrawableTint(R.id.action0, false, tintColor, 7528 PorterDuff.Mode.SRC_ATOP); 7529 if (!tombstone) { 7530 button.setOnClickPendingIntent(R.id.action0, action.actionIntent); 7531 } 7532 button.setContentDescription(R.id.action0, action.title); 7533 return button; 7534 } 7535 7536 private RemoteViews makeMediaContentView() { 7537 RemoteViews view = mBuilder.applyStandardTemplate( 7538 R.layout.notification_template_material_media, false /* hasProgress */); 7539 7540 final int numActions = mBuilder.mActions.size(); 7541 final int N = mActionsToShowInCompact == null 7542 ? 0 7543 : Math.min(mActionsToShowInCompact.length, MAX_MEDIA_BUTTONS_IN_COMPACT); 7544 if (N > 0) { 7545 view.removeAllViews(com.android.internal.R.id.media_actions); 7546 for (int i = 0; i < N; i++) { 7547 if (i >= numActions) { 7548 throw new IllegalArgumentException(String.format( 7549 "setShowActionsInCompactView: action %d out of bounds (max %d)", 7550 i, numActions - 1)); 7551 } 7552 7553 final Action action = mBuilder.mActions.get(mActionsToShowInCompact[i]); 7554 final RemoteViews button = generateMediaActionButton(action, getActionColor()); 7555 view.addView(com.android.internal.R.id.media_actions, button); 7556 } 7557 } 7558 handleImage(view); 7559 // handle the content margin 7560 int endMargin = R.dimen.notification_content_margin_end; 7561 if (mBuilder.mN.hasLargeIcon()) { 7562 endMargin = R.dimen.notification_content_plus_picture_margin_end; 7563 } 7564 view.setViewLayoutMarginEndDimen(R.id.notification_main_column, endMargin); 7565 return view; 7566 } 7567 7568 private int getActionColor() { 7569 return mBuilder.isColorized() ? mBuilder.getPrimaryTextColor() 7570 : mBuilder.resolveContrastColor(); 7571 } 7572 7573 private RemoteViews makeMediaBigContentView() { 7574 final int actionCount = Math.min(mBuilder.mActions.size(), MAX_MEDIA_BUTTONS); 7575 // Dont add an expanded view if there is no more content to be revealed 7576 int actionsInCompact = mActionsToShowInCompact == null 7577 ? 0 7578 : Math.min(mActionsToShowInCompact.length, MAX_MEDIA_BUTTONS_IN_COMPACT); 7579 if (!mBuilder.mN.hasLargeIcon() && actionCount <= actionsInCompact) { 7580 return null; 7581 } 7582 RemoteViews big = mBuilder.applyStandardTemplate( 7583 R.layout.notification_template_material_big_media, 7584 false); 7585 7586 if (actionCount > 0) { 7587 big.removeAllViews(com.android.internal.R.id.media_actions); 7588 for (int i = 0; i < actionCount; i++) { 7589 final RemoteViews button = generateMediaActionButton(mBuilder.mActions.get(i), 7590 getActionColor()); 7591 big.addView(com.android.internal.R.id.media_actions, button); 7592 } 7593 } 7594 handleImage(big); 7595 return big; 7596 } 7597 7598 private void handleImage(RemoteViews contentView) { 7599 if (mBuilder.mN.hasLargeIcon()) { 7600 contentView.setViewLayoutMarginEndDimen(R.id.line1, 0); 7601 contentView.setViewLayoutMarginEndDimen(R.id.text, 0); 7602 } 7603 } 7604 7605 /** 7606 * @hide 7607 */ 7608 @Override 7609 protected boolean hasProgress() { 7610 return false; 7611 } 7612 } 7613 7614 /** 7615 * Notification style for custom views that are decorated by the system 7616 * 7617 * <p>Instead of providing a notification that is completely custom, a developer can set this 7618 * style and still obtain system decorations like the notification header with the expand 7619 * affordance and actions. 7620 * 7621 * <p>Use {@link android.app.Notification.Builder#setCustomContentView(RemoteViews)}, 7622 * {@link android.app.Notification.Builder#setCustomBigContentView(RemoteViews)} and 7623 * {@link android.app.Notification.Builder#setCustomHeadsUpContentView(RemoteViews)} to set the 7624 * corresponding custom views to display. 7625 * 7626 * To use this style with your Notification, feed it to 7627 * {@link Notification.Builder#setStyle(android.app.Notification.Style)} like so: 7628 * <pre class="prettyprint"> 7629 * Notification noti = new Notification.Builder() 7630 * .setSmallIcon(R.drawable.ic_stat_player) 7631 * .setLargeIcon(albumArtBitmap)) 7632 * .setCustomContentView(contentView); 7633 * .setStyle(<b>new Notification.DecoratedCustomViewStyle()</b>) 7634 * .build(); 7635 * </pre> 7636 */ 7637 public static class DecoratedCustomViewStyle extends Style { 7638 7639 public DecoratedCustomViewStyle() { 7640 } 7641 7642 /** 7643 * @hide 7644 */ 7645 public boolean displayCustomViewInline() { 7646 return true; 7647 } 7648 7649 /** 7650 * @hide 7651 */ 7652 @Override 7653 public RemoteViews makeContentView(boolean increasedHeight) { 7654 return makeStandardTemplateWithCustomContent(mBuilder.mN.contentView); 7655 } 7656 7657 /** 7658 * @hide 7659 */ 7660 @Override 7661 public RemoteViews makeBigContentView() { 7662 return makeDecoratedBigContentView(); 7663 } 7664 7665 /** 7666 * @hide 7667 */ 7668 @Override 7669 public RemoteViews makeHeadsUpContentView(boolean increasedHeight) { 7670 return makeDecoratedHeadsUpContentView(); 7671 } 7672 7673 private RemoteViews makeDecoratedHeadsUpContentView() { 7674 RemoteViews headsUpContentView = mBuilder.mN.headsUpContentView == null 7675 ? mBuilder.mN.contentView 7676 : mBuilder.mN.headsUpContentView; 7677 if (mBuilder.mActions.size() == 0) { 7678 return makeStandardTemplateWithCustomContent(headsUpContentView); 7679 } 7680 RemoteViews remoteViews = mBuilder.applyStandardTemplateWithActions( 7681 mBuilder.getBigBaseLayoutResource()); 7682 buildIntoRemoteViewContent(remoteViews, headsUpContentView); 7683 return remoteViews; 7684 } 7685 7686 private RemoteViews makeStandardTemplateWithCustomContent(RemoteViews customContent) { 7687 RemoteViews remoteViews = mBuilder.applyStandardTemplate( 7688 mBuilder.getBaseLayoutResource()); 7689 buildIntoRemoteViewContent(remoteViews, customContent); 7690 return remoteViews; 7691 } 7692 7693 private RemoteViews makeDecoratedBigContentView() { 7694 RemoteViews bigContentView = mBuilder.mN.bigContentView == null 7695 ? mBuilder.mN.contentView 7696 : mBuilder.mN.bigContentView; 7697 if (mBuilder.mActions.size() == 0) { 7698 return makeStandardTemplateWithCustomContent(bigContentView); 7699 } 7700 RemoteViews remoteViews = mBuilder.applyStandardTemplateWithActions( 7701 mBuilder.getBigBaseLayoutResource()); 7702 buildIntoRemoteViewContent(remoteViews, bigContentView); 7703 return remoteViews; 7704 } 7705 7706 private void buildIntoRemoteViewContent(RemoteViews remoteViews, 7707 RemoteViews customContent) { 7708 if (customContent != null) { 7709 // Need to clone customContent before adding, because otherwise it can no longer be 7710 // parceled independently of remoteViews. 7711 customContent = customContent.clone(); 7712 remoteViews.removeAllViewsExceptId(R.id.notification_main_column, R.id.progress); 7713 remoteViews.addView(R.id.notification_main_column, customContent, 0 /* index */); 7714 remoteViews.setReapplyDisallowed(); 7715 } 7716 // also update the end margin if there is an image 7717 int endMargin = R.dimen.notification_content_margin_end; 7718 if (mBuilder.mN.hasLargeIcon()) { 7719 endMargin = R.dimen.notification_content_plus_picture_margin_end; 7720 } 7721 remoteViews.setViewLayoutMarginEndDimen(R.id.notification_main_column, endMargin); 7722 } 7723 7724 /** 7725 * @hide 7726 */ 7727 @Override 7728 public boolean areNotificationsVisiblyDifferent(Style other) { 7729 if (other == null || getClass() != other.getClass()) { 7730 return true; 7731 } 7732 // Comparison done for all custom RemoteViews, independent of style 7733 return false; 7734 } 7735 } 7736 7737 /** 7738 * Notification style for media custom views that are decorated by the system 7739 * 7740 * <p>Instead of providing a media notification that is completely custom, a developer can set 7741 * this style and still obtain system decorations like the notification header with the expand 7742 * affordance and actions. 7743 * 7744 * <p>Use {@link android.app.Notification.Builder#setCustomContentView(RemoteViews)}, 7745 * {@link android.app.Notification.Builder#setCustomBigContentView(RemoteViews)} and 7746 * {@link android.app.Notification.Builder#setCustomHeadsUpContentView(RemoteViews)} to set the 7747 * corresponding custom views to display. 7748 * <p> 7749 * Contrary to {@link MediaStyle} a developer has to opt-in to the colorizing of the 7750 * notification by using {@link Notification.Builder#setColorized(boolean)}. 7751 * <p> 7752 * To use this style with your Notification, feed it to 7753 * {@link Notification.Builder#setStyle(android.app.Notification.Style)} like so: 7754 * <pre class="prettyprint"> 7755 * Notification noti = new Notification.Builder() 7756 * .setSmallIcon(R.drawable.ic_stat_player) 7757 * .setLargeIcon(albumArtBitmap)) 7758 * .setCustomContentView(contentView); 7759 * .setStyle(<b>new Notification.DecoratedMediaCustomViewStyle()</b> 7760 * .setMediaSession(mySession)) 7761 * .build(); 7762 * </pre> 7763 * 7764 * @see android.app.Notification.DecoratedCustomViewStyle 7765 * @see android.app.Notification.MediaStyle 7766 */ 7767 public static class DecoratedMediaCustomViewStyle extends MediaStyle { 7768 7769 public DecoratedMediaCustomViewStyle() { 7770 } 7771 7772 /** 7773 * @hide 7774 */ 7775 public boolean displayCustomViewInline() { 7776 return true; 7777 } 7778 7779 /** 7780 * @hide 7781 */ 7782 @Override 7783 public RemoteViews makeContentView(boolean increasedHeight) { 7784 RemoteViews remoteViews = super.makeContentView(false /* increasedHeight */); 7785 return buildIntoRemoteView(remoteViews, R.id.notification_content_container, 7786 mBuilder.mN.contentView); 7787 } 7788 7789 /** 7790 * @hide 7791 */ 7792 @Override 7793 public RemoteViews makeBigContentView() { 7794 RemoteViews customRemoteView = mBuilder.mN.bigContentView != null 7795 ? mBuilder.mN.bigContentView 7796 : mBuilder.mN.contentView; 7797 return makeBigContentViewWithCustomContent(customRemoteView); 7798 } 7799 7800 private RemoteViews makeBigContentViewWithCustomContent(RemoteViews customRemoteView) { 7801 RemoteViews remoteViews = super.makeBigContentView(); 7802 if (remoteViews != null) { 7803 return buildIntoRemoteView(remoteViews, R.id.notification_main_column, 7804 customRemoteView); 7805 } else if (customRemoteView != mBuilder.mN.contentView){ 7806 remoteViews = super.makeContentView(false /* increasedHeight */); 7807 return buildIntoRemoteView(remoteViews, R.id.notification_content_container, 7808 customRemoteView); 7809 } else { 7810 return null; 7811 } 7812 } 7813 7814 /** 7815 * @hide 7816 */ 7817 @Override 7818 public RemoteViews makeHeadsUpContentView(boolean increasedHeight) { 7819 RemoteViews customRemoteView = mBuilder.mN.headsUpContentView != null 7820 ? mBuilder.mN.headsUpContentView 7821 : mBuilder.mN.contentView; 7822 return makeBigContentViewWithCustomContent(customRemoteView); 7823 } 7824 7825 /** 7826 * @hide 7827 */ 7828 @Override 7829 public boolean areNotificationsVisiblyDifferent(Style other) { 7830 if (other == null || getClass() != other.getClass()) { 7831 return true; 7832 } 7833 // Comparison done for all custom RemoteViews, independent of style 7834 return false; 7835 } 7836 7837 private RemoteViews buildIntoRemoteView(RemoteViews remoteViews, int id, 7838 RemoteViews customContent) { 7839 if (customContent != null) { 7840 // Need to clone customContent before adding, because otherwise it can no longer be 7841 // parceled independently of remoteViews. 7842 customContent = customContent.clone(); 7843 customContent.overrideTextColors(mBuilder.getPrimaryTextColor()); 7844 remoteViews.removeAllViews(id); 7845 remoteViews.addView(id, customContent); 7846 remoteViews.setReapplyDisallowed(); 7847 } 7848 return remoteViews; 7849 } 7850 } 7851 7852 // When adding a new Style subclass here, don't forget to update 7853 // Builder.getNotificationStyleClass. 7854 7855 /** 7856 * Extender interface for use with {@link Builder#extend}. Extenders may be used to add 7857 * metadata or change options on a notification builder. 7858 */ 7859 public interface Extender { 7860 /** 7861 * Apply this extender to a notification builder. 7862 * @param builder the builder to be modified. 7863 * @return the build object for chaining. 7864 */ 7865 public Builder extend(Builder builder); 7866 } 7867 7868 /** 7869 * Helper class to add wearable extensions to notifications. 7870 * <p class="note"> See 7871 * <a href="{@docRoot}wear/notifications/creating.html">Creating Notifications 7872 * for Android Wear</a> for more information on how to use this class. 7873 * <p> 7874 * To create a notification with wearable extensions: 7875 * <ol> 7876 * <li>Create a {@link android.app.Notification.Builder}, setting any desired 7877 * properties. 7878 * <li>Create a {@link android.app.Notification.WearableExtender}. 7879 * <li>Set wearable-specific properties using the 7880 * {@code add} and {@code set} methods of {@link android.app.Notification.WearableExtender}. 7881 * <li>Call {@link android.app.Notification.Builder#extend} to apply the extensions to a 7882 * notification. 7883 * <li>Post the notification to the notification system with the 7884 * {@code NotificationManager.notify(...)} methods. 7885 * </ol> 7886 * 7887 * <pre class="prettyprint"> 7888 * Notification notif = new Notification.Builder(mContext) 7889 * .setContentTitle("New mail from " + sender.toString()) 7890 * .setContentText(subject) 7891 * .setSmallIcon(R.drawable.new_mail) 7892 * .extend(new Notification.WearableExtender() 7893 * .setContentIcon(R.drawable.new_mail)) 7894 * .build(); 7895 * NotificationManager notificationManger = 7896 * (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 7897 * notificationManger.notify(0, notif);</pre> 7898 * 7899 * <p>Wearable extensions can be accessed on an existing notification by using the 7900 * {@code WearableExtender(Notification)} constructor, 7901 * and then using the {@code get} methods to access values. 7902 * 7903 * <pre class="prettyprint"> 7904 * Notification.WearableExtender wearableExtender = new Notification.WearableExtender( 7905 * notification); 7906 * List<Notification> pages = wearableExtender.getPages();</pre> 7907 */ 7908 public static final class WearableExtender implements Extender { 7909 /** 7910 * Sentinel value for an action index that is unset. 7911 */ 7912 public static final int UNSET_ACTION_INDEX = -1; 7913 7914 /** 7915 * Size value for use with {@link #setCustomSizePreset} to show this notification with 7916 * default sizing. 7917 * <p>For custom display notifications created using {@link #setDisplayIntent}, 7918 * the default is {@link #SIZE_MEDIUM}. All other notifications size automatically based 7919 * on their content. 7920 */ 7921 public static final int SIZE_DEFAULT = 0; 7922 7923 /** 7924 * Size value for use with {@link #setCustomSizePreset} to show this notification 7925 * with an extra small size. 7926 * <p>This value is only applicable for custom display notifications created using 7927 * {@link #setDisplayIntent}. 7928 */ 7929 public static final int SIZE_XSMALL = 1; 7930 7931 /** 7932 * Size value for use with {@link #setCustomSizePreset} to show this notification 7933 * with a small size. 7934 * <p>This value is only applicable for custom display notifications created using 7935 * {@link #setDisplayIntent}. 7936 */ 7937 public static final int SIZE_SMALL = 2; 7938 7939 /** 7940 * Size value for use with {@link #setCustomSizePreset} to show this notification 7941 * with a medium size. 7942 * <p>This value is only applicable for custom display notifications created using 7943 * {@link #setDisplayIntent}. 7944 */ 7945 public static final int SIZE_MEDIUM = 3; 7946 7947 /** 7948 * Size value for use with {@link #setCustomSizePreset} to show this notification 7949 * with a large size. 7950 * <p>This value is only applicable for custom display notifications created using 7951 * {@link #setDisplayIntent}. 7952 */ 7953 public static final int SIZE_LARGE = 4; 7954 7955 /** 7956 * Size value for use with {@link #setCustomSizePreset} to show this notification 7957 * full screen. 7958 * <p>This value is only applicable for custom display notifications created using 7959 * {@link #setDisplayIntent}. 7960 */ 7961 public static final int SIZE_FULL_SCREEN = 5; 7962 7963 /** 7964 * Sentinel value for use with {@link #setHintScreenTimeout} to keep the screen on for a 7965 * short amount of time when this notification is displayed on the screen. This 7966 * is the default value. 7967 */ 7968 public static final int SCREEN_TIMEOUT_SHORT = 0; 7969 7970 /** 7971 * Sentinel value for use with {@link #setHintScreenTimeout} to keep the screen on 7972 * for a longer amount of time when this notification is displayed on the screen. 7973 */ 7974 public static final int SCREEN_TIMEOUT_LONG = -1; 7975 7976 /** Notification extra which contains wearable extensions */ 7977 private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS"; 7978 7979 // Keys within EXTRA_WEARABLE_EXTENSIONS for wearable options. 7980 private static final String KEY_ACTIONS = "actions"; 7981 private static final String KEY_FLAGS = "flags"; 7982 private static final String KEY_DISPLAY_INTENT = "displayIntent"; 7983 private static final String KEY_PAGES = "pages"; 7984 private static final String KEY_BACKGROUND = "background"; 7985 private static final String KEY_CONTENT_ICON = "contentIcon"; 7986 private static final String KEY_CONTENT_ICON_GRAVITY = "contentIconGravity"; 7987 private static final String KEY_CONTENT_ACTION_INDEX = "contentActionIndex"; 7988 private static final String KEY_CUSTOM_SIZE_PRESET = "customSizePreset"; 7989 private static final String KEY_CUSTOM_CONTENT_HEIGHT = "customContentHeight"; 7990 private static final String KEY_GRAVITY = "gravity"; 7991 private static final String KEY_HINT_SCREEN_TIMEOUT = "hintScreenTimeout"; 7992 private static final String KEY_DISMISSAL_ID = "dismissalId"; 7993 private static final String KEY_BRIDGE_TAG = "bridgeTag"; 7994 7995 // Flags bitwise-ored to mFlags 7996 private static final int FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE = 0x1; 7997 private static final int FLAG_HINT_HIDE_ICON = 1 << 1; 7998 private static final int FLAG_HINT_SHOW_BACKGROUND_ONLY = 1 << 2; 7999 private static final int FLAG_START_SCROLL_BOTTOM = 1 << 3; 8000 private static final int FLAG_HINT_AVOID_BACKGROUND_CLIPPING = 1 << 4; 8001 private static final int FLAG_BIG_PICTURE_AMBIENT = 1 << 5; 8002 private static final int FLAG_HINT_CONTENT_INTENT_LAUNCHES_ACTIVITY = 1 << 6; 8003 8004 // Default value for flags integer 8005 private static final int DEFAULT_FLAGS = FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE; 8006 8007 private static final int DEFAULT_CONTENT_ICON_GRAVITY = Gravity.END; 8008 private static final int DEFAULT_GRAVITY = Gravity.BOTTOM; 8009 8010 private ArrayList<Action> mActions = new ArrayList<Action>(); 8011 private int mFlags = DEFAULT_FLAGS; 8012 private PendingIntent mDisplayIntent; 8013 private ArrayList<Notification> mPages = new ArrayList<Notification>(); 8014 private Bitmap mBackground; 8015 private int mContentIcon; 8016 private int mContentIconGravity = DEFAULT_CONTENT_ICON_GRAVITY; 8017 private int mContentActionIndex = UNSET_ACTION_INDEX; 8018 private int mCustomSizePreset = SIZE_DEFAULT; 8019 private int mCustomContentHeight; 8020 private int mGravity = DEFAULT_GRAVITY; 8021 private int mHintScreenTimeout; 8022 private String mDismissalId; 8023 private String mBridgeTag; 8024 8025 /** 8026 * Create a {@link android.app.Notification.WearableExtender} with default 8027 * options. 8028 */ 8029 public WearableExtender() { 8030 } 8031 8032 public WearableExtender(Notification notif) { 8033 Bundle wearableBundle = notif.extras.getBundle(EXTRA_WEARABLE_EXTENSIONS); 8034 if (wearableBundle != null) { 8035 List<Action> actions = wearableBundle.getParcelableArrayList(KEY_ACTIONS); 8036 if (actions != null) { 8037 mActions.addAll(actions); 8038 } 8039 8040 mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS); 8041 mDisplayIntent = wearableBundle.getParcelable(KEY_DISPLAY_INTENT); 8042 8043 Notification[] pages = getNotificationArrayFromBundle( 8044 wearableBundle, KEY_PAGES); 8045 if (pages != null) { 8046 Collections.addAll(mPages, pages); 8047 } 8048 8049 mBackground = wearableBundle.getParcelable(KEY_BACKGROUND); 8050 mContentIcon = wearableBundle.getInt(KEY_CONTENT_ICON); 8051 mContentIconGravity = wearableBundle.getInt(KEY_CONTENT_ICON_GRAVITY, 8052 DEFAULT_CONTENT_ICON_GRAVITY); 8053 mContentActionIndex = wearableBundle.getInt(KEY_CONTENT_ACTION_INDEX, 8054 UNSET_ACTION_INDEX); 8055 mCustomSizePreset = wearableBundle.getInt(KEY_CUSTOM_SIZE_PRESET, 8056 SIZE_DEFAULT); 8057 mCustomContentHeight = wearableBundle.getInt(KEY_CUSTOM_CONTENT_HEIGHT); 8058 mGravity = wearableBundle.getInt(KEY_GRAVITY, DEFAULT_GRAVITY); 8059 mHintScreenTimeout = wearableBundle.getInt(KEY_HINT_SCREEN_TIMEOUT); 8060 mDismissalId = wearableBundle.getString(KEY_DISMISSAL_ID); 8061 mBridgeTag = wearableBundle.getString(KEY_BRIDGE_TAG); 8062 } 8063 } 8064 8065 /** 8066 * Apply wearable extensions to a notification that is being built. This is typically 8067 * called by the {@link android.app.Notification.Builder#extend} method of 8068 * {@link android.app.Notification.Builder}. 8069 */ 8070 @Override 8071 public Notification.Builder extend(Notification.Builder builder) { 8072 Bundle wearableBundle = new Bundle(); 8073 8074 if (!mActions.isEmpty()) { 8075 wearableBundle.putParcelableArrayList(KEY_ACTIONS, mActions); 8076 } 8077 if (mFlags != DEFAULT_FLAGS) { 8078 wearableBundle.putInt(KEY_FLAGS, mFlags); 8079 } 8080 if (mDisplayIntent != null) { 8081 wearableBundle.putParcelable(KEY_DISPLAY_INTENT, mDisplayIntent); 8082 } 8083 if (!mPages.isEmpty()) { 8084 wearableBundle.putParcelableArray(KEY_PAGES, mPages.toArray( 8085 new Notification[mPages.size()])); 8086 } 8087 if (mBackground != null) { 8088 wearableBundle.putParcelable(KEY_BACKGROUND, mBackground); 8089 } 8090 if (mContentIcon != 0) { 8091 wearableBundle.putInt(KEY_CONTENT_ICON, mContentIcon); 8092 } 8093 if (mContentIconGravity != DEFAULT_CONTENT_ICON_GRAVITY) { 8094 wearableBundle.putInt(KEY_CONTENT_ICON_GRAVITY, mContentIconGravity); 8095 } 8096 if (mContentActionIndex != UNSET_ACTION_INDEX) { 8097 wearableBundle.putInt(KEY_CONTENT_ACTION_INDEX, 8098 mContentActionIndex); 8099 } 8100 if (mCustomSizePreset != SIZE_DEFAULT) { 8101 wearableBundle.putInt(KEY_CUSTOM_SIZE_PRESET, mCustomSizePreset); 8102 } 8103 if (mCustomContentHeight != 0) { 8104 wearableBundle.putInt(KEY_CUSTOM_CONTENT_HEIGHT, mCustomContentHeight); 8105 } 8106 if (mGravity != DEFAULT_GRAVITY) { 8107 wearableBundle.putInt(KEY_GRAVITY, mGravity); 8108 } 8109 if (mHintScreenTimeout != 0) { 8110 wearableBundle.putInt(KEY_HINT_SCREEN_TIMEOUT, mHintScreenTimeout); 8111 } 8112 if (mDismissalId != null) { 8113 wearableBundle.putString(KEY_DISMISSAL_ID, mDismissalId); 8114 } 8115 if (mBridgeTag != null) { 8116 wearableBundle.putString(KEY_BRIDGE_TAG, mBridgeTag); 8117 } 8118 8119 builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle); 8120 return builder; 8121 } 8122 8123 @Override 8124 public WearableExtender clone() { 8125 WearableExtender that = new WearableExtender(); 8126 that.mActions = new ArrayList<Action>(this.mActions); 8127 that.mFlags = this.mFlags; 8128 that.mDisplayIntent = this.mDisplayIntent; 8129 that.mPages = new ArrayList<Notification>(this.mPages); 8130 that.mBackground = this.mBackground; 8131 that.mContentIcon = this.mContentIcon; 8132 that.mContentIconGravity = this.mContentIconGravity; 8133 that.mContentActionIndex = this.mContentActionIndex; 8134 that.mCustomSizePreset = this.mCustomSizePreset; 8135 that.mCustomContentHeight = this.mCustomContentHeight; 8136 that.mGravity = this.mGravity; 8137 that.mHintScreenTimeout = this.mHintScreenTimeout; 8138 that.mDismissalId = this.mDismissalId; 8139 that.mBridgeTag = this.mBridgeTag; 8140 return that; 8141 } 8142 8143 /** 8144 * Add a wearable action to this notification. 8145 * 8146 * <p>When wearable actions are added using this method, the set of actions that 8147 * show on a wearable device splits from devices that only show actions added 8148 * using {@link android.app.Notification.Builder#addAction}. This allows for customization 8149 * of which actions display on different devices. 8150 * 8151 * @param action the action to add to this notification 8152 * @return this object for method chaining 8153 * @see android.app.Notification.Action 8154 */ 8155 public WearableExtender addAction(Action action) { 8156 mActions.add(action); 8157 return this; 8158 } 8159 8160 /** 8161 * Adds wearable actions to this notification. 8162 * 8163 * <p>When wearable actions are added using this method, the set of actions that 8164 * show on a wearable device splits from devices that only show actions added 8165 * using {@link android.app.Notification.Builder#addAction}. This allows for customization 8166 * of which actions display on different devices. 8167 * 8168 * @param actions the actions to add to this notification 8169 * @return this object for method chaining 8170 * @see android.app.Notification.Action 8171 */ 8172 public WearableExtender addActions(List<Action> actions) { 8173 mActions.addAll(actions); 8174 return this; 8175 } 8176 8177 /** 8178 * Clear all wearable actions present on this builder. 8179 * @return this object for method chaining. 8180 * @see #addAction 8181 */ 8182 public WearableExtender clearActions() { 8183 mActions.clear(); 8184 return this; 8185 } 8186 8187 /** 8188 * Get the wearable actions present on this notification. 8189 */ 8190 public List<Action> getActions() { 8191 return mActions; 8192 } 8193 8194 /** 8195 * Set an intent to launch inside of an activity view when displaying 8196 * this notification. The {@link PendingIntent} provided should be for an activity. 8197 * 8198 * <pre class="prettyprint"> 8199 * Intent displayIntent = new Intent(context, MyDisplayActivity.class); 8200 * PendingIntent displayPendingIntent = PendingIntent.getActivity(context, 8201 * 0, displayIntent, PendingIntent.FLAG_UPDATE_CURRENT); 8202 * Notification notif = new Notification.Builder(context) 8203 * .extend(new Notification.WearableExtender() 8204 * .setDisplayIntent(displayPendingIntent) 8205 * .setCustomSizePreset(Notification.WearableExtender.SIZE_MEDIUM)) 8206 * .build();</pre> 8207 * 8208 * <p>The activity to launch needs to allow embedding, must be exported, and 8209 * should have an empty task affinity. It is also recommended to use the device 8210 * default light theme. 8211 * 8212 * <p>Example AndroidManifest.xml entry: 8213 * <pre class="prettyprint"> 8214 * <activity android:name="com.example.MyDisplayActivity" 8215 * android:exported="true" 8216 * android:allowEmbedded="true" 8217 * android:taskAffinity="" 8218 * android:theme="@android:style/Theme.DeviceDefault.Light" /></pre> 8219 * 8220 * @param intent the {@link PendingIntent} for an activity 8221 * @return this object for method chaining 8222 * @see android.app.Notification.WearableExtender#getDisplayIntent 8223 */ 8224 public WearableExtender setDisplayIntent(PendingIntent intent) { 8225 mDisplayIntent = intent; 8226 return this; 8227 } 8228 8229 /** 8230 * Get the intent to launch inside of an activity view when displaying this 8231 * notification. This {@code PendingIntent} should be for an activity. 8232 */ 8233 public PendingIntent getDisplayIntent() { 8234 return mDisplayIntent; 8235 } 8236 8237 /** 8238 * Add an additional page of content to display with this notification. The current 8239 * notification forms the first page, and pages added using this function form 8240 * subsequent pages. This field can be used to separate a notification into multiple 8241 * sections. 8242 * 8243 * @param page the notification to add as another page 8244 * @return this object for method chaining 8245 * @see android.app.Notification.WearableExtender#getPages 8246 */ 8247 public WearableExtender addPage(Notification page) { 8248 mPages.add(page); 8249 return this; 8250 } 8251 8252 /** 8253 * Add additional pages of content to display with this notification. The current 8254 * notification forms the first page, and pages added using this function form 8255 * subsequent pages. This field can be used to separate a notification into multiple 8256 * sections. 8257 * 8258 * @param pages a list of notifications 8259 * @return this object for method chaining 8260 * @see android.app.Notification.WearableExtender#getPages 8261 */ 8262 public WearableExtender addPages(List<Notification> pages) { 8263 mPages.addAll(pages); 8264 return this; 8265 } 8266 8267 /** 8268 * Clear all additional pages present on this builder. 8269 * @return this object for method chaining. 8270 * @see #addPage 8271 */ 8272 public WearableExtender clearPages() { 8273 mPages.clear(); 8274 return this; 8275 } 8276 8277 /** 8278 * Get the array of additional pages of content for displaying this notification. The 8279 * current notification forms the first page, and elements within this array form 8280 * subsequent pages. This field can be used to separate a notification into multiple 8281 * sections. 8282 * @return the pages for this notification 8283 */ 8284 public List<Notification> getPages() { 8285 return mPages; 8286 } 8287 8288 /** 8289 * Set a background image to be displayed behind the notification content. 8290 * Contrary to the {@link android.app.Notification.BigPictureStyle}, this background 8291 * will work with any notification style. 8292 * 8293 * @param background the background bitmap 8294 * @return this object for method chaining 8295 * @see android.app.Notification.WearableExtender#getBackground 8296 */ 8297 public WearableExtender setBackground(Bitmap background) { 8298 mBackground = background; 8299 return this; 8300 } 8301 8302 /** 8303 * Get a background image to be displayed behind the notification content. 8304 * Contrary to the {@link android.app.Notification.BigPictureStyle}, this background 8305 * will work with any notification style. 8306 * 8307 * @return the background image 8308 * @see android.app.Notification.WearableExtender#setBackground 8309 */ 8310 public Bitmap getBackground() { 8311 return mBackground; 8312 } 8313 8314 /** 8315 * Set an icon that goes with the content of this notification. 8316 */ 8317 @Deprecated 8318 public WearableExtender setContentIcon(int icon) { 8319 mContentIcon = icon; 8320 return this; 8321 } 8322 8323 /** 8324 * Get an icon that goes with the content of this notification. 8325 */ 8326 @Deprecated 8327 public int getContentIcon() { 8328 return mContentIcon; 8329 } 8330 8331 /** 8332 * Set the gravity that the content icon should have within the notification display. 8333 * Supported values include {@link android.view.Gravity#START} and 8334 * {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}. 8335 * @see #setContentIcon 8336 */ 8337 @Deprecated 8338 public WearableExtender setContentIconGravity(int contentIconGravity) { 8339 mContentIconGravity = contentIconGravity; 8340 return this; 8341 } 8342 8343 /** 8344 * Get the gravity that the content icon should have within the notification display. 8345 * Supported values include {@link android.view.Gravity#START} and 8346 * {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}. 8347 * @see #getContentIcon 8348 */ 8349 @Deprecated 8350 public int getContentIconGravity() { 8351 return mContentIconGravity; 8352 } 8353 8354 /** 8355 * Set an action from this notification's actions to be clickable with the content of 8356 * this notification. This action will no longer display separately from the 8357 * notification's content. 8358 * 8359 * <p>For notifications with multiple pages, child pages can also have content actions 8360 * set, although the list of available actions comes from the main notification and not 8361 * from the child page's notification. 8362 * 8363 * @param actionIndex The index of the action to hoist onto the current notification page. 8364 * If wearable actions were added to the main notification, this index 8365 * will apply to that list, otherwise it will apply to the regular 8366 * actions list. 8367 */ 8368 public WearableExtender setContentAction(int actionIndex) { 8369 mContentActionIndex = actionIndex; 8370 return this; 8371 } 8372 8373 /** 8374 * Get the index of the notification action, if any, that was specified as being clickable 8375 * with the content of this notification. This action will no longer display separately 8376 * from the notification's content. 8377 * 8378 * <p>For notifications with multiple pages, child pages can also have content actions 8379 * set, although the list of available actions comes from the main notification and not 8380 * from the child page's notification. 8381 * 8382 * <p>If wearable specific actions were added to the main notification, this index will 8383 * apply to that list, otherwise it will apply to the regular actions list. 8384 * 8385 * @return the action index or {@link #UNSET_ACTION_INDEX} if no action was selected. 8386 */ 8387 public int getContentAction() { 8388 return mContentActionIndex; 8389 } 8390 8391 /** 8392 * Set the gravity that this notification should have within the available viewport space. 8393 * Supported values include {@link android.view.Gravity#TOP}, 8394 * {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}. 8395 * The default value is {@link android.view.Gravity#BOTTOM}. 8396 */ 8397 @Deprecated 8398 public WearableExtender setGravity(int gravity) { 8399 mGravity = gravity; 8400 return this; 8401 } 8402 8403 /** 8404 * Get the gravity that this notification should have within the available viewport space. 8405 * Supported values include {@link android.view.Gravity#TOP}, 8406 * {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}. 8407 * The default value is {@link android.view.Gravity#BOTTOM}. 8408 */ 8409 @Deprecated 8410 public int getGravity() { 8411 return mGravity; 8412 } 8413 8414 /** 8415 * Set the custom size preset for the display of this notification out of the available 8416 * presets found in {@link android.app.Notification.WearableExtender}, e.g. 8417 * {@link #SIZE_LARGE}. 8418 * <p>Some custom size presets are only applicable for custom display notifications created 8419 * using {@link android.app.Notification.WearableExtender#setDisplayIntent}. Check the 8420 * documentation for the preset in question. See also 8421 * {@link #setCustomContentHeight} and {@link #getCustomSizePreset}. 8422 */ 8423 @Deprecated 8424 public WearableExtender setCustomSizePreset(int sizePreset) { 8425 mCustomSizePreset = sizePreset; 8426 return this; 8427 } 8428 8429 /** 8430 * Get the custom size preset for the display of this notification out of the available 8431 * presets found in {@link android.app.Notification.WearableExtender}, e.g. 8432 * {@link #SIZE_LARGE}. 8433 * <p>Some custom size presets are only applicable for custom display notifications created 8434 * using {@link #setDisplayIntent}. Check the documentation for the preset in question. 8435 * See also {@link #setCustomContentHeight} and {@link #setCustomSizePreset}. 8436 */ 8437 @Deprecated 8438 public int getCustomSizePreset() { 8439 return mCustomSizePreset; 8440 } 8441 8442 /** 8443 * Set the custom height in pixels for the display of this notification's content. 8444 * <p>This option is only available for custom display notifications created 8445 * using {@link android.app.Notification.WearableExtender#setDisplayIntent}. See also 8446 * {@link android.app.Notification.WearableExtender#setCustomSizePreset} and 8447 * {@link #getCustomContentHeight}. 8448 */ 8449 @Deprecated 8450 public WearableExtender setCustomContentHeight(int height) { 8451 mCustomContentHeight = height; 8452 return this; 8453 } 8454 8455 /** 8456 * Get the custom height in pixels for the display of this notification's content. 8457 * <p>This option is only available for custom display notifications created 8458 * using {@link #setDisplayIntent}. See also {@link #setCustomSizePreset} and 8459 * {@link #setCustomContentHeight}. 8460 */ 8461 @Deprecated 8462 public int getCustomContentHeight() { 8463 return mCustomContentHeight; 8464 } 8465 8466 /** 8467 * Set whether the scrolling position for the contents of this notification should start 8468 * at the bottom of the contents instead of the top when the contents are too long to 8469 * display within the screen. Default is false (start scroll at the top). 8470 */ 8471 public WearableExtender setStartScrollBottom(boolean startScrollBottom) { 8472 setFlag(FLAG_START_SCROLL_BOTTOM, startScrollBottom); 8473 return this; 8474 } 8475 8476 /** 8477 * Get whether the scrolling position for the contents of this notification should start 8478 * at the bottom of the contents instead of the top when the contents are too long to 8479 * display within the screen. Default is false (start scroll at the top). 8480 */ 8481 public boolean getStartScrollBottom() { 8482 return (mFlags & FLAG_START_SCROLL_BOTTOM) != 0; 8483 } 8484 8485 /** 8486 * Set whether the content intent is available when the wearable device is not connected 8487 * to a companion device. The user can still trigger this intent when the wearable device 8488 * is offline, but a visual hint will indicate that the content intent may not be available. 8489 * Defaults to true. 8490 */ 8491 public WearableExtender setContentIntentAvailableOffline( 8492 boolean contentIntentAvailableOffline) { 8493 setFlag(FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE, contentIntentAvailableOffline); 8494 return this; 8495 } 8496 8497 /** 8498 * Get whether the content intent is available when the wearable device is not connected 8499 * to a companion device. The user can still trigger this intent when the wearable device 8500 * is offline, but a visual hint will indicate that the content intent may not be available. 8501 * Defaults to true. 8502 */ 8503 public boolean getContentIntentAvailableOffline() { 8504 return (mFlags & FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE) != 0; 8505 } 8506 8507 /** 8508 * Set a hint that this notification's icon should not be displayed. 8509 * @param hintHideIcon {@code true} to hide the icon, {@code false} otherwise. 8510 * @return this object for method chaining 8511 */ 8512 @Deprecated 8513 public WearableExtender setHintHideIcon(boolean hintHideIcon) { 8514 setFlag(FLAG_HINT_HIDE_ICON, hintHideIcon); 8515 return this; 8516 } 8517 8518 /** 8519 * Get a hint that this notification's icon should not be displayed. 8520 * @return {@code true} if this icon should not be displayed, false otherwise. 8521 * The default value is {@code false} if this was never set. 8522 */ 8523 @Deprecated 8524 public boolean getHintHideIcon() { 8525 return (mFlags & FLAG_HINT_HIDE_ICON) != 0; 8526 } 8527 8528 /** 8529 * Set a visual hint that only the background image of this notification should be 8530 * displayed, and other semantic content should be hidden. This hint is only applicable 8531 * to sub-pages added using {@link #addPage}. 8532 */ 8533 @Deprecated 8534 public WearableExtender setHintShowBackgroundOnly(boolean hintShowBackgroundOnly) { 8535 setFlag(FLAG_HINT_SHOW_BACKGROUND_ONLY, hintShowBackgroundOnly); 8536 return this; 8537 } 8538 8539 /** 8540 * Get a visual hint that only the background image of this notification should be 8541 * displayed, and other semantic content should be hidden. This hint is only applicable 8542 * to sub-pages added using {@link android.app.Notification.WearableExtender#addPage}. 8543 */ 8544 @Deprecated 8545 public boolean getHintShowBackgroundOnly() { 8546 return (mFlags & FLAG_HINT_SHOW_BACKGROUND_ONLY) != 0; 8547 } 8548 8549 /** 8550 * Set a hint that this notification's background should not be clipped if possible, 8551 * and should instead be resized to fully display on the screen, retaining the aspect 8552 * ratio of the image. This can be useful for images like barcodes or qr codes. 8553 * @param hintAvoidBackgroundClipping {@code true} to avoid clipping if possible. 8554 * @return this object for method chaining 8555 */ 8556 @Deprecated 8557 public WearableExtender setHintAvoidBackgroundClipping( 8558 boolean hintAvoidBackgroundClipping) { 8559 setFlag(FLAG_HINT_AVOID_BACKGROUND_CLIPPING, hintAvoidBackgroundClipping); 8560 return this; 8561 } 8562 8563 /** 8564 * Get a hint that this notification's background should not be clipped if possible, 8565 * and should instead be resized to fully display on the screen, retaining the aspect 8566 * ratio of the image. This can be useful for images like barcodes or qr codes. 8567 * @return {@code true} if it's ok if the background is clipped on the screen, false 8568 * otherwise. The default value is {@code false} if this was never set. 8569 */ 8570 @Deprecated 8571 public boolean getHintAvoidBackgroundClipping() { 8572 return (mFlags & FLAG_HINT_AVOID_BACKGROUND_CLIPPING) != 0; 8573 } 8574 8575 /** 8576 * Set a hint that the screen should remain on for at least this duration when 8577 * this notification is displayed on the screen. 8578 * @param timeout The requested screen timeout in milliseconds. Can also be either 8579 * {@link #SCREEN_TIMEOUT_SHORT} or {@link #SCREEN_TIMEOUT_LONG}. 8580 * @return this object for method chaining 8581 */ 8582 @Deprecated 8583 public WearableExtender setHintScreenTimeout(int timeout) { 8584 mHintScreenTimeout = timeout; 8585 return this; 8586 } 8587 8588 /** 8589 * Get the duration, in milliseconds, that the screen should remain on for 8590 * when this notification is displayed. 8591 * @return the duration in milliseconds if > 0, or either one of the sentinel values 8592 * {@link #SCREEN_TIMEOUT_SHORT} or {@link #SCREEN_TIMEOUT_LONG}. 8593 */ 8594 @Deprecated 8595 public int getHintScreenTimeout() { 8596 return mHintScreenTimeout; 8597 } 8598 8599 /** 8600 * Set a hint that this notification's {@link BigPictureStyle} (if present) should be 8601 * converted to low-bit and displayed in ambient mode, especially useful for barcodes and 8602 * qr codes, as well as other simple black-and-white tickets. 8603 * @param hintAmbientBigPicture {@code true} to enable converstion and ambient. 8604 * @return this object for method chaining 8605 */ 8606 public WearableExtender setHintAmbientBigPicture(boolean hintAmbientBigPicture) { 8607 setFlag(FLAG_BIG_PICTURE_AMBIENT, hintAmbientBigPicture); 8608 return this; 8609 } 8610 8611 /** 8612 * Get a hint that this notification's {@link BigPictureStyle} (if present) should be 8613 * converted to low-bit and displayed in ambient mode, especially useful for barcodes and 8614 * qr codes, as well as other simple black-and-white tickets. 8615 * @return {@code true} if it should be displayed in ambient, false otherwise 8616 * otherwise. The default value is {@code false} if this was never set. 8617 */ 8618 public boolean getHintAmbientBigPicture() { 8619 return (mFlags & FLAG_BIG_PICTURE_AMBIENT) != 0; 8620 } 8621 8622 /** 8623 * Set a hint that this notification's content intent will launch an {@link Activity} 8624 * directly, telling the platform that it can generate the appropriate transitions. 8625 * @param hintContentIntentLaunchesActivity {@code true} if the content intent will launch 8626 * an activity and transitions should be generated, false otherwise. 8627 * @return this object for method chaining 8628 */ 8629 public WearableExtender setHintContentIntentLaunchesActivity( 8630 boolean hintContentIntentLaunchesActivity) { 8631 setFlag(FLAG_HINT_CONTENT_INTENT_LAUNCHES_ACTIVITY, hintContentIntentLaunchesActivity); 8632 return this; 8633 } 8634 8635 /** 8636 * Get a hint that this notification's content intent will launch an {@link Activity} 8637 * directly, telling the platform that it can generate the appropriate transitions 8638 * @return {@code true} if the content intent will launch an activity and transitions should 8639 * be generated, false otherwise. The default value is {@code false} if this was never set. 8640 */ 8641 public boolean getHintContentIntentLaunchesActivity() { 8642 return (mFlags & FLAG_HINT_CONTENT_INTENT_LAUNCHES_ACTIVITY) != 0; 8643 } 8644 8645 /** 8646 * Sets the dismissal id for this notification. If a notification is posted with a 8647 * dismissal id, then when that notification is canceled, notifications on other wearables 8648 * and the paired Android phone having that same dismissal id will also be canceled. See 8649 * <a href="{@docRoot}wear/notifications/index.html">Adding Wearable Features to 8650 * Notifications</a> for more information. 8651 * @param dismissalId the dismissal id of the notification. 8652 * @return this object for method chaining 8653 */ 8654 public WearableExtender setDismissalId(String dismissalId) { 8655 mDismissalId = dismissalId; 8656 return this; 8657 } 8658 8659 /** 8660 * Returns the dismissal id of the notification. 8661 * @return the dismissal id of the notification or null if it has not been set. 8662 */ 8663 public String getDismissalId() { 8664 return mDismissalId; 8665 } 8666 8667 /** 8668 * Sets a bridge tag for this notification. A bridge tag can be set for notifications 8669 * posted from a phone to provide finer-grained control on what notifications are bridged 8670 * to wearables. See <a href="{@docRoot}wear/notifications/index.html">Adding Wearable 8671 * Features to Notifications</a> for more information. 8672 * @param bridgeTag the bridge tag of the notification. 8673 * @return this object for method chaining 8674 */ 8675 public WearableExtender setBridgeTag(String bridgeTag) { 8676 mBridgeTag = bridgeTag; 8677 return this; 8678 } 8679 8680 /** 8681 * Returns the bridge tag of the notification. 8682 * @return the bridge tag or null if not present. 8683 */ 8684 public String getBridgeTag() { 8685 return mBridgeTag; 8686 } 8687 8688 private void setFlag(int mask, boolean value) { 8689 if (value) { 8690 mFlags |= mask; 8691 } else { 8692 mFlags &= ~mask; 8693 } 8694 } 8695 } 8696 8697 /** 8698 * <p>Helper class to add Android Auto extensions to notifications. To create a notification 8699 * with car extensions: 8700 * 8701 * <ol> 8702 * <li>Create an {@link Notification.Builder}, setting any desired 8703 * properties. 8704 * <li>Create a {@link CarExtender}. 8705 * <li>Set car-specific properties using the {@code add} and {@code set} methods of 8706 * {@link CarExtender}. 8707 * <li>Call {@link Notification.Builder#extend(Notification.Extender)} 8708 * to apply the extensions to a notification. 8709 * </ol> 8710 * 8711 * <pre class="prettyprint"> 8712 * Notification notification = new Notification.Builder(context) 8713 * ... 8714 * .extend(new CarExtender() 8715 * .set*(...)) 8716 * .build(); 8717 * </pre> 8718 * 8719 * <p>Car extensions can be accessed on an existing notification by using the 8720 * {@code CarExtender(Notification)} constructor, and then using the {@code get} methods 8721 * to access values. 8722 */ 8723 public static final class CarExtender implements Extender { 8724 private static final String TAG = "CarExtender"; 8725 8726 private static final String EXTRA_CAR_EXTENDER = "android.car.EXTENSIONS"; 8727 private static final String EXTRA_LARGE_ICON = "large_icon"; 8728 private static final String EXTRA_CONVERSATION = "car_conversation"; 8729 private static final String EXTRA_COLOR = "app_color"; 8730 8731 private Bitmap mLargeIcon; 8732 private UnreadConversation mUnreadConversation; 8733 private int mColor = Notification.COLOR_DEFAULT; 8734 8735 /** 8736 * Create a {@link CarExtender} with default options. 8737 */ 8738 public CarExtender() { 8739 } 8740 8741 /** 8742 * Create a {@link CarExtender} from the CarExtender options of an existing Notification. 8743 * 8744 * @param notif The notification from which to copy options. 8745 */ 8746 public CarExtender(Notification notif) { 8747 Bundle carBundle = notif.extras == null ? 8748 null : notif.extras.getBundle(EXTRA_CAR_EXTENDER); 8749 if (carBundle != null) { 8750 mLargeIcon = carBundle.getParcelable(EXTRA_LARGE_ICON); 8751 mColor = carBundle.getInt(EXTRA_COLOR, Notification.COLOR_DEFAULT); 8752 8753 Bundle b = carBundle.getBundle(EXTRA_CONVERSATION); 8754 mUnreadConversation = UnreadConversation.getUnreadConversationFromBundle(b); 8755 } 8756 } 8757 8758 /** 8759 * Apply car extensions to a notification that is being built. This is typically called by 8760 * the {@link Notification.Builder#extend(Notification.Extender)} 8761 * method of {@link Notification.Builder}. 8762 */ 8763 @Override 8764 public Notification.Builder extend(Notification.Builder builder) { 8765 Bundle carExtensions = new Bundle(); 8766 8767 if (mLargeIcon != null) { 8768 carExtensions.putParcelable(EXTRA_LARGE_ICON, mLargeIcon); 8769 } 8770 if (mColor != Notification.COLOR_DEFAULT) { 8771 carExtensions.putInt(EXTRA_COLOR, mColor); 8772 } 8773 8774 if (mUnreadConversation != null) { 8775 Bundle b = mUnreadConversation.getBundleForUnreadConversation(); 8776 carExtensions.putBundle(EXTRA_CONVERSATION, b); 8777 } 8778 8779 builder.getExtras().putBundle(EXTRA_CAR_EXTENDER, carExtensions); 8780 return builder; 8781 } 8782 8783 /** 8784 * Sets the accent color to use when Android Auto presents the notification. 8785 * 8786 * Android Auto uses the color set with {@link Notification.Builder#setColor(int)} 8787 * to accent the displayed notification. However, not all colors are acceptable in an 8788 * automotive setting. This method can be used to override the color provided in the 8789 * notification in such a situation. 8790 */ 8791 public CarExtender setColor(@ColorInt int color) { 8792 mColor = color; 8793 return this; 8794 } 8795 8796 /** 8797 * Gets the accent color. 8798 * 8799 * @see #setColor 8800 */ 8801 @ColorInt 8802 public int getColor() { 8803 return mColor; 8804 } 8805 8806 /** 8807 * Sets the large icon of the car notification. 8808 * 8809 * If no large icon is set in the extender, Android Auto will display the icon 8810 * specified by {@link Notification.Builder#setLargeIcon(android.graphics.Bitmap)} 8811 * 8812 * @param largeIcon The large icon to use in the car notification. 8813 * @return This object for method chaining. 8814 */ 8815 public CarExtender setLargeIcon(Bitmap largeIcon) { 8816 mLargeIcon = largeIcon; 8817 return this; 8818 } 8819 8820 /** 8821 * Gets the large icon used in this car notification, or null if no icon has been set. 8822 * 8823 * @return The large icon for the car notification. 8824 * @see CarExtender#setLargeIcon 8825 */ 8826 public Bitmap getLargeIcon() { 8827 return mLargeIcon; 8828 } 8829 8830 /** 8831 * Sets the unread conversation in a message notification. 8832 * 8833 * @param unreadConversation The unread part of the conversation this notification conveys. 8834 * @return This object for method chaining. 8835 */ 8836 public CarExtender setUnreadConversation(UnreadConversation unreadConversation) { 8837 mUnreadConversation = unreadConversation; 8838 return this; 8839 } 8840 8841 /** 8842 * Returns the unread conversation conveyed by this notification. 8843 * @see #setUnreadConversation(UnreadConversation) 8844 */ 8845 public UnreadConversation getUnreadConversation() { 8846 return mUnreadConversation; 8847 } 8848 8849 /** 8850 * A class which holds the unread messages from a conversation. 8851 */ 8852 public static class UnreadConversation { 8853 private static final String KEY_AUTHOR = "author"; 8854 private static final String KEY_TEXT = "text"; 8855 private static final String KEY_MESSAGES = "messages"; 8856 private static final String KEY_REMOTE_INPUT = "remote_input"; 8857 private static final String KEY_ON_REPLY = "on_reply"; 8858 private static final String KEY_ON_READ = "on_read"; 8859 private static final String KEY_PARTICIPANTS = "participants"; 8860 private static final String KEY_TIMESTAMP = "timestamp"; 8861 8862 private final String[] mMessages; 8863 private final RemoteInput mRemoteInput; 8864 private final PendingIntent mReplyPendingIntent; 8865 private final PendingIntent mReadPendingIntent; 8866 private final String[] mParticipants; 8867 private final long mLatestTimestamp; 8868 8869 UnreadConversation(String[] messages, RemoteInput remoteInput, 8870 PendingIntent replyPendingIntent, PendingIntent readPendingIntent, 8871 String[] participants, long latestTimestamp) { 8872 mMessages = messages; 8873 mRemoteInput = remoteInput; 8874 mReadPendingIntent = readPendingIntent; 8875 mReplyPendingIntent = replyPendingIntent; 8876 mParticipants = participants; 8877 mLatestTimestamp = latestTimestamp; 8878 } 8879 8880 /** 8881 * Gets the list of messages conveyed by this notification. 8882 */ 8883 public String[] getMessages() { 8884 return mMessages; 8885 } 8886 8887 /** 8888 * Gets the remote input that will be used to convey the response to a message list, or 8889 * null if no such remote input exists. 8890 */ 8891 public RemoteInput getRemoteInput() { 8892 return mRemoteInput; 8893 } 8894 8895 /** 8896 * Gets the pending intent that will be triggered when the user replies to this 8897 * notification. 8898 */ 8899 public PendingIntent getReplyPendingIntent() { 8900 return mReplyPendingIntent; 8901 } 8902 8903 /** 8904 * Gets the pending intent that Android Auto will send after it reads aloud all messages 8905 * in this object's message list. 8906 */ 8907 public PendingIntent getReadPendingIntent() { 8908 return mReadPendingIntent; 8909 } 8910 8911 /** 8912 * Gets the participants in the conversation. 8913 */ 8914 public String[] getParticipants() { 8915 return mParticipants; 8916 } 8917 8918 /** 8919 * Gets the firs participant in the conversation. 8920 */ 8921 public String getParticipant() { 8922 return mParticipants.length > 0 ? mParticipants[0] : null; 8923 } 8924 8925 /** 8926 * Gets the timestamp of the conversation. 8927 */ 8928 public long getLatestTimestamp() { 8929 return mLatestTimestamp; 8930 } 8931 8932 Bundle getBundleForUnreadConversation() { 8933 Bundle b = new Bundle(); 8934 String author = null; 8935 if (mParticipants != null && mParticipants.length > 1) { 8936 author = mParticipants[0]; 8937 } 8938 Parcelable[] messages = new Parcelable[mMessages.length]; 8939 for (int i = 0; i < messages.length; i++) { 8940 Bundle m = new Bundle(); 8941 m.putString(KEY_TEXT, mMessages[i]); 8942 m.putString(KEY_AUTHOR, author); 8943 messages[i] = m; 8944 } 8945 b.putParcelableArray(KEY_MESSAGES, messages); 8946 if (mRemoteInput != null) { 8947 b.putParcelable(KEY_REMOTE_INPUT, mRemoteInput); 8948 } 8949 b.putParcelable(KEY_ON_REPLY, mReplyPendingIntent); 8950 b.putParcelable(KEY_ON_READ, mReadPendingIntent); 8951 b.putStringArray(KEY_PARTICIPANTS, mParticipants); 8952 b.putLong(KEY_TIMESTAMP, mLatestTimestamp); 8953 return b; 8954 } 8955 8956 static UnreadConversation getUnreadConversationFromBundle(Bundle b) { 8957 if (b == null) { 8958 return null; 8959 } 8960 Parcelable[] parcelableMessages = b.getParcelableArray(KEY_MESSAGES); 8961 String[] messages = null; 8962 if (parcelableMessages != null) { 8963 String[] tmp = new String[parcelableMessages.length]; 8964 boolean success = true; 8965 for (int i = 0; i < tmp.length; i++) { 8966 if (!(parcelableMessages[i] instanceof Bundle)) { 8967 success = false; 8968 break; 8969 } 8970 tmp[i] = ((Bundle) parcelableMessages[i]).getString(KEY_TEXT); 8971 if (tmp[i] == null) { 8972 success = false; 8973 break; 8974 } 8975 } 8976 if (success) { 8977 messages = tmp; 8978 } else { 8979 return null; 8980 } 8981 } 8982 8983 PendingIntent onRead = b.getParcelable(KEY_ON_READ); 8984 PendingIntent onReply = b.getParcelable(KEY_ON_REPLY); 8985 8986 RemoteInput remoteInput = b.getParcelable(KEY_REMOTE_INPUT); 8987 8988 String[] participants = b.getStringArray(KEY_PARTICIPANTS); 8989 if (participants == null || participants.length != 1) { 8990 return null; 8991 } 8992 8993 return new UnreadConversation(messages, 8994 remoteInput, 8995 onReply, 8996 onRead, 8997 participants, b.getLong(KEY_TIMESTAMP)); 8998 } 8999 }; 9000 9001 /** 9002 * Builder class for {@link CarExtender.UnreadConversation} objects. 9003 */ 9004 public static class Builder { 9005 private final List<String> mMessages = new ArrayList<String>(); 9006 private final String mParticipant; 9007 private RemoteInput mRemoteInput; 9008 private PendingIntent mReadPendingIntent; 9009 private PendingIntent mReplyPendingIntent; 9010 private long mLatestTimestamp; 9011 9012 /** 9013 * Constructs a new builder for {@link CarExtender.UnreadConversation}. 9014 * 9015 * @param name The name of the other participant in the conversation. 9016 */ 9017 public Builder(String name) { 9018 mParticipant = name; 9019 } 9020 9021 /** 9022 * Appends a new unread message to the list of messages for this conversation. 9023 * 9024 * The messages should be added from oldest to newest. 9025 * 9026 * @param message The text of the new unread message. 9027 * @return This object for method chaining. 9028 */ 9029 public Builder addMessage(String message) { 9030 mMessages.add(message); 9031 return this; 9032 } 9033 9034 /** 9035 * Sets the pending intent and remote input which will convey the reply to this 9036 * notification. 9037 * 9038 * @param pendingIntent The pending intent which will be triggered on a reply. 9039 * @param remoteInput The remote input parcelable which will carry the reply. 9040 * @return This object for method chaining. 9041 * 9042 * @see CarExtender.UnreadConversation#getRemoteInput 9043 * @see CarExtender.UnreadConversation#getReplyPendingIntent 9044 */ 9045 public Builder setReplyAction( 9046 PendingIntent pendingIntent, RemoteInput remoteInput) { 9047 mRemoteInput = remoteInput; 9048 mReplyPendingIntent = pendingIntent; 9049 9050 return this; 9051 } 9052 9053 /** 9054 * Sets the pending intent that will be sent once the messages in this notification 9055 * are read. 9056 * 9057 * @param pendingIntent The pending intent to use. 9058 * @return This object for method chaining. 9059 */ 9060 public Builder setReadPendingIntent(PendingIntent pendingIntent) { 9061 mReadPendingIntent = pendingIntent; 9062 return this; 9063 } 9064 9065 /** 9066 * Sets the timestamp of the most recent message in an unread conversation. 9067 * 9068 * If a messaging notification has been posted by your application and has not 9069 * yet been cancelled, posting a later notification with the same id and tag 9070 * but without a newer timestamp may result in Android Auto not displaying a 9071 * heads up notification for the later notification. 9072 * 9073 * @param timestamp The timestamp of the most recent message in the conversation. 9074 * @return This object for method chaining. 9075 */ 9076 public Builder setLatestTimestamp(long timestamp) { 9077 mLatestTimestamp = timestamp; 9078 return this; 9079 } 9080 9081 /** 9082 * Builds a new unread conversation object. 9083 * 9084 * @return The new unread conversation object. 9085 */ 9086 public UnreadConversation build() { 9087 String[] messages = mMessages.toArray(new String[mMessages.size()]); 9088 String[] participants = { mParticipant }; 9089 return new UnreadConversation(messages, mRemoteInput, mReplyPendingIntent, 9090 mReadPendingIntent, participants, mLatestTimestamp); 9091 } 9092 } 9093 } 9094 9095 /** 9096 * <p>Helper class to add Android TV extensions to notifications. To create a notification 9097 * with a TV extension: 9098 * 9099 * <ol> 9100 * <li>Create an {@link Notification.Builder}, setting any desired properties. 9101 * <li>Create a {@link TvExtender}. 9102 * <li>Set TV-specific properties using the {@code set} methods of 9103 * {@link TvExtender}. 9104 * <li>Call {@link Notification.Builder#extend(Notification.Extender)} 9105 * to apply the extension to a notification. 9106 * </ol> 9107 * 9108 * <pre class="prettyprint"> 9109 * Notification notification = new Notification.Builder(context) 9110 * ... 9111 * .extend(new TvExtender() 9112 * .set*(...)) 9113 * .build(); 9114 * </pre> 9115 * 9116 * <p>TV extensions can be accessed on an existing notification by using the 9117 * {@code TvExtender(Notification)} constructor, and then using the {@code get} methods 9118 * to access values. 9119 * 9120 * @hide 9121 */ 9122 @SystemApi 9123 public static final class TvExtender implements Extender { 9124 private static final String TAG = "TvExtender"; 9125 9126 private static final String EXTRA_TV_EXTENDER = "android.tv.EXTENSIONS"; 9127 private static final String EXTRA_FLAGS = "flags"; 9128 private static final String EXTRA_CONTENT_INTENT = "content_intent"; 9129 private static final String EXTRA_DELETE_INTENT = "delete_intent"; 9130 private static final String EXTRA_CHANNEL_ID = "channel_id"; 9131 private static final String EXTRA_SUPPRESS_SHOW_OVER_APPS = "suppressShowOverApps"; 9132 9133 // Flags bitwise-ored to mFlags 9134 private static final int FLAG_AVAILABLE_ON_TV = 0x1; 9135 9136 private int mFlags; 9137 private String mChannelId; 9138 private PendingIntent mContentIntent; 9139 private PendingIntent mDeleteIntent; 9140 private boolean mSuppressShowOverApps; 9141 9142 /** 9143 * Create a {@link TvExtender} with default options. 9144 */ 9145 public TvExtender() { 9146 mFlags = FLAG_AVAILABLE_ON_TV; 9147 } 9148 9149 /** 9150 * Create a {@link TvExtender} from the TvExtender options of an existing Notification. 9151 * 9152 * @param notif The notification from which to copy options. 9153 */ 9154 public TvExtender(Notification notif) { 9155 Bundle bundle = notif.extras == null ? 9156 null : notif.extras.getBundle(EXTRA_TV_EXTENDER); 9157 if (bundle != null) { 9158 mFlags = bundle.getInt(EXTRA_FLAGS); 9159 mChannelId = bundle.getString(EXTRA_CHANNEL_ID); 9160 mSuppressShowOverApps = bundle.getBoolean(EXTRA_SUPPRESS_SHOW_OVER_APPS); 9161 mContentIntent = bundle.getParcelable(EXTRA_CONTENT_INTENT); 9162 mDeleteIntent = bundle.getParcelable(EXTRA_DELETE_INTENT); 9163 } 9164 } 9165 9166 /** 9167 * Apply a TV extension to a notification that is being built. This is typically called by 9168 * the {@link Notification.Builder#extend(Notification.Extender)} 9169 * method of {@link Notification.Builder}. 9170 */ 9171 @Override 9172 public Notification.Builder extend(Notification.Builder builder) { 9173 Bundle bundle = new Bundle(); 9174 9175 bundle.putInt(EXTRA_FLAGS, mFlags); 9176 bundle.putString(EXTRA_CHANNEL_ID, mChannelId); 9177 bundle.putBoolean(EXTRA_SUPPRESS_SHOW_OVER_APPS, mSuppressShowOverApps); 9178 if (mContentIntent != null) { 9179 bundle.putParcelable(EXTRA_CONTENT_INTENT, mContentIntent); 9180 } 9181 9182 if (mDeleteIntent != null) { 9183 bundle.putParcelable(EXTRA_DELETE_INTENT, mDeleteIntent); 9184 } 9185 9186 builder.getExtras().putBundle(EXTRA_TV_EXTENDER, bundle); 9187 return builder; 9188 } 9189 9190 /** 9191 * Returns true if this notification should be shown on TV. This method return true 9192 * if the notification was extended with a TvExtender. 9193 */ 9194 public boolean isAvailableOnTv() { 9195 return (mFlags & FLAG_AVAILABLE_ON_TV) != 0; 9196 } 9197 9198 /** 9199 * Specifies the channel the notification should be delivered on when shown on TV. 9200 * It can be different from the channel that the notification is delivered to when 9201 * posting on a non-TV device. 9202 */ 9203 public TvExtender setChannel(String channelId) { 9204 mChannelId = channelId; 9205 return this; 9206 } 9207 9208 /** 9209 * Specifies the channel the notification should be delivered on when shown on TV. 9210 * It can be different from the channel that the notification is delivered to when 9211 * posting on a non-TV device. 9212 */ 9213 public TvExtender setChannelId(String channelId) { 9214 mChannelId = channelId; 9215 return this; 9216 } 9217 9218 /** @removed */ 9219 @Deprecated 9220 public String getChannel() { 9221 return mChannelId; 9222 } 9223 9224 /** 9225 * Returns the id of the channel this notification posts to on TV. 9226 */ 9227 public String getChannelId() { 9228 return mChannelId; 9229 } 9230 9231 /** 9232 * Supplies a {@link PendingIntent} to be sent when the notification is selected on TV. 9233 * If provided, it is used instead of the content intent specified 9234 * at the level of Notification. 9235 */ 9236 public TvExtender setContentIntent(PendingIntent intent) { 9237 mContentIntent = intent; 9238 return this; 9239 } 9240 9241 /** 9242 * Returns the TV-specific content intent. If this method returns null, the 9243 * main content intent on the notification should be used. 9244 * 9245 * @see {@link Notification#contentIntent} 9246 */ 9247 public PendingIntent getContentIntent() { 9248 return mContentIntent; 9249 } 9250 9251 /** 9252 * Supplies a {@link PendingIntent} to send when the notification is cleared explicitly 9253 * by the user on TV. If provided, it is used instead of the delete intent specified 9254 * at the level of Notification. 9255 */ 9256 public TvExtender setDeleteIntent(PendingIntent intent) { 9257 mDeleteIntent = intent; 9258 return this; 9259 } 9260 9261 /** 9262 * Returns the TV-specific delete intent. If this method returns null, the 9263 * main delete intent on the notification should be used. 9264 * 9265 * @see {@link Notification#deleteIntent} 9266 */ 9267 public PendingIntent getDeleteIntent() { 9268 return mDeleteIntent; 9269 } 9270 9271 /** 9272 * Specifies whether this notification should suppress showing a message over top of apps 9273 * outside of the launcher. 9274 */ 9275 public TvExtender setSuppressShowOverApps(boolean suppress) { 9276 mSuppressShowOverApps = suppress; 9277 return this; 9278 } 9279 9280 /** 9281 * Returns true if this notification should not show messages over top of apps 9282 * outside of the launcher. 9283 */ 9284 public boolean getSuppressShowOverApps() { 9285 return mSuppressShowOverApps; 9286 } 9287 } 9288 9289 /** 9290 * Get an array of Notification objects from a parcelable array bundle field. 9291 * Update the bundle to have a typed array so fetches in the future don't need 9292 * to do an array copy. 9293 */ 9294 private static Notification[] getNotificationArrayFromBundle(Bundle bundle, String key) { 9295 Parcelable[] array = bundle.getParcelableArray(key); 9296 if (array instanceof Notification[] || array == null) { 9297 return (Notification[]) array; 9298 } 9299 Notification[] typedArray = Arrays.copyOf(array, array.length, 9300 Notification[].class); 9301 bundle.putParcelableArray(key, typedArray); 9302 return typedArray; 9303 } 9304 9305 private static class BuilderRemoteViews extends RemoteViews { 9306 public BuilderRemoteViews(Parcel parcel) { 9307 super(parcel); 9308 } 9309 9310 public BuilderRemoteViews(ApplicationInfo appInfo, int layoutId) { 9311 super(appInfo, layoutId); 9312 } 9313 9314 @Override 9315 public BuilderRemoteViews clone() { 9316 Parcel p = Parcel.obtain(); 9317 writeToParcel(p, 0); 9318 p.setDataPosition(0); 9319 BuilderRemoteViews brv = new BuilderRemoteViews(p); 9320 p.recycle(); 9321 return brv; 9322 } 9323 } 9324 9325 private static class StandardTemplateParams { 9326 boolean hasProgress = true; 9327 boolean ambient = false; 9328 CharSequence title; 9329 CharSequence text; 9330 CharSequence headerTextSecondary; 9331 boolean hideLargeIcon; 9332 public boolean alwaysShowReply; 9333 9334 final StandardTemplateParams reset() { 9335 hasProgress = true; 9336 ambient = false; 9337 title = null; 9338 text = null; 9339 headerTextSecondary = null; 9340 return this; 9341 } 9342 9343 final StandardTemplateParams hasProgress(boolean hasProgress) { 9344 this.hasProgress = hasProgress; 9345 return this; 9346 } 9347 9348 final StandardTemplateParams title(CharSequence title) { 9349 this.title = title; 9350 return this; 9351 } 9352 9353 final StandardTemplateParams text(CharSequence text) { 9354 this.text = text; 9355 return this; 9356 } 9357 9358 final StandardTemplateParams headerTextSecondary(CharSequence text) { 9359 this.headerTextSecondary = text; 9360 return this; 9361 } 9362 9363 final StandardTemplateParams alwaysShowReply(boolean alwaysShowReply) { 9364 this.alwaysShowReply = alwaysShowReply; 9365 return this; 9366 } 9367 9368 final StandardTemplateParams hideLargeIcon(boolean hideLargeIcon) { 9369 this.hideLargeIcon = hideLargeIcon; 9370 return this; 9371 } 9372 9373 final StandardTemplateParams ambient(boolean ambient) { 9374 Preconditions.checkState(title == null && text == null, "must set ambient before text"); 9375 this.ambient = ambient; 9376 return this; 9377 } 9378 9379 final StandardTemplateParams fillTextsFrom(Builder b) { 9380 Bundle extras = b.mN.extras; 9381 this.title = b.processLegacyText(extras.getCharSequence(EXTRA_TITLE), ambient); 9382 9383 // Big text notifications should contain their content when viewed in ambient mode. 9384 CharSequence text = extras.getCharSequence(EXTRA_BIG_TEXT); 9385 if (!ambient || TextUtils.isEmpty(text)) { 9386 text = extras.getCharSequence(EXTRA_TEXT); 9387 } 9388 this.text = b.processLegacyText(text, ambient); 9389 return this; 9390 } 9391 } 9392} 9393