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