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