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