Debian Codegraph @

core/java/android/app/Notification.java

raw symbols SCIP
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
17 package android.app;
18
19 import static android.annotation.Dimension.DP;
20 import static android.app.admin.DevicePolicyResources.Drawables.Source.NOTIFICATION;
21 import static android.app.admin.DevicePolicyResources.Drawables.Style.SOLID_COLORED;
22 import static android.app.admin.DevicePolicyResources.Drawables.WORK_PROFILE_ICON;
23 import static android.app.admin.DevicePolicyResources.UNDEFINED;
24 import static android.graphics.drawable.Icon.TYPE_URI;
25 import static android.graphics.drawable.Icon.TYPE_URI_ADAPTIVE_BITMAP;
26
27 import static java.util.Objects.requireNonNull;
28
29 import android.annotation.ColorInt;
30 import android.annotation.ColorRes;
31 import android.annotation.DimenRes;
32 import android.annotation.Dimension;
33 import android.annotation.DrawableRes;
34 import android.annotation.IdRes;
35 import android.annotation.IntDef;
36 import android.annotation.NonNull;
37 import android.annotation.Nullable;
38 import android.annotation.RequiresPermission;
39 import android.annotation.SdkConstant;
40 import android.annotation.SdkConstant.SdkConstantType;
41 import android.annotation.StringRes;
42 import android.annotation.StyleableRes;
43 import android.annotation.SuppressLint;
44 import android.annotation.SystemApi;
45 import android.annotation.TestApi;
46 import android.app.admin.DevicePolicyManager;
47 import android.compat.annotation.UnsupportedAppUsage;
48 import android.content.Context;
49 import android.content.Intent;
50 import android.content.LocusId;
51 import android.content.pm.ApplicationInfo;
52 import android.content.pm.PackageManager;
53 import android.content.pm.PackageManager.NameNotFoundException;
54 import android.content.pm.ShortcutInfo;
55 import android.content.res.ColorStateList;
56 import android.content.res.Configuration;
57 import android.content.res.Resources;
58 import android.content.res.TypedArray;
59 import android.graphics.Bitmap;
60 import android.graphics.Canvas;
61 import android.graphics.Color;
62 import android.graphics.PorterDuff;
63 import android.graphics.drawable.Drawable;
64 import android.graphics.drawable.Icon;
65 import android.media.AudioAttributes;
66 import android.media.AudioManager;
67 import android.media.PlayerBase;
68 import android.media.session.MediaSession;
69 import android.net.Uri;
70 import android.os.BadParcelableException;
71 import android.os.Build;
72 import android.os.Bundle;
73 import android.os.IBinder;
74 import android.os.Parcel;
75 import android.os.Parcelable;
76 import android.os.SystemClock;
77 import android.os.SystemProperties;
78 import android.os.UserHandle;
79 import android.os.UserManager;
80 import android.provider.Settings;
81 import android.text.BidiFormatter;
82 import android.text.SpannableStringBuilder;
83 import android.text.Spanned;
84 import android.text.TextUtils;
85 import android.text.style.AbsoluteSizeSpan;
86 import android.text.style.CharacterStyle;
87 import android.text.style.ForegroundColorSpan;
88 import android.text.style.RelativeSizeSpan;
89 import android.text.style.TextAppearanceSpan;
90 import android.util.ArraySet;
91 import android.util.Log;
92 import android.util.Pair;
93 import android.util.SparseArray;
94 import android.util.TypedValue;
95 import android.util.proto.ProtoOutputStream;
96 import android.view.ContextThemeWrapper;
97 import android.view.Gravity;
98 import android.view.View;
99 import android.view.contentcapture.ContentCaptureContext;
100 import android.widget.ProgressBar;
101 import android.widget.RemoteViews;
102
103 import com.android.internal.R;
104 import com.android.internal.annotations.VisibleForTesting;
105 import com.android.internal.graphics.ColorUtils;
106 import com.android.internal.util.ArrayUtils;
107 import com.android.internal.util.ContrastColorUtil;
108
109 import java.lang.annotation.Retention;
110 import java.lang.annotation.RetentionPolicy;
111 import java.lang.reflect.Array;
112 import java.lang.reflect.Constructor;
113 import java.util.ArrayList;
114 import java.util.Arrays;
115 import java.util.Collections;
116 import java.util.List;
117 import java.util.Objects;
118 import java.util.Set;
119 import java.util.function.Consumer;
120
121 /**
122 * A class that represents how a persistent notification is to be presented to
123 * the user using the {@link android.app.NotificationManager}.
124 *
125 * <p>The {@link Notification.Builder Notification.Builder} has been added to make it
126 * easier to construct Notifications.</p>
127 *
128 * <div class="special reference">
129 * <h3>Developer Guides</h3>
130 * <p>For a guide to creating notifications, read the
131 * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a>
132 * developer guide.</p>
133 * </div>
134 */
135 public class Notification implements Parcelable
136 {
137 private static final String TAG = "Notification";
138
139 /**
140 * @hide
141 */
142 @Retention(RetentionPolicy.SOURCE)
143 @IntDef({
144 FOREGROUND_SERVICE_DEFAULT,
145 FOREGROUND_SERVICE_IMMEDIATE,
146 FOREGROUND_SERVICE_DEFERRED
147 })
148 public @interface ServiceNotificationPolicy {};
149
150 /**
151 * If the Notification associated with starting a foreground service has been
152 * built using setForegroundServiceBehavior() with this behavior, display of
153 * the notification will usually be suppressed for a short time to avoid visual
154 * disturbances to the user.
155 * @see Notification.Builder#setForegroundServiceBehavior(int)
156 * @see #FOREGROUND_SERVICE_IMMEDIATE
157 * @see #FOREGROUND_SERVICE_DEFERRED
158 */
159 public static final @ServiceNotificationPolicy int FOREGROUND_SERVICE_DEFAULT = 0;
160
161 /**
162 * If the Notification associated with starting a foreground service has been
163 * built using setForegroundServiceBehavior() with this behavior, display of
164 * the notification will be immediate even if the default behavior would be
165 * to defer visibility for a short time.
166 * @see Notification.Builder#setForegroundServiceBehavior(int)
167 * @see #FOREGROUND_SERVICE_DEFAULT
168 * @see #FOREGROUND_SERVICE_DEFERRED
169 */
170 public static final @ServiceNotificationPolicy int FOREGROUND_SERVICE_IMMEDIATE = 1;
171
172 /**
173 * If the Notification associated with starting a foreground service has been
174 * built using setForegroundServiceBehavior() with this behavior, display of
175 * the notification will usually be suppressed for a short time to avoid visual
176 * disturbances to the user.
177 * @see Notification.Builder#setForegroundServiceBehavior(int)
178 * @see #FOREGROUND_SERVICE_DEFAULT
179 * @see #FOREGROUND_SERVICE_IMMEDIATE
180 */
181 public static final @ServiceNotificationPolicy int FOREGROUND_SERVICE_DEFERRED = 2;
182
183 @ServiceNotificationPolicy
184 private int mFgsDeferBehavior;
185
186 /**
187 * An activity that provides a user interface for adjusting notification preferences for its
188 * containing application.
189 */
190 @SdkConstant(SdkConstantType.INTENT_CATEGORY)
191 public static final String INTENT_CATEGORY_NOTIFICATION_PREFERENCES
192 = "android.intent.category.NOTIFICATION_PREFERENCES";
193
194 /**
195 * Optional extra for {@link #INTENT_CATEGORY_NOTIFICATION_PREFERENCES}. If provided, will
196 * contain a {@link NotificationChannel#getId() channel id} that can be used to narrow down
197 * what settings should be shown in the target app.
198 */
199 public static final String EXTRA_CHANNEL_ID = "android.intent.extra.CHANNEL_ID";
200
201 /**
202 * Optional extra for {@link #INTENT_CATEGORY_NOTIFICATION_PREFERENCES}. If provided, will
203 * contain a {@link NotificationChannelGroup#getId() group id} that can be used to narrow down
204 * what settings should be shown in the target app.
205 */
206 public static final String EXTRA_CHANNEL_GROUP_ID = "android.intent.extra.CHANNEL_GROUP_ID";
207
208 /**
209 * Optional extra for {@link #INTENT_CATEGORY_NOTIFICATION_PREFERENCES}. If provided, will
210 * contain the tag provided to {@link NotificationManager#notify(String, int, Notification)}
211 * that can be used to narrow down what settings should be shown in the target app.
212 */
213 public static final String EXTRA_NOTIFICATION_TAG = "android.intent.extra.NOTIFICATION_TAG";
214
215 /**
216 * Optional extra for {@link #INTENT_CATEGORY_NOTIFICATION_PREFERENCES}. If provided, will
217 * contain the id provided to {@link NotificationManager#notify(String, int, Notification)}
218 * that can be used to narrow down what settings should be shown in the target app.
219 */
220 public static final String EXTRA_NOTIFICATION_ID = "android.intent.extra.NOTIFICATION_ID";
221
222 /**
223 * Use all default values (where applicable).
224 */
225 public static final int DEFAULT_ALL = ~0;
226
227 /**
228 * Use the default notification sound. This will ignore any given
229 * {@link #sound}.
230 *
231 * <p>
232 * A notification that is noisy is more likely to be presented as a heads-up notification.
233 * </p>
234 *
235 * @see #defaults
236 */
237
238 public static final int DEFAULT_SOUND = 1;
239
240 /**
241 * Use the default notification vibrate. This will ignore any given
242 * {@link #vibrate}. Using phone vibration requires the
243 * {@link android.Manifest.permission#VIBRATE VIBRATE} permission.
244 *
245 * <p>
246 * A notification that vibrates is more likely to be presented as a heads-up notification.
247 * </p>
248 *
249 * @see #defaults
250 */
251
252 public static final int DEFAULT_VIBRATE = 2;
253
254 /**
255 * Use the default notification lights. This will ignore the
256 * {@link #FLAG_SHOW_LIGHTS} bit, and {@link #ledARGB}, {@link #ledOffMS}, or
257 * {@link #ledOnMS}.
258 *
259 * @see #defaults
260 */
261
262 public static final int DEFAULT_LIGHTS = 4;
263
264 /**
265 * Maximum length of CharSequences accepted by Builder and friends.
266 *
267 * <p>
268 * Avoids spamming the system with overly large strings such as full e-mails.
269 */
270 private static final int MAX_CHARSEQUENCE_LENGTH = 1024;
271
272 /**
273 * Maximum entries of reply text that are accepted by Builder and friends.
274 */
275 private static final int MAX_REPLY_HISTORY = 5;
276
277 /**
278 * Maximum aspect ratio of the large icon. 16:9
279 */
280 private static final float MAX_LARGE_ICON_ASPECT_RATIO = 16f / 9f;
281
282 /**
283 * Maximum number of (generic) action buttons in a notification (contextual action buttons are
284 * handled separately).
285 * @hide
286 */
287 public static final int MAX_ACTION_BUTTONS = 3;
288
289 /**
290 * If the notification contained an unsent draft for a RemoteInput when the user clicked on it,
291 * we're adding the draft as a String extra to the {@link #contentIntent} using this key.
292 *
293 * <p>Apps may use this extra to prepopulate text fields in the app, where the user usually
294 * sends messages.</p>
295 */
296 public static final String EXTRA_REMOTE_INPUT_DRAFT = "android.remoteInputDraft";
297
298 /**
299 * A timestamp related to this notification, in milliseconds since the epoch.
300 *
301 * Default value: {@link System#currentTimeMillis() Now}.
302 *
303 * Choose a timestamp that will be most relevant to the user. For most finite events, this
304 * corresponds to the time the event happened (or will happen, in the case of events that have
305 * yet to occur but about which the user is being informed). Indefinite events should be
306 * timestamped according to when the activity began.
307 *
308 * Some examples:
309 *
310 * <ul>
311 * <li>Notification of a new chat message should be stamped when the message was received.</li>
312 * <li>Notification of an ongoing file download (with a progress bar, for example) should be stamped when the download started.</li>
313 * <li>Notification of a completed file download should be stamped when the download finished.</li>
314 * <li>Notification of an upcoming meeting should be stamped with the time the meeting will begin (that is, in the future).</li>
315 * <li>Notification of an ongoing stopwatch (increasing timer) should be stamped with the watch's start time.
316 * <li>Notification of an ongoing countdown timer should be stamped with the timer's end time.
317 * </ul>
318 *
319 * For apps targeting {@link android.os.Build.VERSION_CODES#N} and above, this time is not shown
320 * anymore by default and must be opted into by using
321 * {@link android.app.Notification.Builder#setShowWhen(boolean)}
322 */
323 public long when;
324
325 /**
326 * The creation time of the notification
327 */
328 private long creationTime;
329
330 /**
331 * The resource id of a drawable to use as the icon in the status bar.
332 *
333 * @deprecated Use {@link Builder#setSmallIcon(Icon)} instead.
334 */
335 @Deprecated
336 @DrawableRes
337 public int icon;
338
339 /**
340 * If the icon in the status bar is to have more than one level, you can set this. Otherwise,
341 * leave it at its default value of 0.
342 *
343 * @see android.widget.ImageView#setImageLevel
344 * @see android.graphics.drawable.Drawable#setLevel
345 */
346 public int iconLevel;
347
348 /**
349 * The number of events that this notification represents. For example, in a new mail
350 * notification, this could be the number of unread messages.
351 *
352 * The system may or may not use this field to modify the appearance of the notification.
353 * Starting with {@link android.os.Build.VERSION_CODES#O}, the number may be displayed as a
354 * badge icon in Launchers that support badging.
355 */
356 public int number = 0;
357
358 /**
359 * The intent to execute when the expanded status entry is clicked. If
360 * this is an activity, it must include the
361 * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires
362 * that you take care of task management as described in the
363 * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back
364 * Stack</a> document. In particular, make sure to read the
365 * <a href="{@docRoot}/training/notify-user/navigation">Start
366 * an Activity from a Notification</a> page for the correct ways to launch an application from a
367 * notification.
368 */
369 public PendingIntent contentIntent;
370
371 /**
372 * The intent to execute when the notification is explicitly dismissed by the user, either with
373 * the "Clear All" button or by swiping it away individually.
374 *
375 * This probably shouldn't be launching an activity since several of those will be sent
376 * at the same time.
377 */
378 public PendingIntent deleteIntent;
379
380 /**
381 * An intent to launch instead of posting the notification to the status bar.
382 *
383 * <p>
384 * The system UI may choose to display a heads-up notification, instead of
385 * launching this intent, while the user is using the device.
386 * </p>
387 *
388 * @see Notification.Builder#setFullScreenIntent
389 */
390 public PendingIntent fullScreenIntent;
391
392 /**
393 * Text that summarizes this notification for accessibility services.
394 *
395 * As of the L release, this text is no longer shown on screen, but it is still useful to
396 * accessibility services (where it serves as an audible announcement of the notification's
397 * appearance).
398 *
399 * @see #tickerView
400 */
401 public CharSequence tickerText;
402
403 /**
404 * Formerly, a view showing the {@link #tickerText}.
405 *
406 * No longer displayed in the status bar as of API 21.
407 */
408 @Deprecated
409 public RemoteViews tickerView;
410
411 /**
412 * The view that will represent this notification in the notification list (which is pulled
413 * down from the status bar).
414 *
415 * As of N, this field may be null. The notification view is determined by the inputs
416 * to {@link Notification.Builder}; a custom RemoteViews can optionally be
417 * supplied with {@link Notification.Builder#setCustomContentView(RemoteViews)}.
418 */
419 @Deprecated
420 public RemoteViews contentView;
421
422 /**
423 * A large-format version of {@link #contentView}, giving the Notification an
424 * opportunity to show more detail. The system UI may choose to show this
425 * instead of the normal content view at its discretion.
426 *
427 * As of N, this field may be null. The expanded notification view is determined by the
428 * inputs to {@link Notification.Builder}; a custom RemoteViews can optionally be
429 * supplied with {@link Notification.Builder#setCustomBigContentView(RemoteViews)}.
430 */
431 @Deprecated
432 public RemoteViews bigContentView;
433
434
435 /**
436 * A medium-format version of {@link #contentView}, providing the Notification an
437 * opportunity to add action buttons to contentView. At its discretion, the system UI may
438 * choose to show this as a heads-up notification, which will pop up so the user can see
439 * it without leaving their current activity.
440 *
441 * As of N, this field may be null. The heads-up notification view is determined by the
442 * inputs to {@link Notification.Builder}; a custom RemoteViews can optionally be
443 * supplied with {@link Notification.Builder#setCustomHeadsUpContentView(RemoteViews)}.
444 */
445 @Deprecated
446 public RemoteViews headsUpContentView;
447
448 private boolean mUsesStandardHeader;
449
450 private static final ArraySet<Integer> STANDARD_LAYOUTS = new ArraySet<>();
451 static {
452 STANDARD_LAYOUTS.add(R.layout.notification_template_material_base);
453 STANDARD_LAYOUTS.add(R.layout.notification_template_material_heads_up_base);
454 STANDARD_LAYOUTS.add(R.layout.notification_template_material_big_base);
455 STANDARD_LAYOUTS.add(R.layout.notification_template_material_big_picture);
456 STANDARD_LAYOUTS.add(R.layout.notification_template_material_big_text);
457 STANDARD_LAYOUTS.add(R.layout.notification_template_material_inbox);
458 STANDARD_LAYOUTS.add(R.layout.notification_template_material_messaging);
459 STANDARD_LAYOUTS.add(R.layout.notification_template_material_big_messaging);
460 STANDARD_LAYOUTS.add(R.layout.notification_template_material_conversation);
461 STANDARD_LAYOUTS.add(R.layout.notification_template_material_media);
462 STANDARD_LAYOUTS.add(R.layout.notification_template_material_big_media);
463 STANDARD_LAYOUTS.add(R.layout.notification_template_material_call);
464 STANDARD_LAYOUTS.add(R.layout.notification_template_material_big_call);
465 STANDARD_LAYOUTS.add(R.layout.notification_template_header);
466 }
467
468 /**
469 * A large bitmap to be shown in the notification content area.
470 *
471 * @deprecated Use {@link Builder#setLargeIcon(Icon)} instead.
472 */
473 @Deprecated
474 public Bitmap largeIcon;
475
476 /**
477 * The sound to play.
478 *
479 * <p>
480 * A notification that is noisy is more likely to be presented as a heads-up notification.
481 * </p>
482 *
483 * <p>
484 * To play the default notification sound, see {@link #defaults}.
485 * </p>
486 * @deprecated use {@link NotificationChannel#getSound()}.
487 */
488 @Deprecated
489 public Uri sound;
490
491 /**
492 * Use this constant as the value for audioStreamType to request that
493 * the default stream type for notifications be used. Currently the
494 * default stream type is {@link AudioManager#STREAM_NOTIFICATION}.
495 *
496 * @deprecated Use {@link NotificationChannel#getAudioAttributes()} instead.
497 */
498 @Deprecated
499 public static final int STREAM_DEFAULT = -1;
500
501 /**
502 * The audio stream type to use when playing the sound.
503 * Should be one of the STREAM_ constants from
504 * {@link android.media.AudioManager}.
505 *
506 * @deprecated Use {@link #audioAttributes} instead.
507 */
508 @Deprecated
509 public int audioStreamType = STREAM_DEFAULT;
510
511 /**
512 * The default value of {@link #audioAttributes}.
513 */
514 public static final AudioAttributes AUDIO_ATTRIBUTES_DEFAULT = new AudioAttributes.Builder()
515 .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
516 .setUsage(AudioAttributes.USAGE_NOTIFICATION)
517 .build();
518
519 /**
520 * The {@link AudioAttributes audio attributes} to use when playing the sound.
521 *
522 * @deprecated use {@link NotificationChannel#getAudioAttributes()} instead.
523 */
524 @Deprecated
525 public AudioAttributes audioAttributes = AUDIO_ATTRIBUTES_DEFAULT;
526
527 /**
528 * The pattern with which to vibrate.
529 *
530 * <p>
531 * To vibrate the default pattern, see {@link #defaults}.
532 * </p>
533 *
534 * @see android.os.Vibrator#vibrate(long[],int)
535 * @deprecated use {@link NotificationChannel#getVibrationPattern()}.
536 */
537 @Deprecated
538 public long[] vibrate;
539
540 /**
541 * The color of the led. The hardware will do its best approximation.
542 *
543 * @see #FLAG_SHOW_LIGHTS
544 * @see #flags
545 * @deprecated use {@link NotificationChannel#shouldShowLights()}.
546 */
547 @ColorInt
548 @Deprecated
549 public int ledARGB;
550
551 /**
552 * The number of milliseconds for the LED to be on while it's flashing.
553 * The hardware will do its best approximation.
554 *
555 * @see #FLAG_SHOW_LIGHTS
556 * @see #flags
557 * @deprecated use {@link NotificationChannel#shouldShowLights()}.
558 */
559 @Deprecated
560 public int ledOnMS;
561
562 /**
563 * The number of milliseconds for the LED to be off while it's flashing.
564 * The hardware will do its best approximation.
565 *
566 * @see #FLAG_SHOW_LIGHTS
567 * @see #flags
568 *
569 * @deprecated use {@link NotificationChannel#shouldShowLights()}.
570 */
571 @Deprecated
572 public int ledOffMS;
573
574 /**
575 * Specifies which values should be taken from the defaults.
576 * <p>
577 * To set, OR the desired from {@link #DEFAULT_SOUND},
578 * {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}. For all default
579 * values, use {@link #DEFAULT_ALL}.
580 * </p>
581 *
582 * @deprecated use {@link NotificationChannel#getSound()} and
583 * {@link NotificationChannel#shouldShowLights()} and
584 * {@link NotificationChannel#shouldVibrate()}.
585 */
586 @Deprecated
587 public int defaults;
588
589 /**
590 * Bit to be bitwise-ored into the {@link #flags} field that should be
591 * set if you want the LED on for this notification.
592 * <ul>
593 * <li>To turn the LED off, pass 0 in the alpha channel for colorARGB
594 * or 0 for both ledOnMS and ledOffMS.</li>
595 * <li>To turn the LED on, pass 1 for ledOnMS and 0 for ledOffMS.</li>
596 * <li>To flash the LED, pass the number of milliseconds that it should
597 * be on and off to ledOnMS and ledOffMS.</li>
598 * </ul>
599 * <p>
600 * Since hardware varies, you are not guaranteed that any of the values
601 * you pass are honored exactly. Use the system defaults if possible
602 * because they will be set to values that work on any given hardware.
603 * <p>
604 * The alpha channel must be set for forward compatibility.
605 *
606 * @deprecated use {@link NotificationChannel#shouldShowLights()}.
607 */
608 @Deprecated
609 public static final int FLAG_SHOW_LIGHTS = 0x00000001;
610
611 /**
612 * Bit to be bitwise-ored into the {@link #flags} field that should be
613 * set if this notification is in reference to something that is ongoing,
614 * like a phone call. It should not be set if this notification is in
615 * reference to something that happened at a particular point in time,
616 * like a missed phone call.
617 */
618 public static final int FLAG_ONGOING_EVENT = 0x00000002;
619
620 /**
621 * Bit to be bitwise-ored into the {@link #flags} field that if set,
622 * the audio will be repeated until the notification is
623 * cancelled or the notification window is opened.
624 */
625 public static final int FLAG_INSISTENT = 0x00000004;
626
627 /**
628 * Bit to be bitwise-ored into the {@link #flags} field that should be
629 * set if you would only like the sound, vibrate and ticker to be played
630 * if the notification was not already showing.
631 *
632 * Note that using this flag will stop any ongoing alerting behaviour such
633 * as sound, vibration or blinking notification LED.
634 */
635 public static final int FLAG_ONLY_ALERT_ONCE = 0x00000008;
636
637 /**
638 * Bit to be bitwise-ored into the {@link #flags} field that should be
639 * set if the notification should be canceled when it is clicked by the
640 * user.
641 */
642 public static final int FLAG_AUTO_CANCEL = 0x00000010;
643
644 /**
645 * Bit to be bitwise-ored into the {@link #flags} field that should be
646 * set if the notification should not be canceled when the user clicks
647 * the Clear all button.
648 */
649 public static final int FLAG_NO_CLEAR = 0x00000020;
650
651 /**
652 * Bit to be bitwise-ored into the {@link #flags} field that should be
653 * set if this notification represents a currently running service. This
654 * will normally be set for you by {@link Service#startForeground}.
655 */
656 public static final int FLAG_FOREGROUND_SERVICE = 0x00000040;
657
658 /**
659 * Obsolete flag indicating high-priority notifications; use the priority field instead.
660 *
661 * @deprecated Use {@link #priority} with a positive value.
662 */
663 @Deprecated
664 public static final int FLAG_HIGH_PRIORITY = 0x00000080;
665
666 /**
667 * Bit to be bitswise-ored into the {@link #flags} field that should be
668 * set if this notification is relevant to the current device only
669 * and it is not recommended that it bridge to other devices.
670 */
671 public static final int FLAG_LOCAL_ONLY = 0x00000100;
672
673 /**
674 * Bit to be bitswise-ored into the {@link #flags} field that should be
675 * set if this notification is the group summary for a group of notifications.
676 * Grouped notifications may display in a cluster or stack on devices which
677 * support such rendering. Requires a group key also be set using {@link Builder#setGroup}.
678 */
679 public static final int FLAG_GROUP_SUMMARY = 0x00000200;
680
681 /**
682 * Bit to be bitswise-ored into the {@link #flags} field that should be
683 * set if this notification is the group summary for an auto-group of notifications.
684 *
685 * @hide
686 */
687 @SystemApi
688 public static final int FLAG_AUTOGROUP_SUMMARY = 0x00000400;
689
690 /**
691 * @hide
692 */
693 public static final int FLAG_CAN_COLORIZE = 0x00000800;
694
695 /**
696 * Bit to be bitswised-ored into the {@link #flags} field that should be
697 * set by the system if this notification is showing as a bubble.
698 *
699 * Applications cannot set this flag directly; they should instead call
700 * {@link Notification.Builder#setBubbleMetadata(BubbleMetadata)} to
701 * request that a notification be displayed as a bubble, and then check
702 * this flag to see whether that request was honored by the system.
703 */
704 public static final int FLAG_BUBBLE = 0x00001000;
705
706 private static final List<Class<? extends Style>> PLATFORM_STYLE_CLASSES = Arrays.asList(
707 BigTextStyle.class, BigPictureStyle.class, InboxStyle.class, MediaStyle.class,
708 DecoratedCustomViewStyle.class, DecoratedMediaCustomViewStyle.class,
709 MessagingStyle.class, CallStyle.class);
710
711 /** @hide */
712 @IntDef(flag = true, prefix = { "FLAG_" }, value = {FLAG_SHOW_LIGHTS, FLAG_ONGOING_EVENT,
713 FLAG_INSISTENT, FLAG_ONLY_ALERT_ONCE,
714 FLAG_AUTO_CANCEL, FLAG_NO_CLEAR, FLAG_FOREGROUND_SERVICE, FLAG_HIGH_PRIORITY,
715 FLAG_LOCAL_ONLY, FLAG_GROUP_SUMMARY, FLAG_AUTOGROUP_SUMMARY, FLAG_BUBBLE})
716 @Retention(RetentionPolicy.SOURCE)
717 public @interface NotificationFlags{};
718
719 public int flags;
720
721 /** @hide */
722 @IntDef(prefix = { "PRIORITY_" }, value = {
723 PRIORITY_DEFAULT,
724 PRIORITY_LOW,
725 PRIORITY_MIN,
726 PRIORITY_HIGH,
727 PRIORITY_MAX
728 })
729 @Retention(RetentionPolicy.SOURCE)
730 public @interface Priority {}
731
732 /**
733 * Default notification {@link #priority}. If your application does not prioritize its own
734 * notifications, use this value for all notifications.
735 *
736 * @deprecated use {@link NotificationManager#IMPORTANCE_DEFAULT} instead.
737 */
738 @Deprecated
739 public static final int PRIORITY_DEFAULT = 0;
740
741 /**
742 * Lower {@link #priority}, for items that are less important. The UI may choose to show these
743 * items smaller, or at a different position in the list, compared with your app's
744 * {@link #PRIORITY_DEFAULT} items.
745 *
746 * @deprecated use {@link NotificationManager#IMPORTANCE_LOW} instead.
747 */
748 @Deprecated
749 public static final int PRIORITY_LOW = -1;
750
751 /**
752 * Lowest {@link #priority}; these items might not be shown to the user except under special
753 * circumstances, such as detailed notification logs.
754 *
755 * @deprecated use {@link NotificationManager#IMPORTANCE_MIN} instead.
756 */
757 @Deprecated
758 public static final int PRIORITY_MIN = -2;
759
760 /**
761 * Higher {@link #priority}, for more important notifications or alerts. The UI may choose to
762 * show these items larger, or at a different position in notification lists, compared with
763 * your app's {@link #PRIORITY_DEFAULT} items.
764 *
765 * @deprecated use {@link NotificationManager#IMPORTANCE_HIGH} instead.
766 */
767 @Deprecated
768 public static final int PRIORITY_HIGH = 1;
769
770 /**
771 * Highest {@link #priority}, for your application's most important items that require the
772 * user's prompt attention or input.
773 *
774 * @deprecated use {@link NotificationManager#IMPORTANCE_HIGH} instead.
775 */
776 @Deprecated
777 public static final int PRIORITY_MAX = 2;
778
779 /**
780 * Relative priority for this notification.
781 *
782 * Priority is an indication of how much of the user's valuable attention should be consumed by
783 * this notification. Low-priority notifications may be hidden from the user in certain
784 * situations, while the user might be interrupted for a higher-priority notification. The
785 * system will make a determination about how to interpret this priority when presenting
786 * the notification.
787 *
788 * <p>
789 * A notification that is at least {@link #PRIORITY_HIGH} is more likely to be presented
790 * as a heads-up notification.
791 * </p>
792 *
793 * @deprecated use {@link NotificationChannel#getImportance()} instead.
794 */
795 @Priority
796 @Deprecated
797 public int priority;
798
799 /**
800 * Accent color (an ARGB integer like the constants in {@link android.graphics.Color})
801 * to be applied by the standard Style templates when presenting this notification.
802 *
803 * The current template design constructs a colorful header image by overlaying the
804 * {@link #icon} image (stenciled in white) atop a field of this color. Alpha components are
805 * ignored.
806 */
807 @ColorInt
808 public int color = COLOR_DEFAULT;
809
810 /**
811 * Special value of {@link #color} telling the system not to decorate this notification with
812 * any special color but instead use default colors when presenting this notification.
813 */
814 @ColorInt
815 public static final int COLOR_DEFAULT = 0; // AKA Color.TRANSPARENT
816
817 /**
818 * Special value of {@link #color} used as a place holder for an invalid color.
819 * @hide
820 */
821 @ColorInt
822 public static final int COLOR_INVALID = 1;
823
824 /**
825 * Sphere of visibility of this notification, which affects how and when the SystemUI reveals
826 * the notification's presence and contents in untrusted situations (namely, on the secure
827 * lockscreen).
828 *
829 * The default level, {@link #VISIBILITY_PRIVATE}, behaves exactly as notifications have always
830 * done on Android: The notification's {@link #icon} and {@link #tickerText} (if available) are
831 * shown in all situations, but the contents are only available if the device is unlocked for
832 * the appropriate user.
833 *
834 * A more permissive policy can be expressed by {@link #VISIBILITY_PUBLIC}; such a notification
835 * can be read even in an "insecure" context (that is, above a secure lockscreen).
836 * To modify the public version of this notification—for example, to redact some portions—see
837 * {@link Builder#setPublicVersion(Notification)}.
838 *
839 * Finally, a notification can be made {@link #VISIBILITY_SECRET}, which will suppress its icon
840 * and ticker until the user has bypassed the lockscreen.
841 */
842 public @Visibility int visibility;
843
844 /** @hide */
845 @IntDef(prefix = { "VISIBILITY_" }, value = {
846 VISIBILITY_PUBLIC,
847 VISIBILITY_PRIVATE,
848 VISIBILITY_SECRET,
849 })
850 @Retention(RetentionPolicy.SOURCE)
851 public @interface Visibility {}
852
853 /**
854 * Notification visibility: Show this notification in its entirety on all lockscreens.
855 *
856 * {@see #visibility}
857 */
858 public static final int VISIBILITY_PUBLIC = 1;
859
860 /**
861 * Notification visibility: Show this notification on all lockscreens, but conceal sensitive or
862 * private information on secure lockscreens.
863 *
864 * {@see #visibility}
865 */
866 public static final int VISIBILITY_PRIVATE = 0;
867
868 /**
869 * Notification visibility: Do not reveal any part of this notification on a secure lockscreen.
870 *
871 * {@see #visibility}
872 */
873 public static final int VISIBILITY_SECRET = -1;
874
875 /**
876 * @hide
877 */
878 @IntDef(prefix = "VISIBILITY_", value = {
879 VISIBILITY_PUBLIC,
880 VISIBILITY_PRIVATE,
881 VISIBILITY_SECRET,
882 NotificationManager.VISIBILITY_NO_OVERRIDE
883 })
884 public @interface NotificationVisibilityOverride{};
885
886 /**
887 * Notification category: incoming call (voice or video) or similar synchronous communication request.
888 */
889 public static final String CATEGORY_CALL = "call";
890
891 /**
892 * Notification category: map turn-by-turn navigation.
893 */
894 public static final String CATEGORY_NAVIGATION = "navigation";
895
896 /**
897 * Notification category: incoming direct message (SMS, instant message, etc.).
898 */
899 public static final String CATEGORY_MESSAGE = "msg";
900
901 /**
902 * Notification category: asynchronous bulk message (email).
903 */
904 public static final String CATEGORY_EMAIL = "email";
905
906 /**
907 * Notification category: calendar event.
908 */
909 public static final String CATEGORY_EVENT = "event";
910
911 /**
912 * Notification category: promotion or advertisement.
913 */
914 public static final String CATEGORY_PROMO = "promo";
915
916 /**
917 * Notification category: alarm or timer.
918 */
919 public static final String CATEGORY_ALARM = "alarm";
920
921 /**
922 * Notification category: progress of a long-running background operation.
923 */
924 public static final String CATEGORY_PROGRESS = "progress";
925
926 /**
927 * Notification category: social network or sharing update.
928 */
929 public static final String CATEGORY_SOCIAL = "social";
930
931 /**
932 * Notification category: error in background operation or authentication status.
933 */
934 public static final String CATEGORY_ERROR = "err";
935
936 /**
937 * Notification category: media transport control for playback.
938 */
939 public static final String CATEGORY_TRANSPORT = "transport";
940
941 /**
942 * Notification category: system or device status update. Reserved for system use.
943 */
944 public static final String CATEGORY_SYSTEM = "sys";
945
946 /**
947 * Notification category: indication of running background service.
948 */
949 public static final String CATEGORY_SERVICE = "service";
950
951 /**
952 * Notification category: a specific, timely recommendation for a single thing.
953 * For example, a news app might want to recommend a news story it believes the user will
954 * want to read next.
955 */
956 public static final String CATEGORY_RECOMMENDATION = "recommendation";
957
958 /**
959 * Notification category: ongoing information about device or contextual status.
960 */
961 public static final String CATEGORY_STATUS = "status";
962
963 /**
964 * Notification category: user-scheduled reminder.
965 */
966 public static final String CATEGORY_REMINDER = "reminder";
967
968 /**
969 * Notification category: extreme car emergencies.
970 * @hide
971 */
972 @SystemApi
973 public static final String CATEGORY_CAR_EMERGENCY = "car_emergency";
974
975 /**
976 * Notification category: car warnings.
977 * @hide
978 */
979 @SystemApi
980 public static final String CATEGORY_CAR_WARNING = "car_warning";
981
982 /**
983 * Notification category: general car system information.
984 * @hide
985 */
986 @SystemApi
987 public static final String CATEGORY_CAR_INFORMATION = "car_information";
988
989 /**
990 * Notification category: tracking a user's workout.
991 */
992 public static final String CATEGORY_WORKOUT = "workout";
993
994 /**
995 * Notification category: temporarily sharing location.
996 */
997 public static final String CATEGORY_LOCATION_SHARING = "location_sharing";
998
999 /**
1000 * Notification category: running stopwatch.
1001 */
1002 public static final String CATEGORY_STOPWATCH = "stopwatch";
1003
1004 /**
1005 * Notification category: missed call.
1006 */
1007 public static final String CATEGORY_MISSED_CALL = "missed_call";
1008
1009 /**
1010 * One of the predefined notification categories (see the <code>CATEGORY_*</code> constants)
1011 * that best describes this Notification. May be used by the system for ranking and filtering.
1012 */
1013 public String category;
1014
1015 @UnsupportedAppUsage
1016 private String mGroupKey;
1017
1018 /**
1019 * Get the key used to group this notification into a cluster or stack
1020 * with other notifications on devices which support such rendering.
1021 */
1022 public String getGroup() {
1023 return mGroupKey;
1024 }
1025
1026 private String mSortKey;
1027
1028 /**
1029 * Get a sort key that orders this notification among other notifications from the
1030 * same package. This can be useful if an external sort was already applied and an app
1031 * would like to preserve this. Notifications will be sorted lexicographically using this
1032 * value, although providing different priorities in addition to providing sort key may
1033 * cause this value to be ignored.
1034 *
1035 * <p>This sort key can also be used to order members of a notification group. See
1036 * {@link Builder#setGroup}.
1037 *
1038 * @see String#compareTo(String)
1039 */
1040 public String getSortKey() {
1041 return mSortKey;
1042 }
1043
1044 /**
1045 * Additional semantic data to be carried around with this Notification.
1046 * <p>
1047 * The extras keys defined here are intended to capture the original inputs to {@link Builder}
1048 * APIs, and are intended to be used by
1049 * {@link android.service.notification.NotificationListenerService} implementations to extract
1050 * detailed information from notification objects.
1051 */
1052 public Bundle extras = new Bundle();
1053
1054 /**
1055 * All pending intents in the notification as the system needs to be able to access them but
1056 * touching the extras bundle in the system process is not safe because the bundle may contain
1057 * custom parcelable objects.
1058 *
1059 * @hide
1060 */
1061 @UnsupportedAppUsage
1062 public ArraySet<PendingIntent> allPendingIntents;
1063
1064 /**
1065 * Token identifying the notification that is applying doze/bgcheck allowlisting to the
1066 * pending intents inside of it, so only those will get the behavior.
1067 *
1068 * @hide
1069 */
1070 private IBinder mAllowlistToken;
1071
1072 /**
1073 * Must be set by a process to start associating tokens with Notification objects
1074 * coming in to it. This is set by NotificationManagerService.
1075 *
1076 * @hide
1077 */
1078 static public IBinder processAllowlistToken;
1079
1080 /**
1081 * {@link #extras} key: this is the title of the notification,
1082 * as supplied to {@link Builder#setContentTitle(CharSequence)}.
1083 */
1084 public static final String EXTRA_TITLE = "android.title";
1085
1086 /**
1087 * {@link #extras} key: this is the title of the notification when shown in expanded form,
1088 * e.g. as supplied to {@link BigTextStyle#setBigContentTitle(CharSequence)}.
1089 */
1090 public static final String EXTRA_TITLE_BIG = EXTRA_TITLE + ".big";
1091
1092 /**
1093 * {@link #extras} key: this is the main text payload, as supplied to
1094 * {@link Builder#setContentText(CharSequence)}.
1095 */
1096 public static final String EXTRA_TEXT = "android.text";
1097
1098 /**
1099 * {@link #extras} key: this is a third line of text, as supplied to
1100 * {@link Builder#setSubText(CharSequence)}.
1101 */
1102 public static final String EXTRA_SUB_TEXT = "android.subText";
1103
1104 /**
1105 * {@link #extras} key: this is the remote input history, as supplied to
1106 * {@link Builder#setRemoteInputHistory(CharSequence[])}.
1107 *
1108 * Apps can fill this through {@link Builder#setRemoteInputHistory(CharSequence[])}
1109 * with the most recent inputs that have been sent through a {@link RemoteInput} of this
1110 * Notification and are expected to clear it once the it is no longer relevant (e.g. for chat
1111 * notifications once the other party has responded).
1112 *
1113 * The extra with this key is of type CharSequence[] and contains the most recent entry at
1114 * the 0 index, the second most recent at the 1 index, etc.
1115 *
1116 * @see Builder#setRemoteInputHistory(CharSequence[])
1117 */
1118 public static final String EXTRA_REMOTE_INPUT_HISTORY = "android.remoteInputHistory";
1119
1120
1121 /**
1122 * {@link #extras} key: this is a remote input history which can include media messages
1123 * in addition to text, as supplied to
1124 * {@link Builder#setRemoteInputHistory(RemoteInputHistoryItem[])} or
1125 * {@link Builder#setRemoteInputHistory(CharSequence[])}.
1126 *
1127 * SystemUI can populate this through
1128 * {@link Builder#setRemoteInputHistory(RemoteInputHistoryItem[])} with the most recent inputs
1129 * that have been sent through a {@link RemoteInput} of this Notification. These items can
1130 * represent either media content (specified by a URI and a MIME type) or a text message
1131 * (described by a CharSequence).
1132 *
1133 * To maintain compatibility, this can also be set by apps with
1134 * {@link Builder#setRemoteInputHistory(CharSequence[])}, which will create a
1135 * {@link RemoteInputHistoryItem} for each of the provided text-only messages.
1136 *
1137 * The extra with this key is of type {@link RemoteInputHistoryItem[]} and contains the most
1138 * recent entry at the 0 index, the second most recent at the 1 index, etc.
1139 *
1140 * @see Builder#setRemoteInputHistory(RemoteInputHistoryItem[])
1141 * @hide
1142 */
1143 public static final String EXTRA_REMOTE_INPUT_HISTORY_ITEMS = "android.remoteInputHistoryItems";
1144
1145 /**
1146 * {@link #extras} key: boolean as supplied to
1147 * {@link Builder#setShowRemoteInputSpinner(boolean)}.
1148 *
1149 * If set to true, then the view displaying the remote input history from
1150 * {@link Builder#setRemoteInputHistory(CharSequence[])} will have a progress spinner.
1151 *
1152 * @see Builder#setShowRemoteInputSpinner(boolean)
1153 * @hide
1154 */
1155 public static final String EXTRA_SHOW_REMOTE_INPUT_SPINNER = "android.remoteInputSpinner";
1156
1157 /**
1158 * {@link #extras} key: boolean as supplied to
1159 * {@link Builder#setHideSmartReplies(boolean)}.
1160 *
1161 * If set to true, then any smart reply buttons will be hidden.
1162 *
1163 * @see Builder#setHideSmartReplies(boolean)
1164 * @hide
1165 */
1166 public static final String EXTRA_HIDE_SMART_REPLIES = "android.hideSmartReplies";
1167
1168 /**
1169 * {@link #extras} key: this is a small piece of additional text as supplied to
1170 * {@link Builder#setContentInfo(CharSequence)}.
1171 */
1172 public static final String EXTRA_INFO_TEXT = "android.infoText";
1173
1174 /**
1175 * {@link #extras} key: this is a line of summary information intended to be shown
1176 * alongside expanded notifications, as supplied to (e.g.)
1177 * {@link BigTextStyle#setSummaryText(CharSequence)}.
1178 */
1179 public static final String EXTRA_SUMMARY_TEXT = "android.summaryText";
1180
1181 /**
1182 * {@link #extras} key: this is the longer text shown in the big form of a
1183 * {@link BigTextStyle} notification, as supplied to
1184 * {@link BigTextStyle#bigText(CharSequence)}.
1185 */
1186 public static final String EXTRA_BIG_TEXT = "android.bigText";
1187
1188 /**
1189 * {@link #extras} key: this is the resource ID of the notification's main small icon, as
1190 * supplied to {@link Builder#setSmallIcon(int)}.
1191 *
1192 * @deprecated Use {@link #getSmallIcon()}, which supports a wider variety of icon sources.
1193 */
1194 @Deprecated
1195 public static final String EXTRA_SMALL_ICON = "android.icon";
1196
1197 /**
1198 * {@link #extras} key: this is a bitmap to be used instead of the small icon when showing the
1199 * notification payload, as
1200 * supplied to {@link Builder#setLargeIcon(android.graphics.Bitmap)}.
1201 *
1202 * @deprecated Use {@link #getLargeIcon()}, which supports a wider variety of icon sources.
1203 */
1204 @Deprecated
1205 public static final String EXTRA_LARGE_ICON = "android.largeIcon";
1206
1207 /**
1208 * {@link #extras} key: this is a bitmap to be used instead of the one from
1209 * {@link Builder#setLargeIcon(android.graphics.Bitmap)} when the notification is
1210 * shown in its expanded form, as supplied to
1211 * {@link BigPictureStyle#bigLargeIcon(android.graphics.Bitmap)}.
1212 */
1213 public static final String EXTRA_LARGE_ICON_BIG = EXTRA_LARGE_ICON + ".big";
1214
1215 /**
1216 * {@link #extras} key: this is the progress value supplied to
1217 * {@link Builder#setProgress(int, int, boolean)}.
1218 */
1219 public static final String EXTRA_PROGRESS = "android.progress";
1220
1221 /**
1222 * {@link #extras} key: this is the maximum value supplied to
1223 * {@link Builder#setProgress(int, int, boolean)}.
1224 */
1225 public static final String EXTRA_PROGRESS_MAX = "android.progressMax";
1226
1227 /**
1228 * {@link #extras} key: whether the progress bar is indeterminate, supplied to
1229 * {@link Builder#setProgress(int, int, boolean)}.
1230 */
1231 public static final String EXTRA_PROGRESS_INDETERMINATE = "android.progressIndeterminate";
1232
1233 /**
1234 * {@link #extras} key: whether {@link #when} should be shown as a count-up timer (specifically
1235 * a {@link android.widget.Chronometer}) instead of a timestamp, as supplied to
1236 * {@link Builder#setUsesChronometer(boolean)}.
1237 */
1238 public static final String EXTRA_SHOW_CHRONOMETER = "android.showChronometer";
1239
1240 /**
1241 * {@link #extras} key: whether the chronometer set on the notification should count down
1242 * instead of counting up. Is only relevant if key {@link #EXTRA_SHOW_CHRONOMETER} is present.
1243 * This extra is a boolean. The default is false.
1244 */
1245 public static final String EXTRA_CHRONOMETER_COUNT_DOWN = "android.chronometerCountDown";
1246
1247 /**
1248 * {@link #extras} key: whether {@link #when} should be shown,
1249 * as supplied to {@link Builder#setShowWhen(boolean)}.
1250 */
1251 public static final String EXTRA_SHOW_WHEN = "android.showWhen";
1252
1253 /**
1254 * {@link #extras} key: this is a bitmap to be shown in {@link BigPictureStyle} expanded
1255 * notifications, supplied to {@link BigPictureStyle#bigPicture(android.graphics.Bitmap)}.
1256 */
1257 public static final String EXTRA_PICTURE = "android.picture";
1258
1259 /**
1260 * {@link #extras} key: this is an {@link Icon} of an image to be
1261 * shown in {@link BigPictureStyle} expanded notifications, supplied to
1262 * {@link BigPictureStyle#bigPicture(Icon)}.
1263 */
1264 public static final String EXTRA_PICTURE_ICON = "android.pictureIcon";
1265
1266 /**
1267 * {@link #extras} key: this is a content description of the big picture supplied from
1268 * {@link BigPictureStyle#bigPicture(Bitmap)}, supplied to
1269 * {@link BigPictureStyle#setContentDescription(CharSequence)}.
1270 */
1271 public static final String EXTRA_PICTURE_CONTENT_DESCRIPTION =
1272 "android.pictureContentDescription";
1273
1274 /**
1275 * {@link #extras} key: this is a boolean to indicate that the
1276 * {@link BigPictureStyle#bigPicture(Bitmap) big picture} is to be shown in the collapsed state
1277 * of a {@link BigPictureStyle} notification. This will replace a
1278 * {@link Builder#setLargeIcon(Icon) large icon} in that state if one was provided.
1279 */
1280 public static final String EXTRA_SHOW_BIG_PICTURE_WHEN_COLLAPSED =
1281 "android.showBigPictureWhenCollapsed";
1282
1283 /**
1284 * {@link #extras} key: An array of CharSequences to show in {@link InboxStyle} expanded
1285 * notifications, each of which was supplied to {@link InboxStyle#addLine(CharSequence)}.
1286 */
1287 public static final String EXTRA_TEXT_LINES = "android.textLines";
1288
1289 /**
1290 * {@link #extras} key: A string representing the name of the specific
1291 * {@link android.app.Notification.Style} used to create this notification.
1292 */
1293 public static final String EXTRA_TEMPLATE = "android.template";
1294
1295 /**
1296 * {@link #extras} key: A String array containing the people that this notification relates to,
1297 * each of which was supplied to {@link Builder#addPerson(String)}.
1298 *
1299 * @deprecated the actual objects are now in {@link #EXTRA_PEOPLE_LIST}
1300 */
1301 public static final String EXTRA_PEOPLE = "android.people";
1302
1303 /**
1304 * {@link #extras} key: An arrayList of {@link Person} objects containing the people that
1305 * this notification relates to.
1306 */
1307 public static final String EXTRA_PEOPLE_LIST = "android.people.list";
1308
1309 /**
1310 * Allow certain system-generated notifications to appear before the device is provisioned.
1311 * Only available to notifications coming from the android package.
1312 * @hide
1313 */
1314 @SystemApi
1315 @RequiresPermission(android.Manifest.permission.NOTIFICATION_DURING_SETUP)
1316 public static final String EXTRA_ALLOW_DURING_SETUP = "android.allowDuringSetup";
1317
1318 /**
1319 * {@link #extras} key:
1320 * flat {@link String} representation of a {@link android.content.ContentUris content URI}
1321 * pointing to an image that can be displayed in the background when the notification is
1322 * selected. Used on television platforms. The URI must point to an image stream suitable for
1323 * passing into {@link android.graphics.BitmapFactory#decodeStream(java.io.InputStream)
1324 * BitmapFactory.decodeStream}; all other content types will be ignored.
1325 */
1326 public static final String EXTRA_BACKGROUND_IMAGE_URI = "android.backgroundImageUri";
1327
1328 /**
1329 * {@link #extras} key: A
1330 * {@link android.media.session.MediaSession.Token} associated with a
1331 * {@link android.app.Notification.MediaStyle} notification.
1332 */
1333 public static final String EXTRA_MEDIA_SESSION = "android.mediaSession";
1334
1335 /**
1336 * {@link #extras} key: A {@code CharSequence} name of a remote device used for a media session
1337 * associated with a {@link Notification.MediaStyle} notification. This will show in the media
1338 * controls output switcher instead of the local device name.
1339 * @hide
1340 */
1341 @TestApi
1342 public static final String EXTRA_MEDIA_REMOTE_DEVICE = "android.mediaRemoteDevice";
1343
1344 /**
1345 * {@link #extras} key: A {@code int} resource ID for an icon that should show in the output
1346 * switcher of the media controls for a {@link Notification.MediaStyle} notification.
1347 * @hide
1348 */
1349 @TestApi
1350 public static final String EXTRA_MEDIA_REMOTE_ICON = "android.mediaRemoteIcon";
1351
1352 /**
1353 * {@link #extras} key: A {@code PendingIntent} that will replace the default action for the
1354 * media controls output switcher chip, associated with a {@link Notification.MediaStyle}
1355 * notification. This should launch an activity.
1356 * @hide
1357 */
1358 @TestApi
1359 public static final String EXTRA_MEDIA_REMOTE_INTENT = "android.mediaRemoteIntent";
1360
1361 /**
1362 * {@link #extras} key: the indices of actions to be shown in the compact view,
1363 * as supplied to (e.g.) {@link MediaStyle#setShowActionsInCompactView(int...)}.
1364 */
1365 public static final String EXTRA_COMPACT_ACTIONS = "android.compactActions";
1366
1367 /**
1368 * {@link #extras} key: the username to be displayed for all messages sent by the user including
1369 * direct replies
1370 * {@link android.app.Notification.MessagingStyle} notification. This extra is a
1371 * {@link CharSequence}
1372 *
1373 * @deprecated use {@link #EXTRA_MESSAGING_PERSON}
1374 */
1375 public static final String EXTRA_SELF_DISPLAY_NAME = "android.selfDisplayName";
1376
1377 /**
1378 * {@link #extras} key: the person to be displayed for all messages sent by the user including
1379 * direct replies
1380 * {@link android.app.Notification.MessagingStyle} notification. This extra is a
1381 * {@link Person}
1382 */
1383 public static final String EXTRA_MESSAGING_PERSON = "android.messagingUser";
1384
1385 /**
1386 * {@link #extras} key: a {@link CharSequence} to be displayed as the title to a conversation
1387 * represented by a {@link android.app.Notification.MessagingStyle}
1388 */
1389 public static final String EXTRA_CONVERSATION_TITLE = "android.conversationTitle";
1390
1391 /** @hide */
1392 public static final String EXTRA_CONVERSATION_ICON = "android.conversationIcon";
1393
1394 /** @hide */
1395 public static final String EXTRA_CONVERSATION_UNREAD_MESSAGE_COUNT =
1396 "android.conversationUnreadMessageCount";
1397
1398 /**
1399 * {@link #extras} key: an array of {@link android.app.Notification.MessagingStyle.Message}
1400 * bundles provided by a
1401 * {@link android.app.Notification.MessagingStyle} notification. This extra is a parcelable
1402 * array of bundles.
1403 */
1404 public static final String EXTRA_MESSAGES = "android.messages";
1405
1406 /**
1407 * {@link #extras} key: an array of
1408 * {@link android.app.Notification.MessagingStyle#addHistoricMessage historic}
1409 * {@link android.app.Notification.MessagingStyle.Message} bundles provided by a
1410 * {@link android.app.Notification.MessagingStyle} notification. This extra is a parcelable
1411 * array of bundles.
1412 */
1413 public static final String EXTRA_HISTORIC_MESSAGES = "android.messages.historic";
1414
1415 /**
1416 * {@link #extras} key: whether the {@link android.app.Notification.MessagingStyle} notification
1417 * represents a group conversation.
1418 */
1419 public static final String EXTRA_IS_GROUP_CONVERSATION = "android.isGroupConversation";
1420
1421 /**
1422 * {@link #extras} key: the type of call represented by the
1423 * {@link android.app.Notification.CallStyle} notification. This extra is an int.
1424 * @hide
1425 */
1426 public static final String EXTRA_CALL_TYPE = "android.callType";
1427
1428 /**
1429 * {@link #extras} key: whether the {@link android.app.Notification.CallStyle} notification
1430 * is for a call that will activate video when answered. This extra is a boolean.
1431 */
1432 public static final String EXTRA_CALL_IS_VIDEO = "android.callIsVideo";
1433
1434 /**
1435 * {@link #extras} key: the person to be displayed as calling for the
1436 * {@link android.app.Notification.CallStyle} notification. This extra is a {@link Person}.
1437 */
1438 public static final String EXTRA_CALL_PERSON = "android.callPerson";
1439
1440 /**
1441 * {@link #extras} key: the icon to be displayed as a verification status of the caller on a
1442 * {@link android.app.Notification.CallStyle} notification. This extra is an {@link Icon}.
1443 */
1444 public static final String EXTRA_VERIFICATION_ICON = "android.verificationIcon";
1445
1446 /**
1447 * {@link #extras} key: the text to be displayed as a verification status of the caller on a
1448 * {@link android.app.Notification.CallStyle} notification. This extra is a
1449 * {@link CharSequence}.
1450 */
1451 public static final String EXTRA_VERIFICATION_TEXT = "android.verificationText";
1452
1453 /**
1454 * {@link #extras} key: the intent to be sent when the users answers a
1455 * {@link android.app.Notification.CallStyle} notification. This extra is a
1456 * {@link PendingIntent}.
1457 */
1458 public static final String EXTRA_ANSWER_INTENT = "android.answerIntent";
1459
1460 /**
1461 * {@link #extras} key: the intent to be sent when the users declines a
1462 * {@link android.app.Notification.CallStyle} notification. This extra is a
1463 * {@link PendingIntent}.
1464 */
1465 public static final String EXTRA_DECLINE_INTENT = "android.declineIntent";
1466
1467 /**
1468 * {@link #extras} key: the intent to be sent when the users hangs up a
1469 * {@link android.app.Notification.CallStyle} notification. This extra is a
1470 * {@link PendingIntent}.
1471 */
1472 public static final String EXTRA_HANG_UP_INTENT = "android.hangUpIntent";
1473
1474 /**
1475 * {@link #extras} key: the color used as a hint for the Answer action button of a
1476 * {@link android.app.Notification.CallStyle} notification. This extra is a {@link ColorInt}.
1477 */
1478 public static final String EXTRA_ANSWER_COLOR = "android.answerColor";
1479
1480 /**
1481 * {@link #extras} key: the color used as a hint for the Decline or Hang Up action button of a
1482 * {@link android.app.Notification.CallStyle} notification. This extra is a {@link ColorInt}.
1483 */
1484 public static final String EXTRA_DECLINE_COLOR = "android.declineColor";
1485
1486 /**
1487 * {@link #extras} key: whether the notification should be colorized as
1488 * supplied to {@link Builder#setColorized(boolean)}.
1489 */
1490 public static final String EXTRA_COLORIZED = "android.colorized";
1491
1492 /**
1493 * @hide
1494 */
1495 public static final String EXTRA_BUILDER_APPLICATION_INFO = "android.appInfo";
1496
1497 /**
1498 * @hide
1499 */
1500 public static final String EXTRA_CONTAINS_CUSTOM_VIEW = "android.contains.customView";
1501
1502 /**
1503 * @hide
1504 */
1505 public static final String EXTRA_REDUCED_IMAGES = "android.reduced.images";
1506
1507 /**
1508 * {@link #extras} key: the audio contents of this notification.
1509 *
1510 * This is for use when rendering the notification on an audio-focused interface;
1511 * the audio contents are a complete sound sample that contains the contents/body of the
1512 * notification. This may be used in substitute of a Text-to-Speech reading of the
1513 * notification. For example if the notification represents a voice message this should point
1514 * to the audio of that message.
1515 *
1516 * The data stored under this key should be a String representation of a Uri that contains the
1517 * audio contents in one of the following formats: WAV, PCM 16-bit, AMR-WB.
1518 *
1519 * This extra is unnecessary if you are using {@code MessagingStyle} since each {@code Message}
1520 * has a field for holding data URI. That field can be used for audio.
1521 * See {@code Message#setData}.
1522 *
1523 * Example usage:
1524 * <pre>
1525 * {@code
1526 * Notification.Builder myBuilder = (build your Notification as normal);
1527 * myBuilder.getExtras().putString(EXTRA_AUDIO_CONTENTS_URI, myAudioUri.toString());
1528 * }
1529 * </pre>
1530 */
1531 public static final String EXTRA_AUDIO_CONTENTS_URI = "android.audioContents";
1532
1533 /** @hide */
1534 @SystemApi
1535 @RequiresPermission(android.Manifest.permission.SUBSTITUTE_NOTIFICATION_APP_NAME)
1536 public static final String EXTRA_SUBSTITUTE_APP_NAME = "android.substName";
1537
1538 /**
1539 * This is set on the notifications shown by system_server about apps running foreground
1540 * services. It indicates that the notification should be shown
1541 * only if any of the given apps do not already have a properly tagged
1542 * {@link #FLAG_FOREGROUND_SERVICE} notification currently visible to the user.
1543 * This is a string array of all package names of the apps.
1544 * @hide
1545 */
1546 public static final String EXTRA_FOREGROUND_APPS = "android.foregroundApps";
1547
1548 @UnsupportedAppUsage
1549 private Icon mSmallIcon;
1550 @UnsupportedAppUsage
1551 private Icon mLargeIcon;
1552
1553 @UnsupportedAppUsage
1554 private String mChannelId;
1555 private long mTimeout;
1556
1557 private String mShortcutId;
1558 private LocusId mLocusId;
1559 private CharSequence mSettingsText;
1560
1561 private BubbleMetadata mBubbleMetadata;
1562
1563 /** @hide */
1564 @IntDef(prefix = { "GROUP_ALERT_" }, value = {
1565 GROUP_ALERT_ALL, GROUP_ALERT_CHILDREN, GROUP_ALERT_SUMMARY
1566 })
1567 @Retention(RetentionPolicy.SOURCE)
1568 public @interface GroupAlertBehavior {}
1569
1570 /**
1571 * Constant for {@link Builder#setGroupAlertBehavior(int)}, meaning that all notifications in a
1572 * group with sound or vibration ought to make sound or vibrate (respectively), so this
1573 * notification will not be muted when it is in a group.
1574 */
1575 public static final int GROUP_ALERT_ALL = 0;
1576
1577 /**
1578 * Constant for {@link Builder#setGroupAlertBehavior(int)}, meaning that all children
1579 * notification in a group should be silenced (no sound or vibration) even if they are posted
1580 * to a {@link NotificationChannel} that has sound and/or vibration. Use this constant to
1581 * mute this notification if this notification is a group child. This must be applied to all
1582 * children notifications you want to mute.
1583 *
1584 * <p> For example, you might want to use this constant if you post a number of children
1585 * notifications at once (say, after a periodic sync), and only need to notify the user
1586 * audibly once.
1587 */
1588 public static final int GROUP_ALERT_SUMMARY = 1;
1589
1590 /**
1591 * Constant for {@link Builder#setGroupAlertBehavior(int)}, meaning that the summary
1592 * notification in a group should be silenced (no sound or vibration) even if they are
1593 * posted to a {@link NotificationChannel} that has sound and/or vibration. Use this constant
1594 * to mute this notification if this notification is a group summary.
1595 *
1596 * <p>For example, you might want to use this constant if only the children notifications
1597 * in your group have content and the summary is only used to visually group notifications
1598 * rather than to alert the user that new information is available.
1599 */
1600 public static final int GROUP_ALERT_CHILDREN = 2;
1601
1602 private int mGroupAlertBehavior = GROUP_ALERT_ALL;
1603
1604 /**
1605 * If this notification is being shown as a badge, always show as a number.
1606 */
1607 public static final int BADGE_ICON_NONE = 0;
1608
1609 /**
1610 * If this notification is being shown as a badge, use the {@link #getSmallIcon()} to
1611 * represent this notification.
1612 */
1613 public static final int BADGE_ICON_SMALL = 1;
1614
1615 /**
1616 * If this notification is being shown as a badge, use the {@link #getLargeIcon()} to
1617 * represent this notification.
1618 */
1619 public static final int BADGE_ICON_LARGE = 2;
1620 private int mBadgeIcon = BADGE_ICON_NONE;
1621
1622 /**
1623 * Determines whether the platform can generate contextual actions for a notification.
1624 */
1625 private boolean mAllowSystemGeneratedContextualActions = true;
1626
1627 /**
1628 * Structure to encapsulate a named action that can be shown as part of this notification.
1629 * It must include an icon, a label, and a {@link PendingIntent} to be fired when the action is
1630 * selected by the user.
1631 * <p>
1632 * Apps should use {@link Notification.Builder#addAction(int, CharSequence, PendingIntent)}
1633 * or {@link Notification.Builder#addAction(Notification.Action)}
1634 * to attach actions.
1635 * <p>
1636 * As of Android {@link android.os.Build.VERSION_CODES#S}, apps targeting API level {@link
1637 * android.os.Build.VERSION_CODES#S} or higher won't be able to start activities while
1638 * processing broadcast receivers or services in response to notification action clicks. To
1639 * launch an activity in those cases, provide a {@link PendingIntent} for the activity itself.
1640 */
1641 public static class Action implements Parcelable {
1642 /**
1643 * {@link #extras} key: Keys to a {@link Parcelable} {@link ArrayList} of
1644 * {@link RemoteInput}s.
1645 *
1646 * This is intended for {@link RemoteInput}s that only accept data, meaning
1647 * {@link RemoteInput#getAllowFreeFormInput} is false, {@link RemoteInput#getChoices}
1648 * is null or empty, and {@link RemoteInput#getAllowedDataTypes} is non-null and not
1649 * empty. These {@link RemoteInput}s will be ignored by devices that do not
1650 * support non-text-based {@link RemoteInput}s. See {@link Builder#build}.
1651 *
1652 * You can test if a RemoteInput matches these constraints using
1653 * {@link RemoteInput#isDataOnly}.
1654 */
1655 private static final String EXTRA_DATA_ONLY_INPUTS = "android.extra.DATA_ONLY_INPUTS";
1656
1657 /**
1658 * {@link }: No semantic action defined.
1659 */
1660 public static final int SEMANTIC_ACTION_NONE = 0;
1661
1662 /**
1663 * {@code SemanticAction}: Reply to a conversation, chat, group, or wherever replies
1664 * may be appropriate.
1665 */
1666 public static final int SEMANTIC_ACTION_REPLY = 1;
1667
1668 /**
1669 * {@code SemanticAction}: Mark content as read.
1670 */
1671 public static final int SEMANTIC_ACTION_MARK_AS_READ = 2;
1672
1673 /**
1674 * {@code SemanticAction}: Mark content as unread.
1675 */
1676 public static final int SEMANTIC_ACTION_MARK_AS_UNREAD = 3;
1677
1678 /**
1679 * {@code SemanticAction}: Delete the content associated with the notification. This
1680 * could mean deleting an email, message, etc.
1681 */
1682 public static final int SEMANTIC_ACTION_DELETE = 4;
1683
1684 /**
1685 * {@code SemanticAction}: Archive the content associated with the notification. This
1686 * could mean archiving an email, message, etc.
1687 */
1688 public static final int SEMANTIC_ACTION_ARCHIVE = 5;
1689
1690 /**
1691 * {@code SemanticAction}: Mute the content associated with the notification. This could
1692 * mean silencing a conversation or currently playing media.
1693 */
1694 public static final int SEMANTIC_ACTION_MUTE = 6;
1695
1696 /**
1697 * {@code SemanticAction}: Unmute the content associated with the notification. This could
1698 * mean un-silencing a conversation or currently playing media.
1699 */
1700 public static final int SEMANTIC_ACTION_UNMUTE = 7;
1701
1702 /**
1703 * {@code SemanticAction}: Mark content with a thumbs up.
1704 */
1705 public static final int SEMANTIC_ACTION_THUMBS_UP = 8;
1706
1707 /**
1708 * {@code SemanticAction}: Mark content with a thumbs down.
1709 */
1710 public static final int SEMANTIC_ACTION_THUMBS_DOWN = 9;
1711
1712 /**
1713 * {@code SemanticAction}: Call a contact, group, etc.
1714 */
1715 public static final int SEMANTIC_ACTION_CALL = 10;
1716
1717 /**
1718 * {@code SemanticAction}: Mark the conversation associated with the notification as a
1719 * priority. Note that this is only for use by the notification assistant services. The
1720 * type will be ignored for actions an app adds to its own notifications.
1721 * @hide
1722 */
1723 @SystemApi
1724 public static final int SEMANTIC_ACTION_MARK_CONVERSATION_AS_PRIORITY = 11;
1725
1726 /**
1727 * {@code SemanticAction}: Mark content as a potential phishing attempt.
1728 * Note that this is only for use by the notification assistant services. The type will
1729 * be ignored for actions an app adds to its own notifications.
1730 * @hide
1731 */
1732 @SystemApi
1733 public static final int SEMANTIC_ACTION_CONVERSATION_IS_PHISHING = 12;
1734
1735 private final Bundle mExtras;
1736 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
1737 private Icon mIcon;
1738 private final RemoteInput[] mRemoteInputs;
1739 private boolean mAllowGeneratedReplies = true;
1740 private final @SemanticAction int mSemanticAction;
1741 private final boolean mIsContextual;
1742 private boolean mAuthenticationRequired;
1743
1744 /**
1745 * Small icon representing the action.
1746 *
1747 * @deprecated Use {@link Action#getIcon()} instead.
1748 */
1749 @Deprecated
1750 public int icon;
1751
1752 /**
1753 * Title of the action.
1754 */
1755 public CharSequence title;
1756
1757 /**
1758 * Intent to send when the user invokes this action. May be null, in which case the action
1759 * may be rendered in a disabled presentation by the system UI.
1760 */
1761 public PendingIntent actionIntent;
1762
1763 private Action(Parcel in) {
1764 if (in.readInt() != 0) {
1765 mIcon = Icon.CREATOR.createFromParcel(in);
1766 if (mIcon.getType() == Icon.TYPE_RESOURCE) {
1767 icon = mIcon.getResId();
1768 }
1769 }
1770 title = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
1771 if (in.readInt() == 1) {
1772 actionIntent = PendingIntent.CREATOR.createFromParcel(in);
1773 }
1774 mExtras = Bundle.setDefusable(in.readBundle(), true);
1775 mRemoteInputs = in.createTypedArray(RemoteInput.CREATOR);
1776 mAllowGeneratedReplies = in.readInt() == 1;
1777 mSemanticAction = in.readInt();
1778 mIsContextual = in.readInt() == 1;
1779 mAuthenticationRequired = in.readInt() == 1;
1780 }
1781
1782 /**
1783 * @deprecated Use {@link android.app.Notification.Action.Builder}.
1784 */
1785 @Deprecated
1786 public Action(int icon, CharSequence title, @Nullable PendingIntent intent) {
1787 this(Icon.createWithResource("", icon), title, intent, new Bundle(), null, true,
1788 SEMANTIC_ACTION_NONE, false /* isContextual */, false /* requireAuth */);
1789 }
1790
1791 /** Keep in sync with {@link Notification.Action.Builder#Builder(Action)}! */
1792 private Action(Icon icon, CharSequence title, PendingIntent intent, Bundle extras,
1793 RemoteInput[] remoteInputs, boolean allowGeneratedReplies,
1794 @SemanticAction int semanticAction, boolean isContextual,
1795 boolean requireAuth) {
1796 this.mIcon = icon;
1797 if (icon != null && icon.getType() == Icon.TYPE_RESOURCE) {
1798 this.icon = icon.getResId();
1799 }
1800 this.title = title;
1801 this.actionIntent = intent;
1802 this.mExtras = extras != null ? extras : new Bundle();
1803 this.mRemoteInputs = remoteInputs;
1804 this.mAllowGeneratedReplies = allowGeneratedReplies;
1805 this.mSemanticAction = semanticAction;
1806 this.mIsContextual = isContextual;
1807 this.mAuthenticationRequired = requireAuth;
1808 }
1809
1810 /**
1811 * Return an icon representing the action.
1812 */
1813 public Icon getIcon() {
1814 if (mIcon == null && icon != 0) {
1815 // you snuck an icon in here without using the builder; let's try to keep it
1816 mIcon = Icon.createWithResource("", icon);
1817 }
1818 return mIcon;
1819 }
1820
1821 /**
1822 * Get additional metadata carried around with this Action.
1823 */
1824 public Bundle getExtras() {
1825 return mExtras;
1826 }
1827
1828 /**
1829 * Return whether the platform should automatically generate possible replies for this
1830 * {@link Action}
1831 */
1832 public boolean getAllowGeneratedReplies() {
1833 return mAllowGeneratedReplies;
1834 }
1835
1836 /**
1837 * Get the list of inputs to be collected from the user when this action is sent.
1838 * May return null if no remote inputs were added. Only returns inputs which accept
1839 * a text input. For inputs which only accept data use {@link #getDataOnlyRemoteInputs}.
1840 */
1841 public RemoteInput[] getRemoteInputs() {
1842 return mRemoteInputs;
1843 }
1844
1845 /**
1846 * Returns the {@code SemanticAction} associated with this {@link Action}. A
1847 * {@code SemanticAction} denotes what an {@link Action}'s {@link PendingIntent} will do
1848 * (eg. reply, mark as read, delete, etc).
1849 */
1850 public @SemanticAction int getSemanticAction() {
1851 return mSemanticAction;
1852 }
1853
1854 /**
1855 * Returns whether this is a contextual Action, i.e. whether the action is dependent on the
1856 * notification message body. An example of a contextual action could be an action opening a
1857 * map application with an address shown in the notification.
1858 */
1859 public boolean isContextual() {
1860 return mIsContextual;
1861 }
1862
1863 /**
1864 * Get the list of inputs to be collected from the user that ONLY accept data when this
1865 * action is sent. These remote inputs are guaranteed to return true on a call to
1866 * {@link RemoteInput#isDataOnly}.
1867 *
1868 * Returns null if there are no data-only remote inputs.
1869 *
1870 * This method exists so that legacy RemoteInput collectors that pre-date the addition
1871 * of non-textual RemoteInputs do not access these remote inputs.
1872 */
1873 public RemoteInput[] getDataOnlyRemoteInputs() {
1874 return getParcelableArrayFromBundle(mExtras, EXTRA_DATA_ONLY_INPUTS, RemoteInput.class);
1875 }
1876
1877 /**
1878 * Returns whether the OS should only send this action's {@link PendingIntent} on an
1879 * unlocked device.
1880 *
1881 * If the device is locked when the action is invoked, the OS should show the keyguard and
1882 * require successful authentication before invoking the intent.
1883 */
1884 public boolean isAuthenticationRequired() {
1885 return mAuthenticationRequired;
1886 }
1887
1888 /**
1889 * Builder class for {@link Action} objects.
1890 */
1891 public static final class Builder {
1892 @Nullable private final Icon mIcon;
1893 @Nullable private final CharSequence mTitle;
1894 @Nullable private final PendingIntent mIntent;
1895 private boolean mAllowGeneratedReplies = true;
1896 @NonNull private final Bundle mExtras;
1897 @Nullable private ArrayList<RemoteInput> mRemoteInputs;
1898 private @SemanticAction int mSemanticAction;
1899 private boolean mIsContextual;
1900 private boolean mAuthenticationRequired;
1901
1902 /**
1903 * Construct a new builder for {@link Action} object.
1904 * <p>As of Android {@link android.os.Build.VERSION_CODES#N},
1905 * action button icons will not be displayed on action buttons, but are still required
1906 * and are available to
1907 * {@link android.service.notification.NotificationListenerService notification listeners},
1908 * which may display them in other contexts, for example on a wearable device.
1909 * @param icon icon to show for this action
1910 * @param title the title of the action
1911 * @param intent the {@link PendingIntent} to fire when users trigger this action. May
1912 * be null, in which case the action may be rendered in a disabled presentation by the
1913 * system UI.
1914 */
1915 @Deprecated
1916 public Builder(int icon, CharSequence title, @Nullable PendingIntent intent) {
1917 this(Icon.createWithResource("", icon), title, intent);
1918 }
1919
1920 /**
1921 * Construct a new builder for {@link Action} object.
1922 *
1923 * <p>As of Android {@link android.os.Build.VERSION_CODES#S}, apps targeting API level
1924 * {@link android.os.Build.VERSION_CODES#S} or higher won't be able to start activities
1925 * while processing broadcast receivers or services in response to notification action
1926 * clicks. To launch an activity in those cases, provide a {@link PendingIntent} for the
1927 * activity itself.
1928 *
1929 * <p>How an Action is displayed, including whether the {@code icon}, {@code text}, or
1930 * both are displayed or required, depends on where and how the action is used, and the
1931 * {@link Style} applied to the Notification.
1932 *
1933 * <p>As of Android {@link android.os.Build.VERSION_CODES#N}, action button icons
1934 * will not be displayed on action buttons, but are still required and are available
1935 * to {@link android.service.notification.NotificationListenerService notification
1936 * listeners}, which may display them in other contexts, for example on a wearable
1937 * device.
1938 *
1939 * <p>When the {@code title} is a {@link android.text.Spanned}, any colors set by a
1940 * {@link ForegroundColorSpan} or {@link TextAppearanceSpan} may be removed or displayed
1941 * with an altered in luminance to ensure proper contrast within the Notification.
1942 *
1943 * @param icon icon to show for this action
1944 * @param title the title of the action
1945 * @param intent the {@link PendingIntent} to fire when users trigger this action. May
1946 * be null, in which case the action may be rendered in a disabled presentation by the
1947 * system UI.
1948 */
1949 public Builder(Icon icon, CharSequence title, @Nullable PendingIntent intent) {
1950 this(icon, title, intent, new Bundle(), null, true, SEMANTIC_ACTION_NONE, false);
1951 }
1952
1953 /**
1954 * Construct a new builder for {@link Action} object using the fields from an
1955 * {@link Action}.
1956 * @param action the action to read fields from.
1957 */
1958 public Builder(Action action) {
1959 this(action.getIcon(), action.title, action.actionIntent,
1960 new Bundle(action.mExtras), action.getRemoteInputs(),
1961 action.getAllowGeneratedReplies(), action.getSemanticAction(),
1962 action.isAuthenticationRequired());
1963 }
1964
1965 private Builder(@Nullable Icon icon, @Nullable CharSequence title,
1966 @Nullable PendingIntent intent, @NonNull Bundle extras,
1967 @Nullable RemoteInput[] remoteInputs, boolean allowGeneratedReplies,
1968 @SemanticAction int semanticAction, boolean authRequired) {
1969 mIcon = icon;
1970 mTitle = title;
1971 mIntent = intent;
1972 mExtras = extras;
1973 if (remoteInputs != null) {
1974 mRemoteInputs = new ArrayList<>(remoteInputs.length);
1975 Collections.addAll(mRemoteInputs, remoteInputs);
1976 }
1977 mAllowGeneratedReplies = allowGeneratedReplies;
1978 mSemanticAction = semanticAction;
1979 mAuthenticationRequired = authRequired;
1980 }
1981
1982 /**
1983 * Merge additional metadata into this builder.
1984 *
1985 * <p>Values within the Bundle will replace existing extras values in this Builder.
1986 *
1987 * @see Notification.Action#extras
1988 */
1989 @NonNull
1990 public Builder addExtras(Bundle extras) {
1991 if (extras != null) {
1992 mExtras.putAll(extras);
1993 }
1994 return this;
1995 }
1996
1997 /**
1998 * Get the metadata Bundle used by this Builder.
1999 *
2000 * <p>The returned Bundle is shared with this Builder.
2001 */
2002 @NonNull
2003 public Bundle getExtras() {
2004 return mExtras;
2005 }
2006
2007 /**
2008 * Add an input to be collected from the user when this action is sent.
2009 * Response values can be retrieved from the fired intent by using the
2010 * {@link RemoteInput#getResultsFromIntent} function.
2011 * @param remoteInput a {@link RemoteInput} to add to the action
2012 * @return this object for method chaining
2013 */
2014 @NonNull
2015 public Builder addRemoteInput(RemoteInput remoteInput) {
2016 if (mRemoteInputs == null) {
2017 mRemoteInputs = new ArrayList<RemoteInput>();
2018 }
2019 mRemoteInputs.add(remoteInput);
2020 return this;
2021 }
2022
2023 /**
2024 * Set whether the platform should automatically generate possible replies to add to
2025 * {@link RemoteInput#getChoices()}. If the {@link Action} doesn't have a
2026 * {@link RemoteInput}, this has no effect.
2027 * @param allowGeneratedReplies {@code true} to allow generated replies, {@code false}
2028 * otherwise
2029 * @return this object for method chaining
2030 * The default value is {@code true}
2031 */
2032 @NonNull
2033 public Builder setAllowGeneratedReplies(boolean allowGeneratedReplies) {
2034 mAllowGeneratedReplies = allowGeneratedReplies;
2035 return this;
2036 }
2037
2038 /**
2039 * Sets the {@code SemanticAction} for this {@link Action}. A
2040 * {@code SemanticAction} denotes what an {@link Action}'s
2041 * {@link PendingIntent} will do (eg. reply, mark as read, delete, etc).
2042 * @param semanticAction a SemanticAction defined within {@link Action} with
2043 * {@code SEMANTIC_ACTION_} prefixes
2044 * @return this object for method chaining
2045 */
2046 @NonNull
2047 public Builder setSemanticAction(@SemanticAction int semanticAction) {
2048 mSemanticAction = semanticAction;
2049 return this;
2050 }
2051
2052 /**
2053 * Sets whether this {@link Action} is a contextual action, i.e. whether the action is
2054 * dependent on the notification message body. An example of a contextual action could
2055 * be an action opening a map application with an address shown in the notification.
2056 */
2057 @NonNull
2058 public Builder setContextual(boolean isContextual) {
2059 mIsContextual = isContextual;
2060 return this;
2061 }
2062
2063 /**
2064 * Apply an extender to this action builder. Extenders may be used to add
2065 * metadata or change options on this builder.
2066 */
2067 @NonNull
2068 public Builder extend(Extender extender) {
2069 extender.extend(this);
2070 return this;
2071 }
2072
2073 /**
2074 * Sets whether the OS should only send this action's {@link PendingIntent} on an
2075 * unlocked device.
2076 *
2077 * If this is true and the device is locked when the action is invoked, the OS will
2078 * show the keyguard and require successful authentication before invoking the intent.
2079 * If this is false and the device is locked, the OS will decide whether authentication
2080 * should be required.
2081 */
2082 @NonNull
2083 public Builder setAuthenticationRequired(boolean authenticationRequired) {
2084 mAuthenticationRequired = authenticationRequired;
2085 return this;
2086 }
2087
2088 /**
2089 * Throws an NPE if we are building a contextual action missing one of the fields
2090 * necessary to display the action.
2091 */
2092 private void checkContextualActionNullFields() {
2093 if (!mIsContextual) return;
2094
2095 if (mIcon == null) {
2096 throw new NullPointerException("Contextual Actions must contain a valid icon");
2097 }
2098
2099 if (mIntent == null) {
2100 throw new NullPointerException(
2101 "Contextual Actions must contain a valid PendingIntent");
2102 }
2103 }
2104
2105 /**
2106 * Combine all of the options that have been set and return a new {@link Action}
2107 * object.
2108 * @return the built action
2109 */
2110 @NonNull
2111 public Action build() {
2112 checkContextualActionNullFields();
2113
2114 ArrayList<RemoteInput> dataOnlyInputs = new ArrayList<>();
2115 RemoteInput[] previousDataInputs = getParcelableArrayFromBundle(
2116 mExtras, EXTRA_DATA_ONLY_INPUTS, RemoteInput.class);
2117 if (previousDataInputs != null) {
2118 for (RemoteInput input : previousDataInputs) {
2119 dataOnlyInputs.add(input);
2120 }
2121 }
2122 List<RemoteInput> textInputs = new ArrayList<>();
2123 if (mRemoteInputs != null) {
2124 for (RemoteInput input : mRemoteInputs) {
2125 if (input.isDataOnly()) {
2126 dataOnlyInputs.add(input);
2127 } else {
2128 textInputs.add(input);
2129 }
2130 }
2131 }
2132 if (!dataOnlyInputs.isEmpty()) {
2133 RemoteInput[] dataInputsArr =
2134 dataOnlyInputs.toArray(new RemoteInput[dataOnlyInputs.size()]);
2135 mExtras.putParcelableArray(EXTRA_DATA_ONLY_INPUTS, dataInputsArr);
2136 }
2137 RemoteInput[] textInputsArr = textInputs.isEmpty()
2138 ? null : textInputs.toArray(new RemoteInput[textInputs.size()]);
2139 return new Action(mIcon, mTitle, mIntent, mExtras, textInputsArr,
2140 mAllowGeneratedReplies, mSemanticAction, mIsContextual,
2141 mAuthenticationRequired);
2142 }
2143 }
2144
2145 @Override
2146 public Action clone() {
2147 return new Action(
2148 getIcon(),
2149 title,
2150 actionIntent, // safe to alias
2151 mExtras == null ? new Bundle() : new Bundle(mExtras),
2152 getRemoteInputs(),
2153 getAllowGeneratedReplies(),
2154 getSemanticAction(),
2155 isContextual(),
2156 isAuthenticationRequired());
2157 }
2158
2159 @Override
2160 public int describeContents() {
2161 return 0;
2162 }
2163
2164 @Override
2165 public void writeToParcel(Parcel out, int flags) {
2166 final Icon ic = getIcon();
2167 if (ic != null) {
2168 out.writeInt(1);
2169 ic.writeToParcel(out, 0);
2170 } else {
2171 out.writeInt(0);
2172 }
2173 TextUtils.writeToParcel(title, out, flags);
2174 if (actionIntent != null) {
2175 out.writeInt(1);
2176 actionIntent.writeToParcel(out, flags);
2177 } else {
2178 out.writeInt(0);
2179 }
2180 out.writeBundle(mExtras);
2181 out.writeTypedArray(mRemoteInputs, flags);
2182 out.writeInt(mAllowGeneratedReplies ? 1 : 0);
2183 out.writeInt(mSemanticAction);
2184 out.writeInt(mIsContextual ? 1 : 0);
2185 out.writeInt(mAuthenticationRequired ? 1 : 0);
2186 }
2187
2188 public static final @android.annotation.NonNull Parcelable.Creator<Action> CREATOR =
2189 new Parcelable.Creator<Action>() {
2190 public Action createFromParcel(Parcel in) {
2191 return new Action(in);
2192 }
2193 public Action[] newArray(int size) {
2194 return new Action[size];
2195 }
2196 };
2197
2198 /**
2199 * Extender interface for use with {@link Builder#extend}. Extenders may be used to add
2200 * metadata or change options on an action builder.
2201 */
2202 public interface Extender {
2203 /**
2204 * Apply this extender to a notification action builder.
2205 * @param builder the builder to be modified.
2206 * @return the build object for chaining.
2207 */
2208 public Builder extend(Builder builder);
2209 }
2210
2211 /**
2212 * Wearable extender for notification actions. To add extensions to an action,
2213 * create a new {@link android.app.Notification.Action.WearableExtender} object using
2214 * the {@code WearableExtender()} constructor and apply it to a
2215 * {@link android.app.Notification.Action.Builder} using
2216 * {@link android.app.Notification.Action.Builder#extend}.
2217 *
2218 * <pre class="prettyprint">
2219 * Notification.Action action = new Notification.Action.Builder(
2220 * R.drawable.archive_all, "Archive all", actionIntent)
2221 * .extend(new Notification.Action.WearableExtender()
2222 * .setAvailableOffline(false))
2223 * .build();</pre>
2224 */
2225 public static final class WearableExtender implements Extender {
2226 /** Notification action extra which contains wearable extensions */
2227 private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS";
2228
2229 // Keys within EXTRA_WEARABLE_EXTENSIONS for wearable options.
2230 private static final String KEY_FLAGS = "flags";
2231 private static final String KEY_IN_PROGRESS_LABEL = "inProgressLabel";
2232 private static final String KEY_CONFIRM_LABEL = "confirmLabel";
2233 private static final String KEY_CANCEL_LABEL = "cancelLabel";
2234
2235 // Flags bitwise-ored to mFlags
2236 private static final int FLAG_AVAILABLE_OFFLINE = 0x1;
2237 private static final int FLAG_HINT_LAUNCHES_ACTIVITY = 1 << 1;
2238 private static final int FLAG_HINT_DISPLAY_INLINE = 1 << 2;
2239
2240 // Default value for flags integer
2241 private static final int DEFAULT_FLAGS = FLAG_AVAILABLE_OFFLINE;
2242
2243 private int mFlags = DEFAULT_FLAGS;
2244
2245 private CharSequence mInProgressLabel;
2246 private CharSequence mConfirmLabel;
2247 private CharSequence mCancelLabel;
2248
2249 /**
2250 * Create a {@link android.app.Notification.Action.WearableExtender} with default
2251 * options.
2252 */
2253 public WearableExtender() {
2254 }
2255
2256 /**
2257 * Create a {@link android.app.Notification.Action.WearableExtender} by reading
2258 * wearable options present in an existing notification action.
2259 * @param action the notification action to inspect.
2260 */
2261 public WearableExtender(Action action) {
2262 Bundle wearableBundle = action.getExtras().getBundle(EXTRA_WEARABLE_EXTENSIONS);
2263 if (wearableBundle != null) {
2264 mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS);
2265 mInProgressLabel = wearableBundle.getCharSequence(KEY_IN_PROGRESS_LABEL);
2266 mConfirmLabel = wearableBundle.getCharSequence(KEY_CONFIRM_LABEL);
2267 mCancelLabel = wearableBundle.getCharSequence(KEY_CANCEL_LABEL);
2268 }
2269 }
2270
2271 /**
2272 * Apply wearable extensions to a notification action that is being built. This is
2273 * typically called by the {@link android.app.Notification.Action.Builder#extend}
2274 * method of {@link android.app.Notification.Action.Builder}.
2275 */
2276 @Override
2277 public Action.Builder extend(Action.Builder builder) {
2278 Bundle wearableBundle = new Bundle();
2279
2280 if (mFlags != DEFAULT_FLAGS) {
2281 wearableBundle.putInt(KEY_FLAGS, mFlags);
2282 }
2283 if (mInProgressLabel != null) {
2284 wearableBundle.putCharSequence(KEY_IN_PROGRESS_LABEL, mInProgressLabel);
2285 }
2286 if (mConfirmLabel != null) {
2287 wearableBundle.putCharSequence(KEY_CONFIRM_LABEL, mConfirmLabel);
2288 }
2289 if (mCancelLabel != null) {
2290 wearableBundle.putCharSequence(KEY_CANCEL_LABEL, mCancelLabel);
2291 }
2292
2293 builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle);
2294 return builder;
2295 }
2296
2297 @Override
2298 public WearableExtender clone() {
2299 WearableExtender that = new WearableExtender();
2300 that.mFlags = this.mFlags;
2301 that.mInProgressLabel = this.mInProgressLabel;
2302 that.mConfirmLabel = this.mConfirmLabel;
2303 that.mCancelLabel = this.mCancelLabel;
2304 return that;
2305 }
2306
2307 /**
2308 * Set whether this action is available when the wearable device is not connected to
2309 * a companion device. The user can still trigger this action when the wearable device is
2310 * offline, but a visual hint will indicate that the action may not be available.
2311 * Defaults to true.
2312 */
2313 public WearableExtender setAvailableOffline(boolean availableOffline) {
2314 setFlag(FLAG_AVAILABLE_OFFLINE, availableOffline);
2315 return this;
2316 }
2317
2318 /**
2319 * Get whether this action is available when the wearable device is not connected to
2320 * a companion device. The user can still trigger this action when the wearable device is
2321 * offline, but a visual hint will indicate that the action may not be available.
2322 * Defaults to true.
2323 */
2324 public boolean isAvailableOffline() {
2325 return (mFlags & FLAG_AVAILABLE_OFFLINE) != 0;
2326 }
2327
2328 private void setFlag(int mask, boolean value) {
2329 if (value) {
2330 mFlags |= mask;
2331 } else {
2332 mFlags &= ~mask;
2333 }
2334 }
2335
2336 /**
2337 * Set a label to display while the wearable is preparing to automatically execute the
2338 * action. This is usually a 'ing' verb ending in ellipsis like "Sending..."
2339 *
2340 * @param label the label to display while the action is being prepared to execute
2341 * @return this object for method chaining
2342 */
2343 @Deprecated
2344 public WearableExtender setInProgressLabel(CharSequence label) {
2345 mInProgressLabel = label;
2346 return this;
2347 }
2348
2349 /**
2350 * Get the label to display while the wearable is preparing to automatically execute
2351 * the action. This is usually a 'ing' verb ending in ellipsis like "Sending..."
2352 *
2353 * @return the label to display while the action is being prepared to execute
2354 */
2355 @Deprecated
2356 public CharSequence getInProgressLabel() {
2357 return mInProgressLabel;
2358 }
2359
2360 /**
2361 * Set a label to display to confirm that the action should be executed.
2362 * This is usually an imperative verb like "Send".
2363 *
2364 * @param label the label to confirm the action should be executed
2365 * @return this object for method chaining
2366 */
2367 @Deprecated
2368 public WearableExtender setConfirmLabel(CharSequence label) {
2369 mConfirmLabel = label;
2370 return this;
2371 }
2372
2373 /**
2374 * Get the label to display to confirm that the action should be executed.
2375 * This is usually an imperative verb like "Send".
2376 *
2377 * @return the label to confirm the action should be executed
2378 */
2379 @Deprecated
2380 public CharSequence getConfirmLabel() {
2381 return mConfirmLabel;
2382 }
2383
2384 /**
2385 * Set a label to display to cancel the action.
2386 * This is usually an imperative verb, like "Cancel".
2387 *
2388 * @param label the label to display to cancel the action
2389 * @return this object for method chaining
2390 */
2391 @Deprecated
2392 public WearableExtender setCancelLabel(CharSequence label) {
2393 mCancelLabel = label;
2394 return this;
2395 }
2396
2397 /**
2398 * Get the label to display to cancel the action.
2399 * This is usually an imperative verb like "Cancel".
2400 *
2401 * @return the label to display to cancel the action
2402 */
2403 @Deprecated
2404 public CharSequence getCancelLabel() {
2405 return mCancelLabel;
2406 }
2407
2408 /**
2409 * Set a hint that this Action will launch an {@link Activity} directly, telling the
2410 * platform that it can generate the appropriate transitions.
2411 * @param hintLaunchesActivity {@code true} if the content intent will launch
2412 * an activity and transitions should be generated, false otherwise.
2413 * @return this object for method chaining
2414 */
2415 public WearableExtender setHintLaunchesActivity(
2416 boolean hintLaunchesActivity) {
2417 setFlag(FLAG_HINT_LAUNCHES_ACTIVITY, hintLaunchesActivity);
2418 return this;
2419 }
2420
2421 /**
2422 * Get a hint that this Action will launch an {@link Activity} directly, telling the
2423 * platform that it can generate the appropriate transitions
2424 * @return {@code true} if the content intent will launch an activity and transitions
2425 * should be generated, false otherwise. The default value is {@code false} if this was
2426 * never set.
2427 */
2428 public boolean getHintLaunchesActivity() {
2429 return (mFlags & FLAG_HINT_LAUNCHES_ACTIVITY) != 0;
2430 }
2431
2432 /**
2433 * Set a hint that this Action should be displayed inline.
2434 *
2435 * @param hintDisplayInline {@code true} if action should be displayed inline, false
2436 * otherwise
2437 * @return this object for method chaining
2438 */
2439 public WearableExtender setHintDisplayActionInline(
2440 boolean hintDisplayInline) {
2441 setFlag(FLAG_HINT_DISPLAY_INLINE, hintDisplayInline);
2442 return this;
2443 }
2444
2445 /**
2446 * Get a hint that this Action should be displayed inline.
2447 *
2448 * @return {@code true} if the Action should be displayed inline, {@code false}
2449 * otherwise. The default value is {@code false} if this was never set.
2450 */
2451 public boolean getHintDisplayActionInline() {
2452 return (mFlags & FLAG_HINT_DISPLAY_INLINE) != 0;
2453 }
2454 }
2455
2456 /**
2457 * Provides meaning to an {@link Action} that hints at what the associated
2458 * {@link PendingIntent} will do. For example, an {@link Action} with a
2459 * {@link PendingIntent} that replies to a text message notification may have the
2460 * {@link #SEMANTIC_ACTION_REPLY} {@code SemanticAction} set within it.
2461 *
2462 * @hide
2463 */
2464 @IntDef(prefix = { "SEMANTIC_ACTION_" }, value = {
2465 SEMANTIC_ACTION_NONE,
2466 SEMANTIC_ACTION_REPLY,
2467 SEMANTIC_ACTION_MARK_AS_READ,
2468 SEMANTIC_ACTION_MARK_AS_UNREAD,
2469 SEMANTIC_ACTION_DELETE,
2470 SEMANTIC_ACTION_ARCHIVE,
2471 SEMANTIC_ACTION_MUTE,
2472 SEMANTIC_ACTION_UNMUTE,
2473 SEMANTIC_ACTION_THUMBS_UP,
2474 SEMANTIC_ACTION_THUMBS_DOWN,
2475 SEMANTIC_ACTION_CALL,
2476 SEMANTIC_ACTION_MARK_CONVERSATION_AS_PRIORITY,
2477 SEMANTIC_ACTION_CONVERSATION_IS_PHISHING
2478 })
2479 @Retention(RetentionPolicy.SOURCE)
2480 public @interface SemanticAction {}
2481 }
2482
2483 /**
2484 * Array of all {@link Action} structures attached to this notification by
2485 * {@link Builder#addAction(int, CharSequence, PendingIntent)}. Mostly useful for instances of
2486 * {@link android.service.notification.NotificationListenerService} that provide an alternative
2487 * interface for invoking actions.
2488 */
2489 public Action[] actions;
2490
2491 /**
2492 * Replacement version of this notification whose content will be shown
2493 * in an insecure context such as atop a secure keyguard. See {@link #visibility}
2494 * and {@link #VISIBILITY_PUBLIC}.
2495 */
2496 public Notification publicVersion;
2497
2498 /**
2499 * Constructs a Notification object with default values.
2500 * You might want to consider using {@link Builder} instead.
2501 */
2502 public Notification()
2503 {
2504 this.when = System.currentTimeMillis();
2505 this.creationTime = System.currentTimeMillis();
2506 this.priority = PRIORITY_DEFAULT;
2507 }
2508
2509 /**
2510 * @hide
2511 */
2512 @UnsupportedAppUsage
2513 public Notification(Context context, int icon, CharSequence tickerText, long when,
2514 CharSequence contentTitle, CharSequence contentText, Intent contentIntent)
2515 {
2516 new Builder(context)
2517 .setWhen(when)
2518 .setSmallIcon(icon)
2519 .setTicker(tickerText)
2520 .setContentTitle(contentTitle)
2521 .setContentText(contentText)
2522 .setContentIntent(PendingIntent.getActivity(
2523 context, 0, contentIntent, PendingIntent.FLAG_MUTABLE))
2524 .buildInto(this);
2525 }
2526
2527 /**
2528 * Constructs a Notification object with the information needed to
2529 * have a status bar icon without the standard expanded view.
2530 *
2531 * @param icon The resource id of the icon to put in the status bar.
2532 * @param tickerText The text that flows by in the status bar when the notification first
2533 * activates.
2534 * @param when The time to show in the time field. In the System.currentTimeMillis
2535 * timebase.
2536 *
2537 * @deprecated Use {@link Builder} instead.
2538 */
2539 @Deprecated
2540 public Notification(int icon, CharSequence tickerText, long when)
2541 {
2542 this.icon = icon;
2543 this.tickerText = tickerText;
2544 this.when = when;
2545 this.creationTime = System.currentTimeMillis();
2546 }
2547
2548 /**
2549 * Unflatten the notification from a parcel.
2550 */
2551 @SuppressWarnings("unchecked")
2552 public Notification(Parcel parcel) {
2553 // IMPORTANT: Add unmarshaling code in readFromParcel as the pending
2554 // intents in extras are always written as the last entry.
2555 readFromParcelImpl(parcel);
2556 // Must be read last!
2557 allPendingIntents = (ArraySet<PendingIntent>) parcel.readArraySet(null);
2558 }
2559
2560 private void readFromParcelImpl(Parcel parcel)
2561 {
2562 int version = parcel.readInt();
2563
2564 mAllowlistToken = parcel.readStrongBinder();
2565 if (mAllowlistToken == null) {
2566 mAllowlistToken = processAllowlistToken;
2567 }
2568 // Propagate this token to all pending intents that are unmarshalled from the parcel.
2569 parcel.setClassCookie(PendingIntent.class, mAllowlistToken);
2570
2571 when = parcel.readLong();
2572 creationTime = parcel.readLong();
2573 if (parcel.readInt() != 0) {
2574 mSmallIcon = Icon.CREATOR.createFromParcel(parcel);
2575 if (mSmallIcon.getType() == Icon.TYPE_RESOURCE) {
2576 icon = mSmallIcon.getResId();
2577 }
2578 }
2579 number = parcel.readInt();
2580 if (parcel.readInt() != 0) {
2581 contentIntent = PendingIntent.CREATOR.createFromParcel(parcel);
2582 }
2583 if (parcel.readInt() != 0) {
2584 deleteIntent = PendingIntent.CREATOR.createFromParcel(parcel);
2585 }
2586 if (parcel.readInt() != 0) {
2587 tickerText = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(parcel);
2588 }
2589 if (parcel.readInt() != 0) {
2590 tickerView = RemoteViews.CREATOR.createFromParcel(parcel);
2591 }
2592 if (parcel.readInt() != 0) {
2593 contentView = RemoteViews.CREATOR.createFromParcel(parcel);
2594 }
2595 if (parcel.readInt() != 0) {
2596 mLargeIcon = Icon.CREATOR.createFromParcel(parcel);
2597 }
2598 defaults = parcel.readInt();
2599 flags = parcel.readInt();
2600 if (parcel.readInt() != 0) {
2601 sound = Uri.CREATOR.createFromParcel(parcel);
2602 }
2603
2604 audioStreamType = parcel.readInt();
2605 if (parcel.readInt() != 0) {
2606 audioAttributes = AudioAttributes.CREATOR.createFromParcel(parcel);
2607 }
2608 vibrate = parcel.createLongArray();
2609 ledARGB = parcel.readInt();
2610 ledOnMS = parcel.readInt();
2611 ledOffMS = parcel.readInt();
2612 iconLevel = parcel.readInt();
2613
2614 if (parcel.readInt() != 0) {
2615 fullScreenIntent = PendingIntent.CREATOR.createFromParcel(parcel);
2616 }
2617
2618 priority = parcel.readInt();
2619
2620 category = parcel.readString8();
2621
2622 mGroupKey = parcel.readString8();
2623
2624 mSortKey = parcel.readString8();
2625
2626 extras = Bundle.setDefusable(parcel.readBundle(), true); // may be null
2627 fixDuplicateExtras();
2628
2629 actions = parcel.createTypedArray(Action.CREATOR); // may be null
2630
2631 if (parcel.readInt() != 0) {
2632 bigContentView = RemoteViews.CREATOR.createFromParcel(parcel);
2633 }
2634
2635 if (parcel.readInt() != 0) {
2636 headsUpContentView = RemoteViews.CREATOR.createFromParcel(parcel);
2637 }
2638
2639 visibility = parcel.readInt();
2640
2641 if (parcel.readInt() != 0) {
2642 publicVersion = Notification.CREATOR.createFromParcel(parcel);
2643 }
2644
2645 color = parcel.readInt();
2646
2647 if (parcel.readInt() != 0) {
2648 mChannelId = parcel.readString8();
2649 }
2650 mTimeout = parcel.readLong();
2651
2652 if (parcel.readInt() != 0) {
2653 mShortcutId = parcel.readString8();
2654 }
2655
2656 if (parcel.readInt() != 0) {
2657 mLocusId = LocusId.CREATOR.createFromParcel(parcel);
2658 }
2659
2660 mBadgeIcon = parcel.readInt();
2661
2662 if (parcel.readInt() != 0) {
2663 mSettingsText = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(parcel);
2664 }
2665
2666 mGroupAlertBehavior = parcel.readInt();
2667 if (parcel.readInt() != 0) {
2668 mBubbleMetadata = BubbleMetadata.CREATOR.createFromParcel(parcel);
2669 }
2670
2671 mAllowSystemGeneratedContextualActions = parcel.readBoolean();
2672
2673 mFgsDeferBehavior = parcel.readInt();
2674 }
2675
2676 @Override
2677 public Notification clone() {
2678 Notification that = new Notification();
2679 cloneInto(that, true);
2680 return that;
2681 }
2682
2683 /**
2684 * Copy all (or if heavy is false, all except Bitmaps and RemoteViews) members
2685 * of this into that.
2686 * @hide
2687 */
2688 public void cloneInto(Notification that, boolean heavy) {
2689 that.mAllowlistToken = this.mAllowlistToken;
2690 that.when = this.when;
2691 that.creationTime = this.creationTime;
2692 that.mSmallIcon = this.mSmallIcon;
2693 that.number = this.number;
2694
2695 // PendingIntents are global, so there's no reason (or way) to clone them.
2696 that.contentIntent = this.contentIntent;
2697 that.deleteIntent = this.deleteIntent;
2698 that.fullScreenIntent = this.fullScreenIntent;
2699
2700 if (this.tickerText != null) {
2701 that.tickerText = this.tickerText.toString();
2702 }
2703 if (heavy && this.tickerView != null) {
2704 that.tickerView = this.tickerView.clone();
2705 }
2706 if (heavy && this.contentView != null) {
2707 that.contentView = this.contentView.clone();
2708 }
2709 if (heavy && this.mLargeIcon != null) {
2710 that.mLargeIcon = this.mLargeIcon;
2711 }
2712 that.iconLevel = this.iconLevel;
2713 that.sound = this.sound; // android.net.Uri is immutable
2714 that.audioStreamType = this.audioStreamType;
2715 if (this.audioAttributes != null) {
2716 that.audioAttributes = new AudioAttributes.Builder(this.audioAttributes).build();
2717 }
2718
2719 final long[] vibrate = this.vibrate;
2720 if (vibrate != null) {
2721 final int N = vibrate.length;
2722 final long[] vib = that.vibrate = new long[N];
2723 System.arraycopy(vibrate, 0, vib, 0, N);
2724 }
2725
2726 that.ledARGB = this.ledARGB;
2727 that.ledOnMS = this.ledOnMS;
2728 that.ledOffMS = this.ledOffMS;
2729 that.defaults = this.defaults;
2730
2731 that.flags = this.flags;
2732
2733 that.priority = this.priority;
2734
2735 that.category = this.category;
2736
2737 that.mGroupKey = this.mGroupKey;
2738
2739 that.mSortKey = this.mSortKey;
2740
2741 if (this.extras != null) {
2742 try {
2743 that.extras = new Bundle(this.extras);
2744 // will unparcel
2745 that.extras.size();
2746 } catch (BadParcelableException e) {
2747 Log.e(TAG, "could not unparcel extras from notification: " + this, e);
2748 that.extras = null;
2749 }
2750 }
2751
2752 if (!ArrayUtils.isEmpty(allPendingIntents)) {
2753 that.allPendingIntents = new ArraySet<>(allPendingIntents);
2754 }
2755
2756 if (this.actions != null) {
2757 that.actions = new Action[this.actions.length];
2758 for(int i=0; i<this.actions.length; i++) {
2759 if ( this.actions[i] != null) {
2760 that.actions[i] = this.actions[i].clone();
2761 }
2762 }
2763 }
2764
2765 if (heavy && this.bigContentView != null) {
2766 that.bigContentView = this.bigContentView.clone();
2767 }
2768
2769 if (heavy && this.headsUpContentView != null) {
2770 that.headsUpContentView = this.headsUpContentView.clone();
2771 }
2772
2773 that.visibility = this.visibility;
2774
2775 if (this.publicVersion != null) {
2776 that.publicVersion = new Notification();
2777 this.publicVersion.cloneInto(that.publicVersion, heavy);
2778 }
2779
2780 that.color = this.color;
2781
2782 that.mChannelId = this.mChannelId;
2783 that.mTimeout = this.mTimeout;
2784 that.mShortcutId = this.mShortcutId;
2785 that.mLocusId = this.mLocusId;
2786 that.mBadgeIcon = this.mBadgeIcon;
2787 that.mSettingsText = this.mSettingsText;
2788 that.mGroupAlertBehavior = this.mGroupAlertBehavior;
2789 that.mFgsDeferBehavior = this.mFgsDeferBehavior;
2790 that.mBubbleMetadata = this.mBubbleMetadata;
2791 that.mAllowSystemGeneratedContextualActions = this.mAllowSystemGeneratedContextualActions;
2792
2793 if (!heavy) {
2794 that.lightenPayload(); // will clean out extras
2795 }
2796 }
2797
2798 private static void visitIconUri(@NonNull Consumer<Uri> visitor, @Nullable Icon icon) {
2799 if (icon == null) return;
2800 final int iconType = icon.getType();
2801 if (iconType == TYPE_URI || iconType == TYPE_URI_ADAPTIVE_BITMAP) {
2802 visitor.accept(icon.getUri());
2803 }
2804 }
2805
2806 /**
2807 * Note all {@link Uri} that are referenced internally, with the expectation
2808 * that Uri permission grants will need to be issued to ensure the recipient
2809 * of this object is able to render its contents.
2810 *
2811 * @hide
2812 */
2813 public void visitUris(@NonNull Consumer<Uri> visitor) {
2814 visitor.accept(sound);
2815
2816 if (tickerView != null) tickerView.visitUris(visitor);
2817 if (contentView != null) contentView.visitUris(visitor);
2818 if (bigContentView != null) bigContentView.visitUris(visitor);
2819 if (headsUpContentView != null) headsUpContentView.visitUris(visitor);
2820
2821 visitIconUri(visitor, mSmallIcon);
2822 visitIconUri(visitor, mLargeIcon);
2823
2824 if (actions != null) {
2825 for (Action action : actions) {
2826 visitIconUri(visitor, action.getIcon());
2827 }
2828 }
2829
2830 if (extras != null) {
2831 visitIconUri(visitor, extras.getParcelable(EXTRA_LARGE_ICON_BIG, Icon.class));
2832 visitIconUri(visitor, extras.getParcelable(EXTRA_PICTURE_ICON, Icon.class));
2833
2834 // NOTE: The documentation of EXTRA_AUDIO_CONTENTS_URI explicitly says that it is a
2835 // String representation of a Uri, but the previous implementation (and unit test) of
2836 // this method has always treated it as a Uri object. Given the inconsistency,
2837 // supporting both going forward is the safest choice.
2838 Object audioContentsUri = extras.get(EXTRA_AUDIO_CONTENTS_URI);
2839 if (audioContentsUri instanceof Uri) {
2840 visitor.accept((Uri) audioContentsUri);
2841 } else if (audioContentsUri instanceof String) {
2842 visitor.accept(Uri.parse((String) audioContentsUri));
2843 }
2844
2845 if (extras.containsKey(EXTRA_BACKGROUND_IMAGE_URI)) {
2846 visitor.accept(Uri.parse(extras.getString(EXTRA_BACKGROUND_IMAGE_URI)));
2847 }
2848
2849 ArrayList<Person> people = extras.getParcelableArrayList(EXTRA_PEOPLE_LIST);
2850 if (people != null && !people.isEmpty()) {
2851 for (Person p : people) {
2852 visitor.accept(p.getIconUri());
2853 }
2854 }
2855
2856 final Person person = extras.getParcelable(EXTRA_MESSAGING_PERSON, Person.class);
2857 if (person != null) {
2858 visitor.accept(person.getIconUri());
2859 }
2860 }
2861
2862 if (isStyle(MessagingStyle.class) && extras != null) {
2863 final Parcelable[] messages = extras.getParcelableArray(EXTRA_MESSAGES);
2864 if (!ArrayUtils.isEmpty(messages)) {
2865 for (MessagingStyle.Message message : MessagingStyle.Message
2866 .getMessagesFromBundleArray(messages)) {
2867 visitor.accept(message.getDataUri());
2868
2869 Person senderPerson = message.getSenderPerson();
2870 if (senderPerson != null) {
2871 visitor.accept(senderPerson.getIconUri());
2872 }
2873 }
2874 }
2875
2876 final Parcelable[] historic = extras.getParcelableArray(EXTRA_HISTORIC_MESSAGES);
2877 if (!ArrayUtils.isEmpty(historic)) {
2878 for (MessagingStyle.Message message : MessagingStyle.Message
2879 .getMessagesFromBundleArray(historic)) {
2880 visitor.accept(message.getDataUri());
2881
2882 Person senderPerson = message.getSenderPerson();
2883 if (senderPerson != null) {
2884 visitor.accept(senderPerson.getIconUri());
2885 }
2886 }
2887 }
2888 }
2889
2890 if (mBubbleMetadata != null) {
2891 visitIconUri(visitor, mBubbleMetadata.getIcon());
2892 }
2893 }
2894
2895 /**
2896 * Removes heavyweight parts of the Notification object for archival or for sending to
2897 * listeners when the full contents are not necessary.
2898 * @hide
2899 */
2900 public final void lightenPayload() {
2901 tickerView = null;
2902 contentView = null;
2903 bigContentView = null;
2904 headsUpContentView = null;
2905 mLargeIcon = null;
2906 if (extras != null && !extras.isEmpty()) {
2907 final Set<String> keyset = extras.keySet();
2908 final int N = keyset.size();
2909 final String[] keys = keyset.toArray(new String[N]);
2910 for (int i=0; i<N; i++) {
2911 final String key = keys[i];
2912 if (TvExtender.EXTRA_TV_EXTENDER.equals(key)) {
2913 continue;
2914 }
2915 final Object obj = extras.get(key);
2916 if (obj != null &&
2917 ( obj instanceof Parcelable
2918 || obj instanceof Parcelable[]
2919 || obj instanceof SparseArray
2920 || obj instanceof ArrayList)) {
2921 extras.remove(key);
2922 }
2923 }
2924 }
2925 }
2926
2927 /**
2928 * Make sure this CharSequence is safe to put into a bundle, which basically
2929 * means it had better not be some custom Parcelable implementation.
2930 * @hide
2931 */
2932 public static CharSequence safeCharSequence(CharSequence cs) {
2933 if (cs == null) return cs;
2934 if (cs.length() > MAX_CHARSEQUENCE_LENGTH) {
2935 cs = cs.subSequence(0, MAX_CHARSEQUENCE_LENGTH);
2936 }
2937 if (cs instanceof Parcelable) {
2938 Log.e(TAG, "warning: " + cs.getClass().getCanonicalName()
2939 + " instance is a custom Parcelable and not allowed in Notification");
2940 return cs.toString();
2941 }
2942 return removeTextSizeSpans(cs);
2943 }
2944
2945 private static CharSequence removeTextSizeSpans(CharSequence charSequence) {
2946 if (charSequence instanceof Spanned) {
2947 Spanned ss = (Spanned) charSequence;
2948 Object[] spans = ss.getSpans(0, ss.length(), Object.class);
2949 SpannableStringBuilder builder = new SpannableStringBuilder(ss.toString());
2950 for (Object span : spans) {
2951 Object resultSpan = span;
2952 if (resultSpan instanceof CharacterStyle) {
2953 resultSpan = ((CharacterStyle) span).getUnderlying();
2954 }
2955 if (resultSpan instanceof TextAppearanceSpan) {
2956 TextAppearanceSpan originalSpan = (TextAppearanceSpan) resultSpan;
2957 resultSpan = new TextAppearanceSpan(
2958 originalSpan.getFamily(),
2959 originalSpan.getTextStyle(),
2960 -1,
2961 originalSpan.getTextColor(),
2962 originalSpan.getLinkTextColor());
2963 } else if (resultSpan instanceof RelativeSizeSpan
2964 || resultSpan instanceof AbsoluteSizeSpan) {
2965 continue;
2966 } else {
2967 resultSpan = span;
2968 }
2969 builder.setSpan(resultSpan, ss.getSpanStart(span), ss.getSpanEnd(span),
2970 ss.getSpanFlags(span));
2971 }
2972 return builder;
2973 }
2974 return charSequence;
2975 }
2976
2977 public int describeContents() {
2978 return 0;
2979 }
2980
2981 /**
2982 * Flatten this notification into a parcel.
2983 */
2984 public void writeToParcel(Parcel parcel, int flags) {
2985 // We need to mark all pending intents getting into the notification
2986 // system as being put there to later allow the notification ranker
2987 // to launch them and by doing so add the app to the battery saver white
2988 // list for a short period of time. The problem is that the system
2989 // cannot look into the extras as there may be parcelables there that
2990 // the platform does not know how to handle. To go around that we have
2991 // an explicit list of the pending intents in the extras bundle.
2992 final boolean collectPendingIntents = (allPendingIntents == null);
2993 if (collectPendingIntents) {
2994 PendingIntent.setOnMarshaledListener(
2995 (PendingIntent intent, Parcel out, int outFlags) -> {
2996 if (parcel == out) {
2997 synchronized (this) {
2998 if (allPendingIntents == null) {
2999 allPendingIntents = new ArraySet<>();
3000 }
3001 allPendingIntents.add(intent);
3002 }
3003 }
3004 });
3005 }
3006 try {
3007 // IMPORTANT: Add marshaling code in writeToParcelImpl as we
3008 // want to intercept all pending events written to the parcel.
3009 writeToParcelImpl(parcel, flags);
3010 synchronized (this) {
3011 // Must be written last!
3012 parcel.writeArraySet(allPendingIntents);
3013 }
3014 } finally {
3015 if (collectPendingIntents) {
3016 PendingIntent.setOnMarshaledListener(null);
3017 }
3018 }
3019 }
3020
3021 private void writeToParcelImpl(Parcel parcel, int flags) {
3022 parcel.writeInt(1);
3023
3024 parcel.writeStrongBinder(mAllowlistToken);
3025 parcel.writeLong(when);
3026 parcel.writeLong(creationTime);
3027 if (mSmallIcon == null && icon != 0) {
3028 // you snuck an icon in here without using the builder; let's try to keep it
3029 mSmallIcon = Icon.createWithResource("", icon);
3030 }
3031 if (mSmallIcon != null) {
3032 parcel.writeInt(1);
3033 mSmallIcon.writeToParcel(parcel, 0);
3034 } else {
3035 parcel.writeInt(0);
3036 }
3037 parcel.writeInt(number);
3038 if (contentIntent != null) {
3039 parcel.writeInt(1);
3040 contentIntent.writeToParcel(parcel, 0);
3041 } else {
3042 parcel.writeInt(0);
3043 }
3044 if (deleteIntent != null) {
3045 parcel.writeInt(1);
3046 deleteIntent.writeToParcel(parcel, 0);
3047 } else {
3048 parcel.writeInt(0);
3049 }
3050 if (tickerText != null) {
3051 parcel.writeInt(1);
3052 TextUtils.writeToParcel(tickerText, parcel, flags);
3053 } else {
3054 parcel.writeInt(0);
3055 }
3056 if (tickerView != null) {
3057 parcel.writeInt(1);
3058 tickerView.writeToParcel(parcel, 0);
3059 } else {
3060 parcel.writeInt(0);
3061 }
3062 if (contentView != null) {
3063 parcel.writeInt(1);
3064 contentView.writeToParcel(parcel, 0);
3065 } else {
3066 parcel.writeInt(0);
3067 }
3068 if (mLargeIcon == null && largeIcon != null) {
3069 // you snuck an icon in here without using the builder; let's try to keep it
3070 mLargeIcon = Icon.createWithBitmap(largeIcon);
3071 }
3072 if (mLargeIcon != null) {
3073 parcel.writeInt(1);
3074 mLargeIcon.writeToParcel(parcel, 0);
3075 } else {
3076 parcel.writeInt(0);
3077 }
3078
3079 parcel.writeInt(defaults);
3080 parcel.writeInt(this.flags);
3081
3082 if (sound != null) {
3083 parcel.writeInt(1);
3084 sound.writeToParcel(parcel, 0);
3085 } else {
3086 parcel.writeInt(0);
3087 }
3088 parcel.writeInt(audioStreamType);
3089
3090 if (audioAttributes != null) {
3091 parcel.writeInt(1);
3092 audioAttributes.writeToParcel(parcel, 0);
3093 } else {
3094 parcel.writeInt(0);
3095 }
3096
3097 parcel.writeLongArray(vibrate);
3098 parcel.writeInt(ledARGB);
3099 parcel.writeInt(ledOnMS);
3100 parcel.writeInt(ledOffMS);
3101 parcel.writeInt(iconLevel);
3102
3103 if (fullScreenIntent != null) {
3104 parcel.writeInt(1);
3105 fullScreenIntent.writeToParcel(parcel, 0);
3106 } else {
3107 parcel.writeInt(0);
3108 }
3109
3110 parcel.writeInt(priority);
3111
3112 parcel.writeString8(category);
3113
3114 parcel.writeString8(mGroupKey);
3115
3116 parcel.writeString8(mSortKey);
3117
3118 parcel.writeBundle(extras); // null ok
3119
3120 parcel.writeTypedArray(actions, 0); // null ok
3121
3122 if (bigContentView != null) {
3123 parcel.writeInt(1);
3124 bigContentView.writeToParcel(parcel, 0);
3125 } else {
3126 parcel.writeInt(0);
3127 }
3128
3129 if (headsUpContentView != null) {
3130 parcel.writeInt(1);
3131 headsUpContentView.writeToParcel(parcel, 0);
3132 } else {
3133 parcel.writeInt(0);
3134 }
3135
3136 parcel.writeInt(visibility);
3137
3138 if (publicVersion != null) {
3139 parcel.writeInt(1);
3140 publicVersion.writeToParcel(parcel, 0);
3141 } else {
3142 parcel.writeInt(0);
3143 }
3144
3145 parcel.writeInt(color);
3146
3147 if (mChannelId != null) {
3148 parcel.writeInt(1);
3149 parcel.writeString8(mChannelId);
3150 } else {
3151 parcel.writeInt(0);
3152 }
3153 parcel.writeLong(mTimeout);
3154
3155 if (mShortcutId != null) {
3156 parcel.writeInt(1);
3157 parcel.writeString8(mShortcutId);
3158 } else {
3159 parcel.writeInt(0);
3160 }
3161
3162 if (mLocusId != null) {
3163 parcel.writeInt(1);
3164 mLocusId.writeToParcel(parcel, 0);
3165 } else {
3166 parcel.writeInt(0);
3167 }
3168
3169 parcel.writeInt(mBadgeIcon);
3170
3171 if (mSettingsText != null) {
3172 parcel.writeInt(1);
3173 TextUtils.writeToParcel(mSettingsText, parcel, flags);
3174 } else {
3175 parcel.writeInt(0);
3176 }
3177
3178 parcel.writeInt(mGroupAlertBehavior);
3179
3180 if (mBubbleMetadata != null) {
3181 parcel.writeInt(1);
3182 mBubbleMetadata.writeToParcel(parcel, 0);
3183 } else {
3184 parcel.writeInt(0);
3185 }
3186
3187 parcel.writeBoolean(mAllowSystemGeneratedContextualActions);
3188
3189 parcel.writeInt(mFgsDeferBehavior);
3190
3191 // mUsesStandardHeader is not written because it should be recomputed in listeners
3192 }
3193
3194 /**
3195 * Parcelable.Creator that instantiates Notification objects
3196 */
3197 public static final @android.annotation.NonNull Parcelable.Creator<Notification> CREATOR
3198 = new Parcelable.Creator<Notification>()
3199 {
3200 public Notification createFromParcel(Parcel parcel)
3201 {
3202 return new Notification(parcel);
3203 }
3204
3205 public Notification[] newArray(int size)
3206 {
3207 return new Notification[size];
3208 }
3209 };
3210
3211 /**
3212 * @hide
3213 */
3214 public static boolean areActionsVisiblyDifferent(Notification first, Notification second) {
3215 Notification.Action[] firstAs = first.actions;
3216 Notification.Action[] secondAs = second.actions;
3217 if (firstAs == null && secondAs != null || firstAs != null && secondAs == null) {
3218 return true;
3219 }
3220 if (firstAs != null && secondAs != null) {
3221 if (firstAs.length != secondAs.length) {
3222 return true;
3223 }
3224 for (int i = 0; i < firstAs.length; i++) {
3225 if (!Objects.equals(String.valueOf(firstAs[i].title),
3226 String.valueOf(secondAs[i].title))) {
3227 return true;
3228 }
3229 RemoteInput[] firstRs = firstAs[i].getRemoteInputs();
3230 RemoteInput[] secondRs = secondAs[i].getRemoteInputs();
3231 if (firstRs == null) {
3232 firstRs = new RemoteInput[0];
3233 }
3234 if (secondRs == null) {
3235 secondRs = new RemoteInput[0];
3236 }
3237 if (firstRs.length != secondRs.length) {
3238 return true;
3239 }
3240 for (int j = 0; j < firstRs.length; j++) {
3241 if (!Objects.equals(String.valueOf(firstRs[j].getLabel()),
3242 String.valueOf(secondRs[j].getLabel()))) {
3243 return true;
3244 }
3245 }
3246 }
3247 }
3248 return false;
3249 }
3250
3251 /**
3252 * @hide
3253 */
3254 public static boolean areStyledNotificationsVisiblyDifferent(Builder first, Builder second) {
3255 if (first.getStyle() == null) {
3256 return second.getStyle() != null;
3257 }
3258 if (second.getStyle() == null) {
3259 return true;
3260 }
3261 return first.getStyle().areNotificationsVisiblyDifferent(second.getStyle());
3262 }
3263
3264 /**
3265 * @hide
3266 */
3267 public static boolean areRemoteViewsChanged(Builder first, Builder second) {
3268 if (!Objects.equals(first.usesStandardHeader(), second.usesStandardHeader())) {
3269 return true;
3270 }
3271
3272 if (areRemoteViewsChanged(first.mN.contentView, second.mN.contentView)) {
3273 return true;
3274 }
3275 if (areRemoteViewsChanged(first.mN.bigContentView, second.mN.bigContentView)) {
3276 return true;
3277 }
3278 if (areRemoteViewsChanged(first.mN.headsUpContentView, second.mN.headsUpContentView)) {
3279 return true;
3280 }
3281
3282 return false;
3283 }
3284
3285 private static boolean areRemoteViewsChanged(RemoteViews first, RemoteViews second) {
3286 if (first == null && second == null) {
3287 return false;
3288 }
3289 if (first == null && second != null || first != null && second == null) {
3290 return true;
3291 }
3292
3293 if (!Objects.equals(first.getLayoutId(), second.getLayoutId())) {
3294 return true;
3295 }
3296
3297 if (!Objects.equals(first.getSequenceNumber(), second.getSequenceNumber())) {
3298 return true;
3299 }
3300
3301 return false;
3302 }
3303
3304 /**
3305 * Parcelling creates multiple copies of objects in {@code extras}. Fix them.
3306 * <p>
3307 * For backwards compatibility {@code extras} holds some references to "real" member data such
3308 * as {@link getLargeIcon()} which is mirrored by {@link #EXTRA_LARGE_ICON}. This is mostly
3309 * fine as long as the object stays in one process.
3310 * <p>
3311 * However, once the notification goes into a parcel each reference gets marshalled separately,
3312 * wasting memory. Especially with large images on Auto and TV, this is worth fixing.
3313 */
3314 private void fixDuplicateExtras() {
3315 if (extras != null) {
3316 fixDuplicateExtra(mLargeIcon, EXTRA_LARGE_ICON);
3317 }
3318 }
3319
3320 /**
3321 * If we find an extra that's exactly the same as one of the "real" fields but refers to a
3322 * separate object, replace it with the field's version to avoid holding duplicate copies.
3323 */
3324 private void fixDuplicateExtra(@Nullable Parcelable original, @NonNull String extraName) {
3325 if (original != null && extras.getParcelable(extraName) != null) {
3326 extras.putParcelable(extraName, original);
3327 }
3328 }
3329
3330 /**
3331 * Sets the {@link #contentView} field to be a view with the standard "Latest Event"
3332 * layout.
3333 *
3334 * <p>Uses the {@link #icon} and {@link #when} fields to set the icon and time fields
3335 * in the view.</p>
3336 * @param context The context for your application / activity.
3337 * @param contentTitle The title that goes in the expanded entry.
3338 * @param contentText The text that goes in the expanded entry.
3339 * @param contentIntent The intent to launch when the user clicks the expanded notification.
3340 * If this is an activity, it must include the
3341 * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires
3342 * that you take care of task management as described in the
3343 * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back
3344 * Stack</a> document.
3345 *
3346 * @deprecated Use {@link Builder} instead.
3347 * @removed
3348 */
3349 @Deprecated
3350 public void setLatestEventInfo(Context context,
3351 CharSequence contentTitle, CharSequence contentText, PendingIntent contentIntent) {
3352 if (context.getApplicationInfo().targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1){
3353 Log.e(TAG, "setLatestEventInfo() is deprecated and you should feel deprecated.",
3354 new Throwable());
3355 }
3356
3357 if (context.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N) {
3358 extras.putBoolean(EXTRA_SHOW_WHEN, true);
3359 }
3360
3361 // ensure that any information already set directly is preserved
3362 final Notification.Builder builder = new Notification.Builder(context, this);
3363
3364 // now apply the latestEventInfo fields
3365 if (contentTitle != null) {
3366 builder.setContentTitle(contentTitle);
3367 }
3368 if (contentText != null) {
3369 builder.setContentText(contentText);
3370 }
3371 builder.setContentIntent(contentIntent);
3372
3373 builder.build(); // callers expect this notification to be ready to use
3374 }
3375
3376 /**
3377 * Sets the token used for background operations for the pending intents associated with this
3378 * notification.
3379 *
3380 * This token is automatically set during deserialization for you, you usually won't need to
3381 * call this unless you want to change the existing token, if any.
3382 *
3383 * @hide
3384 */
3385 public void setAllowlistToken(@Nullable IBinder token) {
3386 mAllowlistToken = token;
3387 }
3388
3389 /**
3390 * @hide
3391 */
3392 public static void addFieldsFromContext(Context context, Notification notification) {
3393 addFieldsFromContext(context.getApplicationInfo(), notification);
3394 }
3395
3396 /**
3397 * @hide
3398 */
3399 public static void addFieldsFromContext(ApplicationInfo ai, Notification notification) {
3400 notification.extras.putParcelable(EXTRA_BUILDER_APPLICATION_INFO, ai);
3401 }
3402
3403 /**
3404 * @hide
3405 */
3406 public void dumpDebug(ProtoOutputStream proto, long fieldId) {
3407 long token = proto.start(fieldId);
3408 proto.write(NotificationProto.CHANNEL_ID, getChannelId());
3409 proto.write(NotificationProto.HAS_TICKER_TEXT, this.tickerText != null);
3410 proto.write(NotificationProto.FLAGS, this.flags);
3411 proto.write(NotificationProto.COLOR, this.color);
3412 proto.write(NotificationProto.CATEGORY, this.category);
3413 proto.write(NotificationProto.GROUP_KEY, this.mGroupKey);
3414 proto.write(NotificationProto.SORT_KEY, this.mSortKey);
3415 if (this.actions != null) {
3416 proto.write(NotificationProto.ACTION_LENGTH, this.actions.length);
3417 }
3418 if (this.visibility >= VISIBILITY_SECRET && this.visibility <= VISIBILITY_PUBLIC) {
3419 proto.write(NotificationProto.VISIBILITY, this.visibility);
3420 }
3421 if (publicVersion != null) {
3422 publicVersion.dumpDebug(proto, NotificationProto.PUBLIC_VERSION);
3423 }
3424 proto.end(token);
3425 }
3426
3427 @Override
3428 public String toString() {
3429 StringBuilder sb = new StringBuilder();
3430 sb.append("Notification(channel=");
3431 sb.append(getChannelId());
3432 sb.append(" shortcut=");
3433 sb.append(getShortcutId());
3434 sb.append(" contentView=");
3435 if (contentView != null) {
3436 sb.append(contentView.getPackage());
3437 sb.append("/0x");
3438 sb.append(Integer.toHexString(contentView.getLayoutId()));
3439 } else {
3440 sb.append("null");
3441 }
3442 sb.append(" vibrate=");
3443 if ((this.defaults & DEFAULT_VIBRATE) != 0) {
3444 sb.append("default");
3445 } else if (this.vibrate != null) {
3446 int N = this.vibrate.length-1;
3447 sb.append("[");
3448 for (int i=0; i<N; i++) {
3449 sb.append(this.vibrate[i]);
3450 sb.append(',');
3451 }
3452 if (N != -1) {
3453 sb.append(this.vibrate[N]);
3454 }
3455 sb.append("]");
3456 } else {
3457 sb.append("null");
3458 }
3459 sb.append(" sound=");
3460 if ((this.defaults & DEFAULT_SOUND) != 0) {
3461 sb.append("default");
3462 } else if (this.sound != null) {
3463 sb.append(this.sound.toString());
3464 } else {
3465 sb.append("null");
3466 }
3467 if (this.tickerText != null) {
3468 sb.append(" tick");
3469 }
3470 sb.append(" defaults=0x");
3471 sb.append(Integer.toHexString(this.defaults));
3472 sb.append(" flags=0x");
3473 sb.append(Integer.toHexString(this.flags));
3474 sb.append(String.format(" color=0x%08x", this.color));
3475 if (this.category != null) {
3476 sb.append(" category=");
3477 sb.append(this.category);
3478 }
3479 if (this.mGroupKey != null) {
3480 sb.append(" groupKey=");
3481 sb.append(this.mGroupKey);
3482 }
3483 if (this.mSortKey != null) {
3484 sb.append(" sortKey=");
3485 sb.append(this.mSortKey);
3486 }
3487 if (actions != null) {
3488 sb.append(" actions=");
3489 sb.append(actions.length);
3490 }
3491 sb.append(" vis=");
3492 sb.append(visibilityToString(this.visibility));
3493 if (this.publicVersion != null) {
3494 sb.append(" publicVersion=");
3495 sb.append(publicVersion.toString());
3496 }
3497 if (this.mLocusId != null) {
3498 sb.append(" locusId=");
3499 sb.append(this.mLocusId); // LocusId.toString() is PII safe.
3500 }
3501 sb.append(")");
3502 return sb.toString();
3503 }
3504
3505 /**
3506 * {@hide}
3507 */
3508 public static String visibilityToString(int vis) {
3509 switch (vis) {
3510 case VISIBILITY_PRIVATE:
3511 return "PRIVATE";
3512 case VISIBILITY_PUBLIC:
3513 return "PUBLIC";
3514 case VISIBILITY_SECRET:
3515 return "SECRET";
3516 default:
3517 return "UNKNOWN(" + String.valueOf(vis) + ")";
3518 }
3519 }
3520
3521 /**
3522 * {@hide}
3523 */
3524 public static String priorityToString(@Priority int pri) {
3525 switch (pri) {
3526 case PRIORITY_MIN:
3527 return "MIN";
3528 case PRIORITY_LOW:
3529 return "LOW";
3530 case PRIORITY_DEFAULT:
3531 return "DEFAULT";
3532 case PRIORITY_HIGH:
3533 return "HIGH";
3534 case PRIORITY_MAX:
3535 return "MAX";
3536 default:
3537 return "UNKNOWN(" + String.valueOf(pri) + ")";
3538 }
3539 }
3540
3541 /**
3542 * @hide
3543 */
3544 public boolean hasCompletedProgress() {
3545 // not a progress notification; can't be complete
3546 if (!extras.containsKey(EXTRA_PROGRESS)
3547 || !extras.containsKey(EXTRA_PROGRESS_MAX)) {
3548 return false;
3549 }
3550 // many apps use max 0 for 'indeterminate'; not complete
3551 if (extras.getInt(EXTRA_PROGRESS_MAX) == 0) {
3552 return false;
3553 }
3554 return extras.getInt(EXTRA_PROGRESS) == extras.getInt(EXTRA_PROGRESS_MAX);
3555 }
3556
3557 /** @removed */
3558 @Deprecated
3559 public String getChannel() {
3560 return mChannelId;
3561 }
3562
3563 /**
3564 * Returns the id of the channel this notification posts to.
3565 */
3566 public String getChannelId() {
3567 return mChannelId;
3568 }
3569
3570 /** @removed */
3571 @Deprecated
3572 public long getTimeout() {
3573 return mTimeout;
3574 }
3575
3576 /**
3577 * Returns the duration from posting after which this notification should be canceled by the
3578 * system, if it's not canceled already.
3579 */
3580 public long getTimeoutAfter() {
3581 return mTimeout;
3582 }
3583
3584 /**
3585 * Returns what icon should be shown for this notification if it is being displayed in a
3586 * Launcher that supports badging. Will be one of {@link #BADGE_ICON_NONE},
3587 * {@link #BADGE_ICON_SMALL}, or {@link #BADGE_ICON_LARGE}.
3588 */
3589 public int getBadgeIconType() {
3590 return mBadgeIcon;
3591 }
3592
3593 /**
3594 * Returns the {@link ShortcutInfo#getId() id} that this notification supersedes, if any.
3595 *
3596 * <p>Used by some Launchers that display notification content to hide shortcuts that duplicate
3597 * notifications.
3598 */
3599 public String getShortcutId() {
3600 return mShortcutId;
3601 }
3602
3603 /**
3604 * Gets the {@link LocusId} associated with this notification.
3605 *
3606 * <p>Used by the device's intelligence services to correlate objects (such as
3607 * {@link ShortcutInfo} and {@link ContentCaptureContext}) that are correlated.
3608 */
3609 @Nullable
3610 public LocusId getLocusId() {
3611 return mLocusId;
3612 }
3613
3614 /**
3615 * Returns the settings text provided to {@link Builder#setSettingsText(CharSequence)}.
3616 */
3617 public CharSequence getSettingsText() {
3618 return mSettingsText;
3619 }
3620
3621 /**
3622 * Returns which type of notifications in a group are responsible for audibly alerting the
3623 * user. See {@link #GROUP_ALERT_ALL}, {@link #GROUP_ALERT_CHILDREN},
3624 * {@link #GROUP_ALERT_SUMMARY}.
3625 */
3626 public @GroupAlertBehavior int getGroupAlertBehavior() {
3627 return mGroupAlertBehavior;
3628 }
3629
3630 /**
3631 * Returns the bubble metadata that will be used to display app content in a floating window
3632 * over the existing foreground activity.
3633 */
3634 @Nullable
3635 public BubbleMetadata getBubbleMetadata() {
3636 return mBubbleMetadata;
3637 }
3638
3639 /**
3640 * Sets the {@link BubbleMetadata} for this notification.
3641 * @hide
3642 */
3643 public void setBubbleMetadata(BubbleMetadata data) {
3644 mBubbleMetadata = data;
3645 }
3646
3647 /**
3648 * Returns whether the platform is allowed (by the app developer) to generate contextual actions
3649 * for this notification.
3650 */
3651 public boolean getAllowSystemGeneratedContextualActions() {
3652 return mAllowSystemGeneratedContextualActions;
3653 }
3654
3655 /**
3656 * The small icon representing this notification in the status bar and content view.
3657 *
3658 * @return the small icon representing this notification.
3659 *
3660 * @see Builder#getSmallIcon()
3661 * @see Builder#setSmallIcon(Icon)
3662 */
3663 public Icon getSmallIcon() {
3664 return mSmallIcon;
3665 }
3666
3667 /**
3668 * Used when notifying to clean up legacy small icons.
3669 * @hide
3670 */
3671 @UnsupportedAppUsage
3672 public void setSmallIcon(Icon icon) {
3673 mSmallIcon = icon;
3674 }
3675
3676 /**
3677 * The large icon shown in this notification's content view.
3678 * @see Builder#getLargeIcon()
3679 * @see Builder#setLargeIcon(Icon)
3680 */
3681 public Icon getLargeIcon() {
3682 return mLargeIcon;
3683 }
3684
3685 /**
3686 * @hide
3687 */
3688 @UnsupportedAppUsage
3689 public boolean isGroupSummary() {
3690 return mGroupKey != null && (flags & FLAG_GROUP_SUMMARY) != 0;
3691 }
3692
3693 /**
3694 * @hide
3695 */
3696 @UnsupportedAppUsage
3697 public boolean isGroupChild() {
3698 return mGroupKey != null && (flags & FLAG_GROUP_SUMMARY) == 0;
3699 }
3700
3701 /**
3702 * @hide
3703 */
3704 public boolean suppressAlertingDueToGrouping() {
3705 if (isGroupSummary()
3706 && getGroupAlertBehavior() == Notification.GROUP_ALERT_CHILDREN) {
3707 return true;
3708 } else if (isGroupChild()
3709 && getGroupAlertBehavior() == Notification.GROUP_ALERT_SUMMARY) {
3710 return true;
3711 }
3712 return false;
3713 }
3714
3715
3716 /**
3717 * Finds and returns a remote input and its corresponding action.
3718 *
3719 * @param requiresFreeform requires the remoteinput to allow freeform or not.
3720 * @return the result pair, {@code null} if no result is found.
3721 */
3722 @Nullable
3723 public Pair<RemoteInput, Action> findRemoteInputActionPair(boolean requiresFreeform) {
3724 if (actions == null) {
3725 return null;
3726 }
3727 for (Notification.Action action : actions) {
3728 if (action.getRemoteInputs() == null) {
3729 continue;
3730 }
3731 RemoteInput resultRemoteInput = null;
3732 for (RemoteInput remoteInput : action.getRemoteInputs()) {
3733 if (remoteInput.getAllowFreeFormInput() || !requiresFreeform) {
3734 resultRemoteInput = remoteInput;
3735 }
3736 }
3737 if (resultRemoteInput != null) {
3738 return Pair.create(resultRemoteInput, action);
3739 }
3740 }
3741 return null;
3742 }
3743
3744 /**
3745 * Returns the actions that are contextual (that is, suggested because of the content of the
3746 * notification) out of the actions in this notification.
3747 */
3748 public @NonNull List<Notification.Action> getContextualActions() {
3749 if (actions == null) return Collections.emptyList();
3750
3751 List<Notification.Action> contextualActions = new ArrayList<>();
3752 for (Notification.Action action : actions) {
3753 if (action.isContextual()) {
3754 contextualActions.add(action);
3755 }
3756 }
3757 return contextualActions;
3758 }
3759
3760 /**
3761 * Builder class for {@link Notification} objects.
3762 *
3763 * Provides a convenient way to set the various fields of a {@link Notification} and generate
3764 * content views using the platform's notification layout template. If your app supports
3765 * versions of Android as old as API level 4, you can instead use
3766 * {@link androidx.core.app.NotificationCompat.Builder NotificationCompat.Builder},
3767 * available in the <a href="{@docRoot}tools/extras/support-library.html">Android Support
3768 * library</a>.
3769 *
3770 * <p>Example:
3771 *
3772 * <pre class="prettyprint">
3773 * Notification noti = new Notification.Builder(mContext)
3774 * .setContentTitle(&quot;New mail from &quot; + sender.toString())
3775 * .setContentText(subject)
3776 * .setSmallIcon(R.drawable.new_mail)
3777 * .setLargeIcon(aBitmap)
3778 * .build();
3779 * </pre>
3780 */
3781 public static class Builder {
3782 /**
3783 * @hide
3784 */
3785 public static final String EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT =
3786 "android.rebuild.contentViewActionCount";
3787 /**
3788 * @hide
3789 */
3790 public static final String EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT
3791 = "android.rebuild.bigViewActionCount";
3792 /**
3793 * @hide
3794 */
3795 public static final String EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT
3796 = "android.rebuild.hudViewActionCount";
3797
3798 private static final boolean USE_ONLY_TITLE_IN_LOW_PRIORITY_SUMMARY =
3799 SystemProperties.getBoolean("notifications.only_title", true);
3800
3801 /**
3802 * The lightness difference that has to be added to the primary text color to obtain the
3803 * secondary text color when the background is light.
3804 */
3805 private static final int LIGHTNESS_TEXT_DIFFERENCE_LIGHT = 20;
3806
3807 /**
3808 * The lightness difference that has to be added to the primary text color to obtain the
3809 * secondary text color when the background is dark.
3810 * A bit less then the above value, since it looks better on dark backgrounds.
3811 */
3812 private static final int LIGHTNESS_TEXT_DIFFERENCE_DARK = -10;
3813
3814 private Context mContext;
3815 private Notification mN;
3816 private Bundle mUserExtras = new Bundle();
3817 private Style mStyle;
3818 @UnsupportedAppUsage
3819 private ArrayList<Action> mActions = new ArrayList<>(MAX_ACTION_BUTTONS);
3820 private ArrayList<Person> mPersonList = new ArrayList<>();
3821 private ContrastColorUtil mColorUtil;
3822 private boolean mIsLegacy;
3823 private boolean mIsLegacyInitialized;
3824
3825 /**
3826 * Caches an instance of StandardTemplateParams. Note that this may have been used before,
3827 * so make sure to call {@link StandardTemplateParams#reset()} before using it.
3828 */
3829 StandardTemplateParams mParams = new StandardTemplateParams();
3830 Colors mColors = new Colors();
3831
3832 private boolean mTintActionButtons;
3833 private boolean mInNightMode;
3834
3835 /**
3836 * Constructs a new Builder with the defaults:
3837 *
3838 * @param context
3839 * A {@link Context} that will be used by the Builder to construct the
3840 * RemoteViews. The Context will not be held past the lifetime of this Builder
3841 * object.
3842 * @param channelId
3843 * The constructed Notification will be posted on this
3844 * {@link NotificationChannel}. To use a NotificationChannel, it must first be
3845 * created using {@link NotificationManager#createNotificationChannel}.
3846 */
3847 public Builder(Context context, String channelId) {
3848 this(context, (Notification) null);
3849 mN.mChannelId = channelId;
3850 }
3851
3852 /**
3853 * @deprecated use {@link #Builder(Context, String)}
3854 * instead. All posted Notifications must specify a NotificationChannel Id.
3855 */
3856 @Deprecated
3857 public Builder(Context context) {
3858 this(context, (Notification) null);
3859 }
3860
3861 /**
3862 * @hide
3863 */
3864 public Builder(Context context, Notification toAdopt) {
3865 mContext = context;
3866 Resources res = mContext.getResources();
3867 mTintActionButtons = res.getBoolean(R.bool.config_tintNotificationActionButtons);
3868
3869 if (res.getBoolean(R.bool.config_enableNightMode)) {
3870 Configuration currentConfig = res.getConfiguration();
3871 mInNightMode = (currentConfig.uiMode & Configuration.UI_MODE_NIGHT_MASK)
3872 == Configuration.UI_MODE_NIGHT_YES;
3873 }
3874
3875 if (toAdopt == null) {
3876 mN = new Notification();
3877 if (context.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N) {
3878 mN.extras.putBoolean(EXTRA_SHOW_WHEN, true);
3879 }
3880 mN.priority = PRIORITY_DEFAULT;
3881 mN.visibility = VISIBILITY_PRIVATE;
3882 } else {
3883 mN = toAdopt;
3884 if (mN.actions != null) {
3885 Collections.addAll(mActions, mN.actions);
3886 }
3887
3888 if (mN.extras.containsKey(EXTRA_PEOPLE_LIST)) {
3889 ArrayList<Person> people = mN.extras.getParcelableArrayList(EXTRA_PEOPLE_LIST);
3890 mPersonList.addAll(people);
3891 }
3892
3893 if (mN.getSmallIcon() == null && mN.icon != 0) {
3894 setSmallIcon(mN.icon);
3895 }
3896
3897 if (mN.getLargeIcon() == null && mN.largeIcon != null) {
3898 setLargeIcon(mN.largeIcon);
3899 }
3900
3901 String templateClass = mN.extras.getString(EXTRA_TEMPLATE);
3902 if (!TextUtils.isEmpty(templateClass)) {
3903 final Class<? extends Style> styleClass
3904 = getNotificationStyleClass(templateClass);
3905 if (styleClass == null) {
3906 Log.d(TAG, "Unknown style class: " + templateClass);
3907 } else {
3908 try {
3909 final Constructor<? extends Style> ctor =
3910 styleClass.getDeclaredConstructor();
3911 ctor.setAccessible(true);
3912 final Style style = ctor.newInstance();
3913 style.restoreFromExtras(mN.extras);
3914
3915 if (style != null) {
3916 setStyle(style);
3917 }
3918 } catch (Throwable t) {
3919 Log.e(TAG, "Could not create Style", t);
3920 }
3921 }
3922 }
3923 }
3924 }
3925
3926 private ContrastColorUtil getColorUtil() {
3927 if (mColorUtil == null) {
3928 mColorUtil = ContrastColorUtil.getInstance(mContext);
3929 }
3930 return mColorUtil;
3931 }
3932
3933 /**
3934 * From Android 11, messaging notifications (those that use {@link MessagingStyle}) that
3935 * use this method to link to a published long-lived sharing shortcut may appear in a
3936 * dedicated Conversation section of the shade and may show configuration options that
3937 * are unique to conversations. This behavior should be reserved for person to person(s)
3938 * conversations where there is a likely social obligation for an individual to respond.
3939 * <p>
3940 * For example, the following are some examples of notifications that belong in the
3941 * conversation space:
3942 * <ul>
3943 * <li>1:1 conversations between two individuals</li>
3944 * <li>Group conversations between individuals where everyone can contribute</li>
3945 * </ul>
3946 * And the following are some examples of notifications that do not belong in the
3947 * conversation space:
3948 * <ul>
3949 * <li>Advertisements from a bot (even if personal and contextualized)</li>
3950 * <li>Engagement notifications from a bot</li>
3951 * <li>Directional conversations where there is an active speaker and many passive
3952 * individuals</li>
3953 * <li>Stream / posting updates from other individuals</li>
3954 * <li>Email, document comments, or other conversation types that are not real-time</li>
3955 * </ul>
3956 * </p>
3957 *
3958 * <p>
3959 * Additionally, this method can be used for all types of notifications to mark this
3960 * notification as duplicative of a Launcher shortcut. Launchers that show badges or
3961 * notification content may then suppress the shortcut in favor of the content of this
3962 * notification.
3963 * <p>
3964 * If this notification has {@link BubbleMetadata} attached that was created with
3965 * a shortcutId a check will be performed to ensure the shortcutId supplied to bubble
3966 * metadata matches the shortcutId set here, if one was set. If the shortcutId's were
3967 * specified but do not match, an exception is thrown.
3968 *
3969 * @param shortcutId the {@link ShortcutInfo#getId() id} of the shortcut this notification
3970 * is linked to
3971 *
3972 * @see BubbleMetadata.Builder#Builder(String)
3973 */
3974 @NonNull
3975 public Builder setShortcutId(String shortcutId) {
3976 mN.mShortcutId = shortcutId;
3977 return this;
3978 }
3979
3980 /**
3981 * Sets the {@link LocusId} associated with this notification.
3982 *
3983 * <p>This method should be called when the {@link LocusId} is used in other places (such
3984 * as {@link ShortcutInfo} and {@link ContentCaptureContext}) so the device's intelligence
3985 * services can correlate them.
3986 */
3987 @NonNull
3988 public Builder setLocusId(@Nullable LocusId locusId) {
3989 mN.mLocusId = locusId;
3990 return this;
3991 }
3992
3993 /**
3994 * Sets which icon to display as a badge for this notification.
3995 *
3996 * Must be one of {@link #BADGE_ICON_NONE}, {@link #BADGE_ICON_SMALL},
3997 * {@link #BADGE_ICON_LARGE}.
3998 *
3999 * Note: This value might be ignored, for launchers that don't support badge icons.
4000 */
4001 @NonNull
4002 public Builder setBadgeIconType(int icon) {
4003 mN.mBadgeIcon = icon;
4004 return this;
4005 }
4006
4007 /**
4008 * Sets the group alert behavior for this notification. Use this method to mute this
4009 * notification if alerts for this notification's group should be handled by a different
4010 * notification. This is only applicable for notifications that belong to a
4011 * {@link #setGroup(String) group}. This must be called on all notifications you want to
4012 * mute. For example, if you want only the summary of your group to make noise, all
4013 * children in the group should have the group alert behavior {@link #GROUP_ALERT_SUMMARY}.
4014 *
4015 * <p> The default value is {@link #GROUP_ALERT_ALL}.</p>
4016 */
4017 @NonNull
4018 public Builder setGroupAlertBehavior(@GroupAlertBehavior int groupAlertBehavior) {
4019 mN.mGroupAlertBehavior = groupAlertBehavior;
4020 return this;
4021 }
4022
4023 /**
4024 * Sets the {@link BubbleMetadata} that will be used to display app content in a floating
4025 * window over the existing foreground activity.
4026 *
4027 * <p>This data will be ignored unless the notification is posted to a channel that
4028 * allows {@link NotificationChannel#canBubble() bubbles}.</p>
4029 *
4030 * <p>Notifications allowed to bubble that have valid bubble metadata will display in
4031 * collapsed state outside of the notification shade on unlocked devices. When a user
4032 * interacts with the collapsed state, the bubble intent will be invoked and displayed.</p>
4033 */
4034 @NonNull
4035 public Builder setBubbleMetadata(@Nullable BubbleMetadata data) {
4036 mN.mBubbleMetadata = data;
4037 return this;
4038 }
4039
4040 /** @removed */
4041 @Deprecated
4042 public Builder setChannel(String channelId) {
4043 mN.mChannelId = channelId;
4044 return this;
4045 }
4046
4047 /**
4048 * Specifies the channel the notification should be delivered on.
4049 */
4050 @NonNull
4051 public Builder setChannelId(String channelId) {
4052 mN.mChannelId = channelId;
4053 return this;
4054 }
4055
4056 /** @removed */
4057 @Deprecated
4058 public Builder setTimeout(long durationMs) {
4059 mN.mTimeout = durationMs;
4060 return this;
4061 }
4062
4063 /**
4064 * Specifies a duration in milliseconds after which this notification should be canceled,
4065 * if it is not already canceled.
4066 */
4067 @NonNull
4068 public Builder setTimeoutAfter(long durationMs) {
4069 mN.mTimeout = durationMs;
4070 return this;
4071 }
4072
4073 /**
4074 * Add a timestamp pertaining to the notification (usually the time the event occurred).
4075 *
4076 * For apps targeting {@link android.os.Build.VERSION_CODES#N} and above, this time is not
4077 * shown anymore by default and must be opted into by using
4078 * {@link android.app.Notification.Builder#setShowWhen(boolean)}
4079 *
4080 * @see Notification#when
4081 */
4082 @NonNull
4083 public Builder setWhen(long when) {
4084 mN.when = when;
4085 return this;
4086 }
4087
4088 /**
4089 * Control whether the timestamp set with {@link #setWhen(long) setWhen} is shown
4090 * in the content view.
4091 * For apps targeting {@link android.os.Build.VERSION_CODES#N} and above, this defaults to
4092 * {@code false}. For earlier apps, the default is {@code true}.
4093 */
4094 @NonNull
4095 public Builder setShowWhen(boolean show) {
4096 mN.extras.putBoolean(EXTRA_SHOW_WHEN, show);
4097 return this;
4098 }
4099
4100 /**
4101 * Show the {@link Notification#when} field as a stopwatch.
4102 *
4103 * Instead of presenting <code>when</code> as a timestamp, the notification will show an
4104 * automatically updating display of the minutes and seconds since <code>when</code>.
4105 *
4106 * Useful when showing an elapsed time (like an ongoing phone call).
4107 *
4108 * The counter can also be set to count down to <code>when</code> when using
4109 * {@link #setChronometerCountDown(boolean)}.
4110 *
4111 * @see android.widget.Chronometer
4112 * @see Notification#when
4113 * @see #setChronometerCountDown(boolean)
4114 */
4115 @NonNull
4116 public Builder setUsesChronometer(boolean b) {
4117 mN.extras.putBoolean(EXTRA_SHOW_CHRONOMETER, b);
4118 return this;
4119 }
4120
4121 /**
4122 * Sets the Chronometer to count down instead of counting up.
4123 *
4124 * <p>This is only relevant if {@link #setUsesChronometer(boolean)} has been set to true.
4125 * If it isn't set the chronometer will count up.
4126 *
4127 * @see #setUsesChronometer(boolean)
4128 */
4129 @NonNull
4130 public Builder setChronometerCountDown(boolean countDown) {
4131 mN.extras.putBoolean(EXTRA_CHRONOMETER_COUNT_DOWN, countDown);
4132 return this;
4133 }
4134
4135 /**
4136 * Set the small icon resource, which will be used to represent the notification in the
4137 * status bar.
4138 *
4139
4140 * The platform template for the expanded view will draw this icon in the left, unless a
4141 * {@link #setLargeIcon(Bitmap) large icon} has also been specified, in which case the small
4142 * icon will be moved to the right-hand side.
4143 *
4144
4145 * @param icon
4146 * A resource ID in the application's package of the drawable to use.
4147 * @see Notification#icon
4148 */
4149 @NonNull
4150 public Builder setSmallIcon(@DrawableRes int icon) {
4151 return setSmallIcon(icon != 0
4152 ? Icon.createWithResource(mContext, icon)
4153 : null);
4154 }
4155
4156 /**
4157 * A variant of {@link #setSmallIcon(int) setSmallIcon(int)} that takes an additional
4158 * level parameter for when the icon is a {@link android.graphics.drawable.LevelListDrawable
4159 * LevelListDrawable}.
4160 *
4161 * @param icon A resource ID in the application's package of the drawable to use.
4162 * @param level The level to use for the icon.
4163 *
4164 * @see Notification#icon
4165 * @see Notification#iconLevel
4166 */
4167 @NonNull
4168 public Builder setSmallIcon(@DrawableRes int icon, int level) {
4169 mN.iconLevel = level;
4170 return setSmallIcon(icon);
4171 }
4172
4173 /**
4174 * Set the small icon, which will be used to represent the notification in the
4175 * status bar and content view (unless overridden there by a
4176 * {@link #setLargeIcon(Bitmap) large icon}).
4177 *
4178 * @param icon An Icon object to use.
4179 * @see Notification#icon
4180 */
4181 @NonNull
4182 public Builder setSmallIcon(Icon icon) {
4183 mN.setSmallIcon(icon);
4184 if (icon != null && icon.getType() == Icon.TYPE_RESOURCE) {
4185 mN.icon = icon.getResId();
4186 }
4187 return this;
4188 }
4189
4190 /**
4191 * Set the first line of text in the platform notification template.
4192 */
4193 @NonNull
4194 public Builder setContentTitle(CharSequence title) {
4195 mN.extras.putCharSequence(EXTRA_TITLE, safeCharSequence(title));
4196 return this;
4197 }
4198
4199 /**
4200 * Set the second line of text in the platform notification template.
4201 */
4202 @NonNull
4203 public Builder setContentText(CharSequence text) {
4204 mN.extras.putCharSequence(EXTRA_TEXT, safeCharSequence(text));
4205 return this;
4206 }
4207
4208 /**
4209 * This provides some additional information that is displayed in the notification. No
4210 * guarantees are given where exactly it is displayed.
4211 *
4212 * <p>This information should only be provided if it provides an essential
4213 * benefit to the understanding of the notification. The more text you provide the
4214 * less readable it becomes. For example, an email client should only provide the account
4215 * name here if more than one email account has been added.</p>
4216 *
4217 * <p>As of {@link android.os.Build.VERSION_CODES#N} this information is displayed in the
4218 * notification header area.
4219 *
4220 * On Android versions before {@link android.os.Build.VERSION_CODES#N}
4221 * this will be shown in the third line of text in the platform notification template.
4222 * You should not be using {@link #setProgress(int, int, boolean)} at the
4223 * same time on those versions; they occupy the same place.
4224 * </p>
4225 */
4226 @NonNull
4227 public Builder setSubText(CharSequence text) {
4228 mN.extras.putCharSequence(EXTRA_SUB_TEXT, safeCharSequence(text));
4229 return this;
4230 }
4231
4232 /**
4233 * Provides text that will appear as a link to your application's settings.
4234 *
4235 * <p>This text does not appear within notification {@link Style templates} but may
4236 * appear when the user uses an affordance to learn more about the notification.
4237 * Additionally, this text will not appear unless you provide a valid link target by
4238 * handling {@link #INTENT_CATEGORY_NOTIFICATION_PREFERENCES}.
4239 *
4240 * <p>This text is meant to be concise description about what the user can customize
4241 * when they click on this link. The recommended maximum length is 40 characters.
4242 * @param text
4243 * @return
4244 */
4245 @NonNull
4246 public Builder setSettingsText(CharSequence text) {
4247 mN.mSettingsText = safeCharSequence(text);
4248 return this;
4249 }
4250
4251 /**
4252 * Set the remote input history.
4253 *
4254 * This should be set to the most recent inputs that have been sent
4255 * through a {@link RemoteInput} of this Notification and cleared once the it is no
4256 * longer relevant (e.g. for chat notifications once the other party has responded).
4257 *
4258 * The most recent input must be stored at the 0 index, the second most recent at the
4259 * 1 index, etc. Note that the system will limit both how far back the inputs will be shown
4260 * and how much of each individual input is shown.
4261 *
4262 * <p>Note: The reply text will only be shown on notifications that have least one action
4263 * with a {@code RemoteInput}.</p>
4264 */
4265 @NonNull
4266 public Builder setRemoteInputHistory(CharSequence[] text) {
4267 if (text == null) {
4268 mN.extras.putCharSequenceArray(EXTRA_REMOTE_INPUT_HISTORY, null);
4269 } else {
4270 final int itemCount = Math.min(MAX_REPLY_HISTORY, text.length);
4271 CharSequence[] safe = new CharSequence[itemCount];
4272 RemoteInputHistoryItem[] items = new RemoteInputHistoryItem[itemCount];
4273 for (int i = 0; i < itemCount; i++) {
4274 safe[i] = safeCharSequence(text[i]);
4275 items[i] = new RemoteInputHistoryItem(text[i]);
4276 }
4277 mN.extras.putCharSequenceArray(EXTRA_REMOTE_INPUT_HISTORY, safe);
4278
4279 // Also add these messages as structured history items.
4280 mN.extras.putParcelableArray(EXTRA_REMOTE_INPUT_HISTORY_ITEMS, items);
4281 }
4282 return this;
4283 }
4284
4285 /**
4286 * Set the remote input history, with support for embedding URIs and mime types for
4287 * images and other media.
4288 * @hide
4289 */
4290 @NonNull
4291 public Builder setRemoteInputHistory(RemoteInputHistoryItem[] items) {
4292 if (items == null) {
4293 mN.extras.putParcelableArray(EXTRA_REMOTE_INPUT_HISTORY_ITEMS, null);
4294 } else {
4295 final int itemCount = Math.min(MAX_REPLY_HISTORY, items.length);
4296 RemoteInputHistoryItem[] history = new RemoteInputHistoryItem[itemCount];
4297 for (int i = 0; i < itemCount; i++) {
4298 history[i] = items[i];
4299 }
4300 mN.extras.putParcelableArray(EXTRA_REMOTE_INPUT_HISTORY_ITEMS, history);
4301 }
4302 return this;
4303 }
4304
4305 /**
4306 * Sets whether remote history entries view should have a spinner.
4307 * @hide
4308 */
4309 @NonNull
4310 public Builder setShowRemoteInputSpinner(boolean showSpinner) {
4311 mN.extras.putBoolean(EXTRA_SHOW_REMOTE_INPUT_SPINNER, showSpinner);
4312 return this;
4313 }
4314
4315 /**
4316 * Sets whether smart reply buttons should be hidden.
4317 * @hide
4318 */
4319 @NonNull
4320 public Builder setHideSmartReplies(boolean hideSmartReplies) {
4321 mN.extras.putBoolean(EXTRA_HIDE_SMART_REPLIES, hideSmartReplies);
4322 return this;
4323 }
4324
4325 /**
4326 * Sets the number of items this notification represents. May be displayed as a badge count
4327 * for Launchers that support badging.
4328 */
4329 @NonNull
4330 public Builder setNumber(int number) {
4331 mN.number = number;
4332 return this;
4333 }
4334
4335 /**
4336 * A small piece of additional information pertaining to this notification.
4337 *
4338 * The platform template will draw this on the last line of the notification, at the far
4339 * right (to the right of a smallIcon if it has been placed there).
4340 *
4341 * @deprecated use {@link #setSubText(CharSequence)} instead to set a text in the header.
4342 * For legacy apps targeting a version below {@link android.os.Build.VERSION_CODES#N} this
4343 * field will still show up, but the subtext will take precedence.
4344 */
4345 @Deprecated
4346 public Builder setContentInfo(CharSequence info) {
4347 mN.extras.putCharSequence(EXTRA_INFO_TEXT, safeCharSequence(info));
4348 return this;
4349 }
4350
4351 /**
4352 * Set the progress this notification represents.
4353 *
4354 * The platform template will represent this using a {@link ProgressBar}.
4355 */
4356 @NonNull
4357 public Builder setProgress(int max, int progress, boolean indeterminate) {
4358 mN.extras.putInt(EXTRA_PROGRESS, progress);
4359 mN.extras.putInt(EXTRA_PROGRESS_MAX, max);
4360 mN.extras.putBoolean(EXTRA_PROGRESS_INDETERMINATE, indeterminate);
4361 return this;
4362 }
4363
4364 /**
4365 * Supply a custom RemoteViews to use instead of the platform template.
4366 *
4367 * Use {@link #setCustomContentView(RemoteViews)} instead.
4368 */
4369 @Deprecated
4370 public Builder setContent(RemoteViews views) {
4371 return setCustomContentView(views);
4372 }
4373
4374 /**
4375 * Supply custom RemoteViews to use instead of the platform template.
4376 *
4377 * This will override the layout that would otherwise be constructed by this Builder
4378 * object.
4379 */
4380 @NonNull
4381 public Builder setCustomContentView(RemoteViews contentView) {
4382 mN.contentView = contentView;
4383 return this;
4384 }
4385
4386 /**
4387 * Supply custom RemoteViews to use instead of the platform template in the expanded form.
4388 *
4389 * This will override the expanded layout that would otherwise be constructed by this
4390 * Builder object.
4391 */
4392 @NonNull
4393 public Builder setCustomBigContentView(RemoteViews contentView) {
4394 mN.bigContentView = contentView;
4395 return this;
4396 }
4397
4398 /**
4399 * Supply custom RemoteViews to use instead of the platform template in the heads up dialog.
4400 *
4401 * This will override the heads-up layout that would otherwise be constructed by this
4402 * Builder object.
4403 */
4404 @NonNull
4405 public Builder setCustomHeadsUpContentView(RemoteViews contentView) {
4406 mN.headsUpContentView = contentView;
4407 return this;
4408 }
4409
4410 /**
4411 * Supply a {@link PendingIntent} to be sent when the notification is clicked.
4412 *
4413 * <p>As of Android {@link android.os.Build.VERSION_CODES#S}, apps targeting API level
4414 * {@link android.os.Build.VERSION_CODES#S} or higher won't be able to start activities
4415 * while processing broadcast receivers or services in response to notification clicks. To
4416 * launch an activity in those cases, provide a {@link PendingIntent} for the activity
4417 * itself.
4418 *
4419 * <p>As of {@link android.os.Build.VERSION_CODES#HONEYCOMB}, if this field is unset and you
4420 * have specified a custom RemoteViews with {@link #setContent(RemoteViews)}, you can use
4421 * {@link RemoteViews#setOnClickPendingIntent RemoteViews.setOnClickPendingIntent(int,PendingIntent)}
4422 * to assign PendingIntents to individual views in that custom layout (i.e., to create
4423 * clickable buttons inside the notification view).
4424 *
4425 * @see Notification#contentIntent Notification.contentIntent
4426 */
4427 @NonNull
4428 public Builder setContentIntent(PendingIntent intent) {
4429 mN.contentIntent = intent;
4430 return this;
4431 }
4432
4433 /**
4434 * Supply a {@link PendingIntent} to send when the notification is cleared explicitly by the user.
4435 *
4436 * @see Notification#deleteIntent
4437 */
4438 @NonNull
4439 public Builder setDeleteIntent(PendingIntent intent) {
4440 mN.deleteIntent = intent;
4441 return this;
4442 }
4443
4444 /**
4445 * An intent to launch instead of posting the notification to the status bar.
4446 * Only for use with extremely high-priority notifications demanding the user's
4447 * <strong>immediate</strong> attention, such as an incoming phone call or
4448 * alarm clock that the user has explicitly set to a particular time.
4449 * If this facility is used for something else, please give the user an option
4450 * to turn it off and use a normal notification, as this can be extremely
4451 * disruptive.
4452 *
4453 * <p>
4454 * The system UI may choose to display a heads-up notification, instead of
4455 * launching this intent, while the user is using the device.
4456 * </p>
4457 * <p>Apps targeting {@link Build.VERSION_CODES#Q} and above will have to request
4458 * a permission ({@link android.Manifest.permission#USE_FULL_SCREEN_INTENT}) in order to
4459 * use full screen intents.</p>
4460 * <p>
4461 * To be launched as a full screen intent, the notification must also be posted to a
4462 * channel with importance level set to IMPORTANCE_HIGH or higher.
4463 * </p>
4464 *
4465 * @param intent The pending intent to launch.
4466 * @param highPriority Passing true will cause this notification to be sent
4467 * even if other notifications are suppressed.
4468 *
4469 * @see Notification#fullScreenIntent
4470 */
4471 @NonNull
4472 public Builder setFullScreenIntent(PendingIntent intent, boolean highPriority) {
4473 mN.fullScreenIntent = intent;
4474 setFlag(FLAG_HIGH_PRIORITY, highPriority);
4475 return this;
4476 }
4477
4478 /**
4479 * Set the "ticker" text which is sent to accessibility services.
4480 *
4481 * @see Notification#tickerText
4482 */
4483 @NonNull
4484 public Builder setTicker(CharSequence tickerText) {
4485 mN.tickerText = safeCharSequence(tickerText);
4486 return this;
4487 }
4488
4489 /**
4490 * Obsolete version of {@link #setTicker(CharSequence)}.
4491 *
4492 */
4493 @Deprecated
4494 public Builder setTicker(CharSequence tickerText, RemoteViews views) {
4495 setTicker(tickerText);
4496 // views is ignored
4497 return this;
4498 }
4499
4500 /**
4501 * Add a large icon to the notification content view.
4502 *
4503 * In the platform template, this image will be shown either on the right of the
4504 * notification, with an aspect ratio of up to 16:9, or (when the notification is grouped)
4505 * on the left in place of the {@link #setSmallIcon(Icon) small icon}.
4506 */
4507 @NonNull
4508 public Builder setLargeIcon(Bitmap b) {
4509 return setLargeIcon(b != null ? Icon.createWithBitmap(b) : null);
4510 }
4511
4512 /**
4513 * Add a large icon to the notification content view.
4514 *
4515 * In the platform template, this image will be shown either on the right of the
4516 * notification, with an aspect ratio of up to 16:9, or (when the notification is grouped)
4517 * on the left in place of the {@link #setSmallIcon(Icon) small icon}.
4518 */
4519 @NonNull
4520 public Builder setLargeIcon(Icon icon) {
4521 mN.mLargeIcon = icon;
4522 mN.extras.putParcelable(EXTRA_LARGE_ICON, icon);
4523 return this;
4524 }
4525
4526 /**
4527 * Set the sound to play.
4528 *
4529 * It will be played using the {@link #AUDIO_ATTRIBUTES_DEFAULT default audio attributes}
4530 * for notifications.
4531 *
4532 * @deprecated use {@link NotificationChannel#setSound(Uri, AudioAttributes)} instead.
4533 */
4534 @Deprecated
4535 public Builder setSound(Uri sound) {
4536 mN.sound = sound;
4537 mN.audioAttributes = AUDIO_ATTRIBUTES_DEFAULT;
4538 return this;
4539 }
4540
4541 /**
4542 * Set the sound to play, along with a specific stream on which to play it.
4543 *
4544 * See {@link android.media.AudioManager} for the <code>STREAM_</code> constants.
4545 *
4546 * @deprecated use {@link NotificationChannel#setSound(Uri, AudioAttributes)}.
4547 */
4548 @Deprecated
4549 public Builder setSound(Uri sound, int streamType) {
4550 PlayerBase.deprecateStreamTypeForPlayback(streamType, "Notification", "setSound()");
4551 mN.sound = sound;
4552 mN.audioStreamType = streamType;
4553 return this;
4554 }
4555
4556 /**
4557 * Set the sound to play, along with specific {@link AudioAttributes audio attributes} to
4558 * use during playback.
4559 *
4560 * @deprecated use {@link NotificationChannel#setSound(Uri, AudioAttributes)} instead.
4561 * @see Notification#sound
4562 */
4563 @Deprecated
4564 public Builder setSound(Uri sound, AudioAttributes audioAttributes) {
4565 mN.sound = sound;
4566 mN.audioAttributes = audioAttributes;
4567 return this;
4568 }
4569
4570 /**
4571 * Set the vibration pattern to use.
4572 *
4573 * See {@link android.os.Vibrator#vibrate(long[], int)} for a discussion of the
4574 * <code>pattern</code> parameter.
4575 *
4576 * <p>
4577 * A notification that vibrates is more likely to be presented as a heads-up notification.
4578 * </p>
4579 *
4580 * @deprecated use {@link NotificationChannel#setVibrationPattern(long[])} instead.
4581 * @see Notification#vibrate
4582 */
4583 @Deprecated
4584 public Builder setVibrate(long[] pattern) {
4585 mN.vibrate = pattern;
4586 return this;
4587 }
4588
4589 /**
4590 * Set the desired color for the indicator LED on the device, as well as the
4591 * blink duty cycle (specified in milliseconds).
4592 *
4593
4594 * Not all devices will honor all (or even any) of these values.
4595 *
4596 * @deprecated use {@link NotificationChannel#enableLights(boolean)} instead.
4597 * @see Notification#ledARGB
4598 * @see Notification#ledOnMS
4599 * @see Notification#ledOffMS
4600 */
4601 @Deprecated
4602 public Builder setLights(@ColorInt int argb, int onMs, int offMs) {
4603 mN.ledARGB = argb;
4604 mN.ledOnMS = onMs;
4605 mN.ledOffMS = offMs;
4606 if (onMs != 0 || offMs != 0) {
4607 mN.flags |= FLAG_SHOW_LIGHTS;
4608 }
4609 return this;
4610 }
4611
4612 /**
4613 * Set whether this is an "ongoing" notification.
4614 *
4615
4616 * Ongoing notifications cannot be dismissed by the user, so your application or service
4617 * must take care of canceling them.
4618 *
4619
4620 * They are typically used to indicate a background task that the user is actively engaged
4621 * with (e.g., playing music) or is pending in some way and therefore occupying the device
4622 * (e.g., a file download, sync operation, active network connection).
4623 *
4624
4625 * @see Notification#FLAG_ONGOING_EVENT
4626 */
4627 @NonNull
4628 public Builder setOngoing(boolean ongoing) {
4629 setFlag(FLAG_ONGOING_EVENT, ongoing);
4630 return this;
4631 }
4632
4633 /**
4634 * Set whether this notification should be colorized. When set, the color set with
4635 * {@link #setColor(int)} will be used as the background color of this notification.
4636 * <p>
4637 * This should only be used for high priority ongoing tasks like navigation, an ongoing
4638 * call, or other similarly high-priority events for the user.
4639 * <p>
4640 * For most styles, the coloring will only be applied if the notification is for a
4641 * foreground service notification.
4642 * However, for {@link MediaStyle} and {@link DecoratedMediaCustomViewStyle} notifications
4643 * that have a media session attached there is no such requirement.
4644 *
4645 * @see #setColor(int)
4646 * @see MediaStyle#setMediaSession(MediaSession.Token)
4647 */
4648 @NonNull
4649 public Builder setColorized(boolean colorize) {
4650 mN.extras.putBoolean(EXTRA_COLORIZED, colorize);
4651 return this;
4652 }
4653
4654 /**
4655 * Set this flag if you would only like the sound, vibrate
4656 * and ticker to be played if the notification is not already showing.
4657 *
4658 * Note that using this flag will stop any ongoing alerting behaviour such
4659 * as sound, vibration or blinking notification LED.
4660 *
4661 * @see Notification#FLAG_ONLY_ALERT_ONCE
4662 */
4663 @NonNull
4664 public Builder setOnlyAlertOnce(boolean onlyAlertOnce) {
4665 setFlag(FLAG_ONLY_ALERT_ONCE, onlyAlertOnce);
4666 return this;
4667 }
4668
4669 /**
4670 * Specify a desired visibility policy for a Notification associated with a
4671 * foreground service. By default, the system can choose to defer
4672 * visibility of the notification for a short time after the service is
4673 * started. Pass
4674 * {@link Notification#FOREGROUND_SERVICE_IMMEDIATE FOREGROUND_SERVICE_IMMEDIATE}
4675 * to this method in order to guarantee that visibility is never deferred. Pass
4676 * {@link Notification#FOREGROUND_SERVICE_DEFERRED FOREGROUND_SERVICE_DEFERRED}
4677 * to request that visibility is deferred whenever possible.
4678 *
4679 * <p class="note">Note that deferred visibility is not guaranteed. There
4680 * may be some circumstances under which the system will show the foreground
4681 * service's associated Notification immediately even when the app has used
4682 * this method to explicitly request deferred display.</p>
4683 * @param behavior One of
4684 * {@link Notification#FOREGROUND_SERVICE_DEFAULT FOREGROUND_SERVICE_DEFAULT},
4685 * {@link Notification#FOREGROUND_SERVICE_IMMEDIATE FOREGROUND_SERVICE_IMMEDIATE},
4686 * or {@link Notification#FOREGROUND_SERVICE_DEFERRED FOREGROUND_SERVICE_DEFERRED}
4687 * @return
4688 */
4689 @NonNull
4690 public Builder setForegroundServiceBehavior(@ServiceNotificationPolicy int behavior) {
4691 mN.mFgsDeferBehavior = behavior;
4692 return this;
4693 }
4694
4695 /**
4696 * Make this notification automatically dismissed when the user touches it.
4697 *
4698 * @see Notification#FLAG_AUTO_CANCEL
4699 */
4700 @NonNull
4701 public Builder setAutoCancel(boolean autoCancel) {
4702 setFlag(FLAG_AUTO_CANCEL, autoCancel);
4703 return this;
4704 }
4705
4706 /**
4707 * Set whether or not this notification should not bridge to other devices.
4708 *
4709 * <p>Some notifications can be bridged to other devices for remote display.
4710 * This hint can be set to recommend this notification not be bridged.
4711 */
4712 @NonNull
4713 public Builder setLocalOnly(boolean localOnly) {
4714 setFlag(FLAG_LOCAL_ONLY, localOnly);
4715 return this;
4716 }
4717
4718 /**
4719 * Set which notification properties will be inherited from system defaults.
4720 * <p>
4721 * The value should be one or more of the following fields combined with
4722 * bitwise-or:
4723 * {@link #DEFAULT_SOUND}, {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}.
4724 * <p>
4725 * For all default values, use {@link #DEFAULT_ALL}.
4726 *
4727 * @deprecated use {@link NotificationChannel#enableVibration(boolean)} and
4728 * {@link NotificationChannel#enableLights(boolean)} and
4729 * {@link NotificationChannel#setSound(Uri, AudioAttributes)} instead.
4730 */
4731 @Deprecated
4732 public Builder setDefaults(int defaults) {
4733 mN.defaults = defaults;
4734 return this;
4735 }
4736
4737 /**
4738 * Set the priority of this notification.
4739 *
4740 * @see Notification#priority
4741 * @deprecated use {@link NotificationChannel#setImportance(int)} instead.
4742 */
4743 @Deprecated
4744 public Builder setPriority(@Priority int pri) {
4745 mN.priority = pri;
4746 return this;
4747 }
4748
4749 /**
4750 * Set the notification category.
4751 *
4752 * @see Notification#category
4753 */
4754 @NonNull
4755 public Builder setCategory(String category) {
4756 mN.category = category;
4757 return this;
4758 }
4759
4760 /**
4761 * Add a person that is relevant to this notification.
4762 *
4763 * <P>
4764 * Depending on user preferences, this annotation may allow the notification to pass
4765 * through interruption filters, if this notification is of category {@link #CATEGORY_CALL}
4766 * or {@link #CATEGORY_MESSAGE}. The addition of people may also cause this notification to
4767 * appear more prominently in the user interface.
4768 * </P>
4769 *
4770 * <P>
4771 * The person should be specified by the {@code String} representation of a
4772 * {@link android.provider.ContactsContract.Contacts#CONTENT_LOOKUP_URI}.
4773 * </P>
4774 *
4775 * <P>The system will also attempt to resolve {@code mailto:} and {@code tel:} schema
4776 * URIs. The path part of these URIs must exist in the contacts database, in the
4777 * appropriate column, or the reference will be discarded as invalid. Telephone schema
4778 * URIs will be resolved by {@link android.provider.ContactsContract.PhoneLookup}.
4779 * It is also possible to provide a URI with the schema {@code name:} in order to uniquely
4780 * identify a person without an entry in the contacts database.
4781 * </P>
4782 *
4783 * @param uri A URI for the person.
4784 * @see Notification#EXTRA_PEOPLE
4785 * @deprecated use {@link #addPerson(Person)}
4786 */
4787 public Builder addPerson(String uri) {
4788 addPerson(new Person.Builder().setUri(uri).build());
4789 return this;
4790 }
4791
4792 /**
4793 * Add a person that is relevant to this notification.
4794 *
4795 * <P>
4796 * Depending on user preferences, this annotation may allow the notification to pass
4797 * through interruption filters, if this notification is of category {@link #CATEGORY_CALL}
4798 * or {@link #CATEGORY_MESSAGE}. The addition of people may also cause this notification to
4799 * appear more prominently in the user interface.
4800 * </P>
4801 *
4802 * <P>
4803 * A person should usually contain a uri in order to benefit from the ranking boost.
4804 * However, even if no uri is provided, it's beneficial to provide other people in the
4805 * notification, such that listeners and voice only devices can announce and handle them
4806 * properly.
4807 * </P>
4808 *
4809 * @param person the person to add.
4810 * @see Notification#EXTRA_PEOPLE_LIST
4811 */
4812 @NonNull
4813 public Builder addPerson(Person person) {
4814 mPersonList.add(person);
4815 return this;
4816 }
4817
4818 /**
4819 * Set this notification to be part of a group of notifications sharing the same key.
4820 * Grouped notifications may display in a cluster or stack on devices which
4821 * support such rendering.
4822 *
4823 * <p>To make this notification the summary for its group, also call
4824 * {@link #setGroupSummary}. A sort order can be specified for group members by using
4825 * {@link #setSortKey}.
4826 * @param groupKey The group key of the group.
4827 * @return this object for method chaining
4828 */
4829 @NonNull
4830 public Builder setGroup(String groupKey) {
4831 mN.mGroupKey = groupKey;
4832 return this;
4833 }
4834
4835 /**
4836 * Set this notification to be the group summary for a group of notifications.
4837 * Grouped notifications may display in a cluster or stack on devices which
4838 * support such rendering. If thereRequires a group key also be set using {@link #setGroup}.
4839 * The group summary may be suppressed if too few notifications are included in the group.
4840 * @param isGroupSummary Whether this notification should be a group summary.
4841 * @return this object for method chaining
4842 */
4843 @NonNull
4844 public Builder setGroupSummary(boolean isGroupSummary) {
4845 setFlag(FLAG_GROUP_SUMMARY, isGroupSummary);
4846 return this;
4847 }
4848
4849 /**
4850 * Set a sort key that orders this notification among other notifications from the
4851 * same package. This can be useful if an external sort was already applied and an app
4852 * would like to preserve this. Notifications will be sorted lexicographically using this
4853 * value, although providing different priorities in addition to providing sort key may
4854 * cause this value to be ignored.
4855 *
4856 * <p>This sort key can also be used to order members of a notification group. See
4857 * {@link #setGroup}.
4858 *
4859 * @see String#compareTo(String)
4860 */
4861 @NonNull
4862 public Builder setSortKey(String sortKey) {
4863 mN.mSortKey = sortKey;
4864 return this;
4865 }
4866
4867 /**
4868 * Merge additional metadata into this notification.
4869 *
4870 * <p>Values within the Bundle will replace existing extras values in this Builder.
4871 *
4872 * @see Notification#extras
4873 */
4874 @NonNull
4875 public Builder addExtras(Bundle extras) {
4876 if (extras != null) {
4877 mUserExtras.putAll(extras);
4878 }
4879 return this;
4880 }
4881
4882 /**
4883 * Set metadata for this notification.
4884 *
4885 * <p>A reference to the Bundle is held for the lifetime of this Builder, and the Bundle's
4886 * current contents are copied into the Notification each time {@link #build()} is
4887 * called.
4888 *
4889 * <p>Replaces any existing extras values with those from the provided Bundle.
4890 * Use {@link #addExtras} to merge in metadata instead.
4891 *
4892 * @see Notification#extras
4893 */
4894 @NonNull
4895 public Builder setExtras(Bundle extras) {
4896 if (extras != null) {
4897 mUserExtras = extras;
4898 }
4899 return this;
4900 }
4901
4902 /**
4903 * Get the current metadata Bundle used by this notification Builder.
4904 *
4905 * <p>The returned Bundle is shared with this Builder.
4906 *
4907 * <p>The current contents of this Bundle are copied into the Notification each time
4908 * {@link #build()} is called.
4909 *
4910 * @see Notification#extras
4911 */
4912 public Bundle getExtras() {
4913 return mUserExtras;
4914 }
4915
4916 private Bundle getAllExtras() {
4917 final Bundle saveExtras = (Bundle) mUserExtras.clone();
4918 saveExtras.putAll(mN.extras);
4919 return saveExtras;
4920 }
4921
4922 /**
4923 * Add an action to this notification. Actions are typically displayed by
4924 * the system as a button adjacent to the notification content.
4925 * <p>
4926 * Every action must have an icon (32dp square and matching the
4927 * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo
4928 * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}.
4929 * <p>
4930 * A notification in its expanded form can display up to 3 actions, from left to right in
4931 * the order they were added. Actions will not be displayed when the notification is
4932 * collapsed, however, so be sure that any essential functions may be accessed by the user
4933 * in some other way (for example, in the Activity pointed to by {@link #contentIntent}).
4934 * <p>
4935 * As of Android {@link android.os.Build.VERSION_CODES#S}, apps targeting API level
4936 * {@link android.os.Build.VERSION_CODES#S} or higher won't be able to start activities
4937 * while processing broadcast receivers or services in response to notification action
4938 * clicks. To launch an activity in those cases, provide a {@link PendingIntent} to the
4939 * activity itself.
4940 * <p>
4941 * As of Android {@link android.os.Build.VERSION_CODES#N},
4942 * action button icons will not be displayed on action buttons, but are still required
4943 * and are available to
4944 * {@link android.service.notification.NotificationListenerService notification listeners},
4945 * which may display them in other contexts, for example on a wearable device.
4946 *
4947 * @param icon Resource ID of a drawable that represents the action.
4948 * @param title Text describing the action.
4949 * @param intent PendingIntent to be fired when the action is invoked.
4950 *
4951 * @deprecated Use {@link #addAction(Action)} instead.
4952 */
4953 @Deprecated
4954 public Builder addAction(int icon, CharSequence title, PendingIntent intent) {
4955 mActions.add(new Action(icon, safeCharSequence(title), intent));
4956 return this;
4957 }
4958
4959 /**
4960 * Add an action to this notification. Actions are typically displayed by
4961 * the system as a button adjacent to the notification content.
4962 * <p>
4963 * Every action must have an icon (32dp square and matching the
4964 * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo
4965 * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}.
4966 * <p>
4967 * A notification in its expanded form can display up to 3 actions, from left to right in
4968 * the order they were added. Actions will not be displayed when the notification is
4969 * collapsed, however, so be sure that any essential functions may be accessed by the user
4970 * in some other way (for example, in the Activity pointed to by {@link #contentIntent}).
4971 *
4972 * @param action The action to add.
4973 */
4974 @NonNull
4975 public Builder addAction(Action action) {
4976 if (action != null) {
4977 mActions.add(action);
4978 }
4979 return this;
4980 }
4981
4982 /**
4983 * Alter the complete list of actions attached to this notification.
4984 * @see #addAction(Action).
4985 *
4986 * @param actions
4987 * @return
4988 */
4989 @NonNull
4990 public Builder setActions(Action... actions) {
4991 mActions.clear();
4992 for (int i = 0; i < actions.length; i++) {
4993 if (actions[i] != null) {
4994 mActions.add(actions[i]);
4995 }
4996 }
4997 return this;
4998 }
4999
5000 /**
5001 * Add a rich notification style to be applied at build time.
5002 *
5003 * @param style Object responsible for modifying the notification style.
5004 */
5005 @NonNull
5006 public Builder setStyle(Style style) {
5007 if (mStyle != style) {
5008 mStyle = style;
5009 if (mStyle != null) {
5010 mStyle.setBuilder(this);
5011 mN.extras.putString(EXTRA_TEMPLATE, style.getClass().getName());
5012 } else {
5013 mN.extras.remove(EXTRA_TEMPLATE);
5014 }
5015 }
5016 return this;
5017 }
5018
5019 /**
5020 * Returns the style set by {@link #setStyle(Style)}.
5021 */
5022 public Style getStyle() {
5023 return mStyle;
5024 }
5025
5026 /**
5027 * Specify the value of {@link #visibility}.
5028 *
5029 * @return The same Builder.
5030 */
5031 @NonNull
5032 public Builder setVisibility(@Visibility int visibility) {
5033 mN.visibility = visibility;
5034 return this;
5035 }
5036
5037 /**
5038 * Supply a replacement Notification whose contents should be shown in insecure contexts
5039 * (i.e. atop the secure lockscreen). See {@link #visibility} and {@link #VISIBILITY_PUBLIC}.
5040 * @param n A replacement notification, presumably with some or all info redacted.
5041 * @return The same Builder.
5042 */
5043 @NonNull
5044 public Builder setPublicVersion(Notification n) {
5045 if (n != null) {
5046 mN.publicVersion = new Notification();
5047 n.cloneInto(mN.publicVersion, /*heavy=*/ true);
5048 } else {
5049 mN.publicVersion = null;
5050 }
5051 return this;
5052 }
5053
5054 /**
5055 * Apply an extender to this notification builder. Extenders may be used to add
5056 * metadata or change options on this builder.
5057 */
5058 @NonNull
5059 public Builder extend(Extender extender) {
5060 extender.extend(this);
5061 return this;
5062 }
5063
5064 /**
5065 * Set the value for a notification flag
5066 *
5067 * @param mask Bit mask of the flag
5068 * @param value Status (on/off) of the flag
5069 *
5070 * @return The same Builder.
5071 */
5072 @NonNull
5073 public Builder setFlag(@NotificationFlags int mask, boolean value) {
5074 if (value) {
5075 mN.flags |= mask;
5076 } else {
5077 mN.flags &= ~mask;
5078 }
5079 return this;
5080 }
5081
5082 /**
5083 * Sets {@link Notification#color}.
5084 *
5085 * @param argb The accent color to use
5086 *
5087 * @return The same Builder.
5088 */
5089 @NonNull
5090 public Builder setColor(@ColorInt int argb) {
5091 mN.color = argb;
5092 sanitizeColor();
5093 return this;
5094 }
5095
5096 private void bindPhishingAlertIcon(RemoteViews contentView, StandardTemplateParams p) {
5097 contentView.setDrawableTint(
5098 R.id.phishing_alert,
5099 false /* targetBackground */,
5100 getColors(p).getErrorColor(),
5101 PorterDuff.Mode.SRC_ATOP);
5102 }
5103
5104 private Drawable getProfileBadgeDrawable() {
5105 if (mContext.getUserId() == UserHandle.USER_SYSTEM) {
5106 // This user can never be a badged profile,
5107 // and also includes USER_ALL system notifications.
5108 return null;
5109 }
5110 // Note: This assumes that the current user can read the profile badge of the
5111 // originating user.
5112 DevicePolicyManager dpm = mContext.getSystemService(DevicePolicyManager.class);
5113 return dpm.getResources().getDrawable(
5114 getUpdatableProfileBadgeId(), SOLID_COLORED, NOTIFICATION,
5115 this::getDefaultProfileBadgeDrawable);
5116 }
5117
5118 private String getUpdatableProfileBadgeId() {
5119 return mContext.getSystemService(UserManager.class).isManagedProfile()
5120 ? WORK_PROFILE_ICON : UNDEFINED;
5121 }
5122
5123 private Drawable getDefaultProfileBadgeDrawable() {
5124 return mContext.getPackageManager().getUserBadgeForDensityNoBackground(
5125 new UserHandle(mContext.getUserId()), 0);
5126 }
5127
5128 private Bitmap getProfileBadge() {
5129 Drawable badge = getProfileBadgeDrawable();
5130 if (badge == null) {
5131 return null;
5132 }
5133 final int size = mContext.getResources().getDimensionPixelSize(
5134 R.dimen.notification_badge_size);
5135 Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
5136 Canvas canvas = new Canvas(bitmap);
5137 badge.setBounds(0, 0, size, size);
5138 badge.draw(canvas);
5139 return bitmap;
5140 }
5141
5142 private void bindProfileBadge(RemoteViews contentView, StandardTemplateParams p) {
5143 Bitmap profileBadge = getProfileBadge();
5144
5145 if (profileBadge != null) {
5146 contentView.setImageViewBitmap(R.id.profile_badge, profileBadge);
5147 contentView.setViewVisibility(R.id.profile_badge, View.VISIBLE);
5148 if (isBackgroundColorized(p)) {
5149 contentView.setDrawableTint(R.id.profile_badge, false,
5150 getPrimaryTextColor(p), PorterDuff.Mode.SRC_ATOP);
5151 }
5152 }
5153 }
5154
5155 private void bindAlertedIcon(RemoteViews contentView, StandardTemplateParams p) {
5156 contentView.setDrawableTint(
5157 R.id.alerted_icon,
5158 false /* targetBackground */,
5159 getColors(p).getSecondaryTextColor(),
5160 PorterDuff.Mode.SRC_IN);
5161 }
5162
5163 /**
5164 * @hide
5165 */
5166 public boolean usesStandardHeader() {
5167 if (mN.mUsesStandardHeader) {
5168 return true;
5169 }
5170 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.N) {
5171 if (mN.contentView == null && mN.bigContentView == null) {
5172 return true;
5173 }
5174 }
5175 boolean contentViewUsesHeader = mN.contentView == null
5176 || STANDARD_LAYOUTS.contains(mN.contentView.getLayoutId());
5177 boolean bigContentViewUsesHeader = mN.bigContentView == null
5178 || STANDARD_LAYOUTS.contains(mN.bigContentView.getLayoutId());
5179 return contentViewUsesHeader && bigContentViewUsesHeader;
5180 }
5181
5182 private void resetStandardTemplate(RemoteViews contentView) {
5183 resetNotificationHeader(contentView);
5184 contentView.setViewVisibility(R.id.right_icon, View.GONE);
5185 contentView.setViewVisibility(R.id.title, View.GONE);
5186 contentView.setTextViewText(R.id.title, null);
5187 contentView.setViewVisibility(R.id.text, View.GONE);
5188 contentView.setTextViewText(R.id.text, null);
5189 }
5190
5191 /**
5192 * Resets the notification header to its original state
5193 */
5194 private void resetNotificationHeader(RemoteViews contentView) {
5195 // Small icon doesn't need to be reset, as it's always set. Resetting would prevent
5196 // re-using the drawable when the notification is updated.
5197 contentView.setBoolean(R.id.expand_button, "setExpanded", false);
5198 contentView.setViewVisibility(R.id.app_name_text, View.GONE);
5199 contentView.setTextViewText(R.id.app_name_text, null);
5200 contentView.setViewVisibility(R.id.chronometer, View.GONE);
5201 contentView.setViewVisibility(R.id.header_text, View.GONE);
5202 contentView.setTextViewText(R.id.header_text, null);
5203 contentView.setViewVisibility(R.id.header_text_secondary, View.GONE);
5204 contentView.setTextViewText(R.id.header_text_secondary, null);
5205 contentView.setViewVisibility(R.id.header_text_divider, View.GONE);
5206 contentView.setViewVisibility(R.id.header_text_secondary_divider, View.GONE);
5207 contentView.setViewVisibility(R.id.time_divider, View.GONE);
5208 contentView.setViewVisibility(R.id.time, View.GONE);
5209 contentView.setImageViewIcon(R.id.profile_badge, null);
5210 contentView.setViewVisibility(R.id.profile_badge, View.GONE);
5211 mN.mUsesStandardHeader = false;
5212 }
5213
5214 private RemoteViews applyStandardTemplate(int resId, StandardTemplateParams p,
5215 TemplateBindResult result) {
5216 p.headerless(resId == getBaseLayoutResource()
5217 || resId == getHeadsUpBaseLayoutResource()
5218 || resId == getMessagingLayoutResource()
5219 || resId == R.layout.notification_template_material_media);
5220 RemoteViews contentView = new BuilderRemoteViews(mContext.getApplicationInfo(), resId);
5221
5222 resetStandardTemplate(contentView);
5223
5224 final Bundle ex = mN.extras;
5225 updateBackgroundColor(contentView, p);
5226 bindNotificationHeader(contentView, p);
5227 bindLargeIconAndApplyMargin(contentView, p, result);
5228 boolean showProgress = handleProgressBar(contentView, ex, p);
5229 boolean hasSecondLine = showProgress;
5230 if (p.hasTitle()) {
5231 contentView.setViewVisibility(p.mTitleViewId, View.VISIBLE);
5232 contentView.setTextViewText(p.mTitleViewId, processTextSpans(p.title));
5233 setTextViewColorPrimary(contentView, p.mTitleViewId, p);
5234 } else if (p.mTitleViewId != R.id.title) {
5235 // This alternate title view ID is not cleared by resetStandardTemplate
5236 contentView.setViewVisibility(p.mTitleViewId, View.GONE);
5237 contentView.setTextViewText(p.mTitleViewId, null);
5238 }
5239 if (p.text != null && p.text.length() != 0
5240 && (!showProgress || p.mAllowTextWithProgress)) {
5241 contentView.setViewVisibility(p.mTextViewId, View.VISIBLE);
5242 contentView.setTextViewText(p.mTextViewId, processTextSpans(p.text));
5243 setTextViewColorSecondary(contentView, p.mTextViewId, p);
5244 hasSecondLine = true;
5245 } else if (p.mTextViewId != R.id.text) {
5246 // This alternate text view ID is not cleared by resetStandardTemplate
5247 contentView.setViewVisibility(p.mTextViewId, View.GONE);
5248 contentView.setTextViewText(p.mTextViewId, null);
5249 }
5250 setHeaderlessVerticalMargins(contentView, p, hasSecondLine);
5251
5252 return contentView;
5253 }
5254
5255 private static void setHeaderlessVerticalMargins(RemoteViews contentView,
5256 StandardTemplateParams p, boolean hasSecondLine) {
5257 if (!p.mHeaderless) {
5258 return;
5259 }
5260 int marginDimen = hasSecondLine
5261 ? R.dimen.notification_headerless_margin_twoline
5262 : R.dimen.notification_headerless_margin_oneline;
5263 contentView.setViewLayoutMarginDimen(R.id.notification_headerless_view_column,
5264 RemoteViews.MARGIN_TOP, marginDimen);
5265 contentView.setViewLayoutMarginDimen(R.id.notification_headerless_view_column,
5266 RemoteViews.MARGIN_BOTTOM, marginDimen);
5267 }
5268
5269 private CharSequence processTextSpans(CharSequence text) {
5270 if (mInNightMode) {
5271 return ContrastColorUtil.clearColorSpans(text);
5272 }
5273 return text;
5274 }
5275
5276 private void setTextViewColorPrimary(RemoteViews contentView, @IdRes int id,
5277 StandardTemplateParams p) {
5278 contentView.setTextColor(id, getPrimaryTextColor(p));
5279 }
5280
5281 /**
5282 * @param p the template params to inflate this with
5283 * @return the primary text color
5284 * @hide
5285 */
5286 @VisibleForTesting
5287 public @ColorInt int getPrimaryTextColor(StandardTemplateParams p) {
5288 return getColors(p).getPrimaryTextColor();
5289 }
5290
5291 /**
5292 * @param p the template params to inflate this with
5293 * @return the secondary text color
5294 * @hide
5295 */
5296 @VisibleForTesting
5297 public @ColorInt int getSecondaryTextColor(StandardTemplateParams p) {
5298 return getColors(p).getSecondaryTextColor();
5299 }
5300
5301 private void setTextViewColorSecondary(RemoteViews contentView, @IdRes int id,
5302 StandardTemplateParams p) {
5303 contentView.setTextColor(id, getSecondaryTextColor(p));
5304 }
5305
5306 private Colors getColors(StandardTemplateParams p) {
5307 mColors.resolvePalette(mContext, mN.color, isBackgroundColorized(p), mInNightMode);
5308 return mColors;
5309 }
5310
5311 private void updateBackgroundColor(RemoteViews contentView,
5312 StandardTemplateParams p) {
5313 if (isBackgroundColorized(p)) {
5314 contentView.setInt(R.id.status_bar_latest_event_content, "setBackgroundColor",
5315 getBackgroundColor(p));
5316 } else {
5317 // Clear it!
5318 contentView.setInt(R.id.status_bar_latest_event_content, "setBackgroundResource",
5319 0);
5320 }
5321 }
5322
5323 private boolean handleProgressBar(RemoteViews contentView, Bundle ex,
5324 StandardTemplateParams p) {
5325 final int max = ex.getInt(EXTRA_PROGRESS_MAX, 0);
5326 final int progress = ex.getInt(EXTRA_PROGRESS, 0);
5327 final boolean ind = ex.getBoolean(EXTRA_PROGRESS_INDETERMINATE);
5328 if (!p.mHideProgress && (max != 0 || ind)) {
5329 contentView.setViewVisibility(com.android.internal.R.id.progress, View.VISIBLE);
5330 contentView.setProgressBar(R.id.progress, max, progress, ind);
5331 contentView.setProgressBackgroundTintList(R.id.progress,
5332 mContext.getColorStateList(R.color.notification_progress_background_color));
5333 ColorStateList progressTint = ColorStateList.valueOf(getPrimaryAccentColor(p));
5334 contentView.setProgressTintList(R.id.progress, progressTint);
5335 contentView.setProgressIndeterminateTintList(R.id.progress, progressTint);
5336 return true;
5337 } else {
5338 contentView.setViewVisibility(R.id.progress, View.GONE);
5339 return false;
5340 }
5341 }
5342
5343 private void bindLargeIconAndApplyMargin(RemoteViews contentView,
5344 @NonNull StandardTemplateParams p,
5345 @Nullable TemplateBindResult result) {
5346 if (result == null) {
5347 result = new TemplateBindResult();
5348 }
5349 bindLargeIcon(contentView, p, result);
5350 if (!p.mHeaderless) {
5351 // views in states with a header (big states)
5352 result.mHeadingExtraMarginSet.applyToView(contentView, R.id.notification_header);
5353 result.mTitleMarginSet.applyToView(contentView, R.id.title);
5354 // If there is no title, the text (or big_text) needs to wrap around the image
5355 result.mTitleMarginSet.applyToView(contentView, p.mTextViewId);
5356 contentView.setInt(p.mTextViewId, "setNumIndentLines", p.hasTitle() ? 0 : 1);
5357 }
5358 }
5359
5360 // This code is executed on behalf of other apps' notifications, sometimes even by 3p apps,
5361 // a use case that is not supported by the Compat Framework library. Workarounds to resolve
5362 // the change's state in NotificationManagerService were very complex. These behavior
5363 // changes are entirely visual, and should otherwise be undetectable by apps.
5364 @SuppressWarnings("AndroidFrameworkCompatChange")
5365 private void calculateRightIconDimens(Icon rightIcon, boolean isPromotedPicture,
5366 @NonNull TemplateBindResult result) {
5367 final Resources resources = mContext.getResources();
5368 final float density = resources.getDisplayMetrics().density;
5369 final float iconMarginDp = resources.getDimension(
5370 R.dimen.notification_right_icon_content_margin) / density;
5371 final float contentMarginDp = resources.getDimension(
5372 R.dimen.notification_content_margin_end) / density;
5373 final float expanderSizeDp = resources.getDimension(
5374 R.dimen.notification_header_expand_icon_size) / density - contentMarginDp;
5375 final float viewHeightDp = resources.getDimension(
5376 R.dimen.notification_right_icon_size) / density;
5377 float viewWidthDp = viewHeightDp; // icons are 1:1 by default
5378 if (rightIcon != null && (isPromotedPicture
5379 || mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.S)) {
5380 Drawable drawable = rightIcon.loadDrawable(mContext);
5381 if (drawable != null) {
5382 int iconWidth = drawable.getIntrinsicWidth();
5383 int iconHeight = drawable.getIntrinsicHeight();
5384 if (iconWidth > iconHeight && iconHeight > 0) {
5385 final float maxViewWidthDp = viewHeightDp * MAX_LARGE_ICON_ASPECT_RATIO;
5386 viewWidthDp = Math.min(viewHeightDp * iconWidth / iconHeight,
5387 maxViewWidthDp);
5388 }
5389 }
5390 }
5391 final float extraMarginEndDpIfVisible = viewWidthDp + iconMarginDp;
5392 result.setRightIconState(rightIcon != null /* visible */, viewWidthDp,
5393 viewHeightDp, extraMarginEndDpIfVisible, expanderSizeDp);
5394 }
5395
5396 /**
5397 * Bind the large icon.
5398 */
5399 private void bindLargeIcon(RemoteViews contentView, @NonNull StandardTemplateParams p,
5400 @NonNull TemplateBindResult result) {
5401 if (mN.mLargeIcon == null && mN.largeIcon != null) {
5402 mN.mLargeIcon = Icon.createWithBitmap(mN.largeIcon);
5403 }
5404
5405 // Determine the left and right icons
5406 Icon leftIcon = p.mHideLeftIcon ? null : mN.mLargeIcon;
5407 Icon rightIcon = p.mHideRightIcon ? null
5408 : (p.mPromotedPicture != null ? p.mPromotedPicture : mN.mLargeIcon);
5409
5410 // Apply the left icon (without duplicating the bitmap)
5411 if (leftIcon != rightIcon || leftIcon == null) {
5412 // If the leftIcon is explicitly hidden or different from the rightIcon, then set it
5413 // explicitly and make sure it won't take the right_icon drawable.
5414 contentView.setImageViewIcon(R.id.left_icon, leftIcon);
5415 contentView.setIntTag(R.id.left_icon, R.id.tag_uses_right_icon_drawable, 0);
5416 } else {
5417 // If the leftIcon equals the rightIcon, just set the flag to use the right_icon
5418 // drawable. This avoids the view having two copies of the same bitmap.
5419 contentView.setIntTag(R.id.left_icon, R.id.tag_uses_right_icon_drawable, 1);
5420 }
5421
5422 // Always calculate dimens to populate `result` for the GONE case
5423 boolean isPromotedPicture = p.mPromotedPicture != null;
5424 calculateRightIconDimens(rightIcon, isPromotedPicture, result);
5425
5426 // Bind the right icon
5427 if (rightIcon != null) {
5428 contentView.setViewLayoutWidth(R.id.right_icon,
5429 result.mRightIconWidthDp, TypedValue.COMPLEX_UNIT_DIP);
5430 contentView.setViewLayoutHeight(R.id.right_icon,
5431 result.mRightIconHeightDp, TypedValue.COMPLEX_UNIT_DIP);
5432 contentView.setViewVisibility(R.id.right_icon, View.VISIBLE);
5433 contentView.setImageViewIcon(R.id.right_icon, rightIcon);
5434 contentView.setIntTag(R.id.right_icon, R.id.tag_keep_when_showing_left_icon,
5435 isPromotedPicture ? 1 : 0);
5436 processLargeLegacyIcon(rightIcon, contentView, p);
5437 } else {
5438 // The "reset" doesn't clear the drawable, so we do it here. This clear is
5439 // important because the presence of a drawable in this view (regardless of the
5440 // visibility) is used by NotificationGroupingUtil to set the visibility.
5441 contentView.setImageViewIcon(R.id.right_icon, null);
5442 contentView.setIntTag(R.id.right_icon, R.id.tag_keep_when_showing_left_icon, 0);
5443 }
5444 }
5445
5446 private void bindNotificationHeader(RemoteViews contentView, StandardTemplateParams p) {
5447 bindSmallIcon(contentView, p);
5448 // Populate text left-to-right so that separators are only shown between strings
5449 boolean hasTextToLeft = bindHeaderAppName(contentView, p, false /* force */);
5450 hasTextToLeft |= bindHeaderTextSecondary(contentView, p, hasTextToLeft);
5451 hasTextToLeft |= bindHeaderText(contentView, p, hasTextToLeft);
5452 if (!hasTextToLeft) {
5453 // If there's still no text, force add the app name so there is some text.
5454 hasTextToLeft |= bindHeaderAppName(contentView, p, true /* force */);
5455 }
5456 bindHeaderChronometerAndTime(contentView, p, hasTextToLeft);
5457 bindPhishingAlertIcon(contentView, p);
5458 bindProfileBadge(contentView, p);
5459 bindAlertedIcon(contentView, p);
5460 bindExpandButton(contentView, p);
5461 mN.mUsesStandardHeader = true;
5462 }
5463
5464 private void bindExpandButton(RemoteViews contentView, StandardTemplateParams p) {
5465 // set default colors
5466 int bgColor = getBackgroundColor(p);
5467 int pillColor = Colors.flattenAlpha(getColors(p).getProtectionColor(), bgColor);
5468 int textColor = Colors.flattenAlpha(getPrimaryTextColor(p), pillColor);
5469 contentView.setInt(R.id.expand_button, "setDefaultTextColor", textColor);
5470 contentView.setInt(R.id.expand_button, "setDefaultPillColor", pillColor);
5471 // Use different highlighted colors for conversations' unread count
5472 if (p.mHighlightExpander) {
5473 pillColor = Colors.flattenAlpha(getColors(p).getTertiaryAccentColor(), bgColor);
5474 textColor = Colors.flattenAlpha(getColors(p).getOnAccentTextColor(), pillColor);
5475 }
5476 contentView.setInt(R.id.expand_button, "setHighlightTextColor", textColor);
5477 contentView.setInt(R.id.expand_button, "setHighlightPillColor", pillColor);
5478 }
5479
5480 private void bindHeaderChronometerAndTime(RemoteViews contentView,
5481 StandardTemplateParams p, boolean hasTextToLeft) {
5482 if (!p.mHideTime && showsTimeOrChronometer()) {
5483 if (hasTextToLeft) {
5484 contentView.setViewVisibility(R.id.time_divider, View.VISIBLE);
5485 setTextViewColorSecondary(contentView, R.id.time_divider, p);
5486 }
5487 if (mN.extras.getBoolean(EXTRA_SHOW_CHRONOMETER)) {
5488 contentView.setViewVisibility(R.id.chronometer, View.VISIBLE);
5489 contentView.setLong(R.id.chronometer, "setBase",
5490 mN.when + (SystemClock.elapsedRealtime() - System.currentTimeMillis()));
5491 contentView.setBoolean(R.id.chronometer, "setStarted", true);
5492 boolean countsDown = mN.extras.getBoolean(EXTRA_CHRONOMETER_COUNT_DOWN);
5493 contentView.setChronometerCountDown(R.id.chronometer, countsDown);
5494 setTextViewColorSecondary(contentView, R.id.chronometer, p);
5495 } else {
5496 contentView.setViewVisibility(R.id.time, View.VISIBLE);
5497 contentView.setLong(R.id.time, "setTime", mN.when);
5498 setTextViewColorSecondary(contentView, R.id.time, p);
5499 }
5500 } else {
5501 // We still want a time to be set but gone, such that we can show and hide it
5502 // on demand in case it's a child notification without anything in the header
5503 contentView.setLong(R.id.time, "setTime", mN.when != 0 ? mN.when : mN.creationTime);
5504 setTextViewColorSecondary(contentView, R.id.time, p);
5505 }
5506 }
5507
5508 /**
5509 * @return true if the header text will be visible
5510 */
5511 private boolean bindHeaderText(RemoteViews contentView, StandardTemplateParams p,
5512 boolean hasTextToLeft) {
5513 if (p.mHideSubText) {
5514 return false;
5515 }
5516 CharSequence summaryText = p.summaryText;
5517 if (summaryText == null && mStyle != null && mStyle.mSummaryTextSet
5518 && mStyle.hasSummaryInHeader()) {
5519 summaryText = mStyle.mSummaryText;
5520 }
5521 if (summaryText == null
5522 && mContext.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N
5523 && mN.extras.getCharSequence(EXTRA_INFO_TEXT) != null) {
5524 summaryText = mN.extras.getCharSequence(EXTRA_INFO_TEXT);
5525 }
5526 if (!TextUtils.isEmpty(summaryText)) {
5527 // TODO: Remove the span entirely to only have the string with propper formating.
5528 contentView.setTextViewText(R.id.header_text, processTextSpans(
5529 processLegacyText(summaryText)));
5530 setTextViewColorSecondary(contentView, R.id.header_text, p);
5531 contentView.setViewVisibility(R.id.header_text, View.VISIBLE);
5532 if (hasTextToLeft) {
5533 contentView.setViewVisibility(R.id.header_text_divider, View.VISIBLE);
5534 setTextViewColorSecondary(contentView, R.id.header_text_divider, p);
5535 }
5536 return true;
5537 }
5538 return false;
5539 }
5540
5541 /**
5542 * @return true if the secondary header text will be visible
5543 */
5544 private boolean bindHeaderTextSecondary(RemoteViews contentView, StandardTemplateParams p,
5545 boolean hasTextToLeft) {
5546 if (p.mHideSubText) {
5547 return false;
5548 }
5549 if (!TextUtils.isEmpty(p.headerTextSecondary)) {
5550 contentView.setTextViewText(R.id.header_text_secondary, processTextSpans(
5551 processLegacyText(p.headerTextSecondary)));
5552 setTextViewColorSecondary(contentView, R.id.header_text_secondary, p);
5553 contentView.setViewVisibility(R.id.header_text_secondary, View.VISIBLE);
5554 if (hasTextToLeft) {
5555 contentView.setViewVisibility(R.id.header_text_secondary_divider, View.VISIBLE);
5556 setTextViewColorSecondary(contentView, R.id.header_text_secondary_divider, p);
5557 }
5558 return true;
5559 }
5560 return false;
5561 }
5562
5563 /**
5564 * @hide
5565 */
5566 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
5567 public String loadHeaderAppName() {
5568 CharSequence name = null;
5569 final PackageManager pm = mContext.getPackageManager();
5570 if (mN.extras.containsKey(EXTRA_SUBSTITUTE_APP_NAME)) {
5571 // only system packages which lump together a bunch of unrelated stuff
5572 // may substitute a different name to make the purpose of the
5573 // notification more clear. the correct package label should always
5574 // be accessible via SystemUI.
5575 final String pkg = mContext.getPackageName();
5576 final String subName = mN.extras.getString(EXTRA_SUBSTITUTE_APP_NAME);
5577 if (PackageManager.PERMISSION_GRANTED == pm.checkPermission(
5578 android.Manifest.permission.SUBSTITUTE_NOTIFICATION_APP_NAME, pkg)) {
5579 name = subName;
5580 } else {
5581 Log.w(TAG, "warning: pkg "
5582 + pkg + " attempting to substitute app name '" + subName
5583 + "' without holding perm "
5584 + android.Manifest.permission.SUBSTITUTE_NOTIFICATION_APP_NAME);
5585 }
5586 }
5587 if (TextUtils.isEmpty(name)) {
5588 name = pm.getApplicationLabel(mContext.getApplicationInfo());
5589 }
5590 if (TextUtils.isEmpty(name)) {
5591 // still nothing?
5592 return null;
5593 }
5594
5595 return String.valueOf(name);
5596 }
5597
5598 /**
5599 * @return true if the app name will be visible
5600 */
5601 private boolean bindHeaderAppName(RemoteViews contentView, StandardTemplateParams p,
5602 boolean force) {
5603 if (p.mViewType == StandardTemplateParams.VIEW_TYPE_MINIMIZED && !force) {
5604 // unless the force flag is set, don't show the app name in the minimized state.
5605 return false;
5606 }
5607 if (p.mHeaderless && p.hasTitle()) {
5608 // the headerless template will have the TITLE in this position; return true to
5609 // keep the divider visible between that title and the next text element.
5610 return true;
5611 }
5612 if (p.mHideAppName) {
5613 // The app name is being hidden, so we definitely want to return here.
5614 // Assume that there is a title which will replace it in the header.
5615 return p.hasTitle();
5616 }
5617 contentView.setViewVisibility(R.id.app_name_text, View.VISIBLE);
5618 contentView.setTextViewText(R.id.app_name_text, loadHeaderAppName());
5619 contentView.setTextColor(R.id.app_name_text, getSecondaryTextColor(p));
5620 return true;
5621 }
5622
5623 /**
5624 * Determines if the notification should be colorized *for the purposes of applying colors*.
5625 * If this is the minimized view of a colorized notification, this will return false so that
5626 * internal coloring logic can still render the notification normally.
5627 */
5628 private boolean isBackgroundColorized(StandardTemplateParams p) {
5629 return p.allowColorization && mN.isColorized();
5630 }
5631
5632 private boolean isCallActionColorCustomizable() {
5633 // NOTE: this doesn't need to check StandardTemplateParams.allowColorization because
5634 // that is only used for disallowing colorization of headers for the minimized state,
5635 // and neither of those conditions applies when showing actions.
5636 // Not requiring StandardTemplateParams as an argument simplifies the creation process.
5637 return mN.isColorized() && mContext.getResources().getBoolean(
5638 R.bool.config_callNotificationActionColorsRequireColorized);
5639 }
5640
5641 private void bindSmallIcon(RemoteViews contentView, StandardTemplateParams p) {
5642 if (mN.mSmallIcon == null && mN.icon != 0) {
5643 mN.mSmallIcon = Icon.createWithResource(mContext, mN.icon);
5644 }
5645 contentView.setImageViewIcon(R.id.icon, mN.mSmallIcon);
5646 contentView.setInt(R.id.icon, "setImageLevel", mN.iconLevel);
5647 processSmallIconColor(mN.mSmallIcon, contentView, p);
5648 }
5649
5650 /**
5651 * @return true if the built notification will show the time or the chronometer; false
5652 * otherwise
5653 */
5654 private boolean showsTimeOrChronometer() {
5655 return mN.showsTime() || mN.showsChronometer();
5656 }
5657
5658 private void resetStandardTemplateWithActions(RemoteViews big) {
5659 // actions_container is only reset when there are no actions to avoid focus issues with
5660 // remote inputs.
5661 big.setViewVisibility(R.id.actions, View.GONE);
5662 big.removeAllViews(R.id.actions);
5663
5664 big.setViewVisibility(R.id.notification_material_reply_container, View.GONE);
5665 big.setTextViewText(R.id.notification_material_reply_text_1, null);
5666 big.setViewVisibility(R.id.notification_material_reply_text_1_container, View.GONE);
5667 big.setViewVisibility(R.id.notification_material_reply_progress, View.GONE);
5668
5669 big.setViewVisibility(R.id.notification_material_reply_text_2, View.GONE);
5670 big.setTextViewText(R.id.notification_material_reply_text_2, null);
5671 big.setViewVisibility(R.id.notification_material_reply_text_3, View.GONE);
5672 big.setTextViewText(R.id.notification_material_reply_text_3, null);
5673
5674 // This may get erased by bindSnoozeAction
5675 big.setViewLayoutMarginDimen(R.id.notification_action_list_margin_target,
5676 RemoteViews.MARGIN_BOTTOM, R.dimen.notification_content_margin);
5677 }
5678
5679 private void bindSnoozeAction(RemoteViews big, StandardTemplateParams p) {
5680 boolean hideSnoozeButton = mN.isForegroundService() || mN.fullScreenIntent != null
5681 || isBackgroundColorized(p)
5682 || p.mViewType != StandardTemplateParams.VIEW_TYPE_BIG;
5683 big.setBoolean(R.id.snooze_button, "setEnabled", !hideSnoozeButton);
5684 if (hideSnoozeButton) {
5685 // Only hide; NotificationContentView will show it when it adds the click listener
5686 big.setViewVisibility(R.id.snooze_button, View.GONE);
5687 }
5688
5689 final boolean snoozeEnabled = !hideSnoozeButton
5690 && mContext.getContentResolver() != null
5691 && isSnoozeSettingEnabled();
5692 if (snoozeEnabled) {
5693 big.setViewLayoutMarginDimen(R.id.notification_action_list_margin_target,
5694 RemoteViews.MARGIN_BOTTOM, 0);
5695 }
5696 }
5697
5698 private boolean isSnoozeSettingEnabled() {
5699 try {
5700 return Settings.Secure.getInt(mContext.getContentResolver(),
5701 Settings.Secure.SHOW_NOTIFICATION_SNOOZE, 0) == 1;
5702 } catch (SecurityException ex) {
5703 // Most 3p apps can't access this snooze setting, so their NotificationListeners
5704 // would be unable to create notification views if we propagated this exception.
5705 return false;
5706 }
5707 }
5708
5709 /**
5710 * Returns the actions that are not contextual.
5711 */
5712 private @NonNull List<Notification.Action> getNonContextualActions() {
5713 if (mActions == null) return Collections.emptyList();
5714 List<Notification.Action> standardActions = new ArrayList<>();
5715 for (Notification.Action action : mActions) {
5716 if (!action.isContextual()) {
5717 standardActions.add(action);
5718 }
5719 }
5720 return standardActions;
5721 }
5722
5723 private RemoteViews applyStandardTemplateWithActions(int layoutId,
5724 StandardTemplateParams p, TemplateBindResult result) {
5725 RemoteViews big = applyStandardTemplate(layoutId, p, result);
5726
5727 resetStandardTemplateWithActions(big);
5728 bindSnoozeAction(big, p);
5729 // color the snooze and bubble actions with the theme color
5730 ColorStateList actionColor = ColorStateList.valueOf(getStandardActionColor(p));
5731 big.setColorStateList(R.id.snooze_button, "setImageTintList", actionColor);
5732 big.setColorStateList(R.id.bubble_button, "setImageTintList", actionColor);
5733
5734 boolean validRemoteInput = false;
5735
5736 // In the UI, contextual actions appear separately from the standard actions, so we
5737 // filter them out here.
5738 List<Notification.Action> nonContextualActions = getNonContextualActions();
5739
5740 int numActions = Math.min(nonContextualActions.size(), MAX_ACTION_BUTTONS);
5741 boolean emphazisedMode = mN.fullScreenIntent != null || p.mCallStyleActions;
5742 if (p.mCallStyleActions) {
5743 // Clear view padding to allow buttons to start on the left edge.
5744 // This must be done before 'setEmphasizedMode' which sets top/bottom margins.
5745 big.setViewPadding(R.id.actions, 0, 0, 0, 0);
5746 // Add an optional indent that will make buttons start at the correct column when
5747 // there is enough space to do so (and fall back to the left edge if not).
5748 big.setInt(R.id.actions, "setCollapsibleIndentDimen",
5749 R.dimen.call_notification_collapsible_indent);
5750 }
5751 big.setBoolean(R.id.actions, "setEmphasizedMode", emphazisedMode);
5752 if (numActions > 0 && !p.mHideActions) {
5753 big.setViewVisibility(R.id.actions_container, View.VISIBLE);
5754 big.setViewVisibility(R.id.actions, View.VISIBLE);
5755 big.setViewLayoutMarginDimen(R.id.notification_action_list_margin_target,
5756 RemoteViews.MARGIN_BOTTOM, 0);
5757 for (int i = 0; i < numActions; i++) {
5758 Action action = nonContextualActions.get(i);
5759
5760 boolean actionHasValidInput = hasValidRemoteInput(action);
5761 validRemoteInput |= actionHasValidInput;
5762
5763 final RemoteViews button = generateActionButton(action, emphazisedMode, p);
5764 if (actionHasValidInput && !emphazisedMode) {
5765 // Clear the drawable
5766 button.setInt(R.id.action0, "setBackgroundResource", 0);
5767 }
5768 if (emphazisedMode && i > 0) {
5769 // Clear start margin from non-first buttons to reduce the gap between them.
5770 // (8dp remaining gap is from all buttons' standard 4dp inset).
5771 button.setViewLayoutMarginDimen(R.id.action0, RemoteViews.MARGIN_START, 0);
5772 }
5773 big.addView(R.id.actions, button);
5774 }
5775 } else {
5776 big.setViewVisibility(R.id.actions_container, View.GONE);
5777 }
5778
5779 RemoteInputHistoryItem[] replyText = getParcelableArrayFromBundle(
5780 mN.extras, EXTRA_REMOTE_INPUT_HISTORY_ITEMS, RemoteInputHistoryItem.class);
5781 if (validRemoteInput && replyText != null && replyText.length > 0
5782 && !TextUtils.isEmpty(replyText[0].getText())
5783 && p.maxRemoteInputHistory > 0) {
5784 boolean showSpinner = mN.extras.getBoolean(EXTRA_SHOW_REMOTE_INPUT_SPINNER);
5785 big.setViewVisibility(R.id.notification_material_reply_container, View.VISIBLE);
5786 big.setViewVisibility(R.id.notification_material_reply_text_1_container,
5787 View.VISIBLE);
5788 big.setTextViewText(R.id.notification_material_reply_text_1,
5789 processTextSpans(replyText[0].getText()));
5790 setTextViewColorSecondary(big, R.id.notification_material_reply_text_1, p);
5791 big.setViewVisibility(R.id.notification_material_reply_progress,
5792 showSpinner ? View.VISIBLE : View.GONE);
5793 big.setProgressIndeterminateTintList(
5794 R.id.notification_material_reply_progress,
5795 ColorStateList.valueOf(getPrimaryAccentColor(p)));
5796
5797 if (replyText.length > 1 && !TextUtils.isEmpty(replyText[1].getText())
5798 && p.maxRemoteInputHistory > 1) {
5799 big.setViewVisibility(R.id.notification_material_reply_text_2, View.VISIBLE);
5800 big.setTextViewText(R.id.notification_material_reply_text_2,
5801 processTextSpans(replyText[1].getText()));
5802 setTextViewColorSecondary(big, R.id.notification_material_reply_text_2, p);
5803
5804 if (replyText.length > 2 && !TextUtils.isEmpty(replyText[2].getText())
5805 && p.maxRemoteInputHistory > 2) {
5806 big.setViewVisibility(
5807 R.id.notification_material_reply_text_3, View.VISIBLE);
5808 big.setTextViewText(R.id.notification_material_reply_text_3,
5809 processTextSpans(replyText[2].getText()));
5810 setTextViewColorSecondary(big, R.id.notification_material_reply_text_3, p);
5811 }
5812 }
5813 }
5814
5815 return big;
5816 }
5817
5818 private boolean hasValidRemoteInput(Action action) {
5819 if (TextUtils.isEmpty(action.title) || action.actionIntent == null) {
5820 // Weird actions
5821 return false;
5822 }
5823
5824 RemoteInput[] remoteInputs = action.getRemoteInputs();
5825 if (remoteInputs == null) {
5826 return false;
5827 }
5828
5829 for (RemoteInput r : remoteInputs) {
5830 CharSequence[] choices = r.getChoices();
5831 if (r.getAllowFreeFormInput() || (choices != null && choices.length != 0)) {
5832 return true;
5833 }
5834 }
5835 return false;
5836 }
5837
5838 /**
5839 * Construct a RemoteViews for the final 1U notification layout. In order:
5840 * 1. Custom contentView from the caller
5841 * 2. Style's proposed content view
5842 * 3. Standard template view
5843 */
5844 public RemoteViews createContentView() {
5845 return createContentView(false /* increasedheight */ );
5846 }
5847
5848 // This code is executed on behalf of other apps' notifications, sometimes even by 3p apps,
5849 // a use case that is not supported by the Compat Framework library. Workarounds to resolve
5850 // the change's state in NotificationManagerService were very complex. While it's possible
5851 // apps can detect the change, it's most likely that the changes will simply result in
5852 // visual regressions.
5853 @SuppressWarnings("AndroidFrameworkCompatChange")
5854 private boolean fullyCustomViewRequiresDecoration(boolean fromStyle) {
5855 // Custom views which come from a platform style class are safe, and thus do not need to
5856 // be wrapped. Any subclass of those styles has the opportunity to make arbitrary
5857 // changes to the RemoteViews, and thus can't be trusted as a fully vetted view.
5858 if (fromStyle && PLATFORM_STYLE_CLASSES.contains(mStyle.getClass())) {
5859 return false;
5860 }
5861 return mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.S;
5862 }
5863
5864 private RemoteViews minimallyDecoratedContentView(@NonNull RemoteViews customContent) {
5865 StandardTemplateParams p = mParams.reset()
5866 .viewType(StandardTemplateParams.VIEW_TYPE_NORMAL)
5867 .decorationType(StandardTemplateParams.DECORATION_MINIMAL)
5868 .fillTextsFrom(this);
5869 TemplateBindResult result = new TemplateBindResult();
5870 RemoteViews standard = applyStandardTemplate(getBaseLayoutResource(), p, result);
5871 buildCustomContentIntoTemplate(mContext, standard, customContent,
5872 p, result);
5873 return standard;
5874 }
5875
5876 private RemoteViews minimallyDecoratedBigContentView(@NonNull RemoteViews customContent) {
5877 StandardTemplateParams p = mParams.reset()
5878 .viewType(StandardTemplateParams.VIEW_TYPE_BIG)
5879 .decorationType(StandardTemplateParams.DECORATION_MINIMAL)
5880 .fillTextsFrom(this);
5881 TemplateBindResult result = new TemplateBindResult();
5882 RemoteViews standard = applyStandardTemplateWithActions(getBigBaseLayoutResource(),
5883 p, result);
5884 buildCustomContentIntoTemplate(mContext, standard, customContent,
5885 p, result);
5886 makeHeaderExpanded(standard);
5887 return standard;
5888 }
5889
5890 private RemoteViews minimallyDecoratedHeadsUpContentView(
5891 @NonNull RemoteViews customContent) {
5892 StandardTemplateParams p = mParams.reset()
5893 .viewType(StandardTemplateParams.VIEW_TYPE_HEADS_UP)
5894 .decorationType(StandardTemplateParams.DECORATION_MINIMAL)
5895 .fillTextsFrom(this);
5896 TemplateBindResult result = new TemplateBindResult();
5897 RemoteViews standard = applyStandardTemplateWithActions(getHeadsUpBaseLayoutResource(),
5898 p, result);
5899 buildCustomContentIntoTemplate(mContext, standard, customContent,
5900 p, result);
5901 return standard;
5902 }
5903
5904 /**
5905 * Construct a RemoteViews for the smaller content view.
5906 *
5907 * @param increasedHeight true if this layout be created with an increased height. Some
5908 * styles may support showing more then just that basic 1U size
5909 * and the system may decide to render important notifications
5910 * slightly bigger even when collapsed.
5911 *
5912 * @hide
5913 */
5914 public RemoteViews createContentView(boolean increasedHeight) {
5915 if (useExistingRemoteView(mN.contentView)) {
5916 return fullyCustomViewRequiresDecoration(false /* fromStyle */)
5917 ? minimallyDecoratedContentView(mN.contentView) : mN.contentView;
5918 } else if (mStyle != null) {
5919 final RemoteViews styleView = mStyle.makeContentView(increasedHeight);
5920 if (styleView != null) {
5921 return fullyCustomViewRequiresDecoration(true /* fromStyle */)
5922 ? minimallyDecoratedContentView(styleView) : styleView;
5923 }
5924 }
5925 StandardTemplateParams p = mParams.reset()
5926 .viewType(StandardTemplateParams.VIEW_TYPE_NORMAL)
5927 .fillTextsFrom(this);
5928 return applyStandardTemplate(getBaseLayoutResource(), p, null /* result */);
5929 }
5930
5931 private boolean useExistingRemoteView(RemoteViews customContent) {
5932 if (customContent == null) {
5933 return false;
5934 }
5935 if (styleDisplaysCustomViewInline()) {
5936 // the provided custom view is intended to be wrapped by the style.
5937 return false;
5938 }
5939 if (fullyCustomViewRequiresDecoration(false)
5940 && STANDARD_LAYOUTS.contains(customContent.getLayoutId())) {
5941 // If the app's custom views are objects returned from Builder.create*ContentView()
5942 // then the app is most likely attempting to spoof the user. Even if they are not,
5943 // the result would be broken (b/189189308) so we will ignore it.
5944 Log.w(TAG, "For apps targeting S, a custom content view that is a modified "
5945 + "version of any standard layout is disallowed.");
5946 return false;
5947 }
5948 return true;
5949 }
5950
5951 /**
5952 * Construct a RemoteViews for the final big notification layout.
5953 */
5954 public RemoteViews createBigContentView() {
5955 RemoteViews result = null;
5956 if (useExistingRemoteView(mN.bigContentView)) {
5957 return fullyCustomViewRequiresDecoration(false /* fromStyle */)
5958 ? minimallyDecoratedBigContentView(mN.bigContentView) : mN.bigContentView;
5959 }
5960 if (mStyle != null) {
5961 result = mStyle.makeBigContentView();
5962 if (fullyCustomViewRequiresDecoration(true /* fromStyle */)) {
5963 result = minimallyDecoratedBigContentView(result);
5964 }
5965 }
5966 if (result == null) {
5967 if (bigContentViewRequired()) {
5968 StandardTemplateParams p = mParams.reset()
5969 .viewType(StandardTemplateParams.VIEW_TYPE_BIG)
5970 .allowTextWithProgress(true)
5971 .fillTextsFrom(this);
5972 result = applyStandardTemplateWithActions(getBigBaseLayoutResource(), p,
5973 null /* result */);
5974 }
5975 }
5976 makeHeaderExpanded(result);
5977 return result;
5978 }
5979
5980 // This code is executed on behalf of other apps' notifications, sometimes even by 3p apps,
5981 // a use case that is not supported by the Compat Framework library. Workarounds to resolve
5982 // the change's state in NotificationManagerService were very complex. While it's possible
5983 // apps can detect the change, it's most likely that the changes will simply result in
5984 // visual regressions.
5985 @SuppressWarnings("AndroidFrameworkCompatChange")
5986 private boolean bigContentViewRequired() {
5987 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.S) {
5988 return true;
5989 }
5990 // Notifications with contentView and without a bigContentView, style, or actions would
5991 // not have an expanded state before S, so showing the standard template expanded state
5992 // usually looks wrong, so we keep it simple and don't show the expanded state.
5993 boolean exempt = mN.contentView != null && mN.bigContentView == null
5994 && mStyle == null && mActions.size() == 0;
5995 return !exempt;
5996 }
5997
5998 /**
5999 * Construct a RemoteViews for the final notification header only. This will not be
6000 * colorized.
6001 *
6002 * @hide
6003 */
6004 public RemoteViews makeNotificationGroupHeader() {
6005 return makeNotificationHeader(mParams.reset()
6006 .viewType(StandardTemplateParams.VIEW_TYPE_GROUP_HEADER)
6007 .fillTextsFrom(this));
6008 }
6009
6010 /**
6011 * Construct a RemoteViews for the final notification header only. This will not be
6012 * colorized.
6013 *
6014 * @param p the template params to inflate this with
6015 */
6016 private RemoteViews makeNotificationHeader(StandardTemplateParams p) {
6017 // Headers on their own are never colorized
6018 p.disallowColorization();
6019 RemoteViews header = new BuilderRemoteViews(mContext.getApplicationInfo(),
6020 R.layout.notification_template_header);
6021 resetNotificationHeader(header);
6022 bindNotificationHeader(header, p);
6023 return header;
6024 }
6025
6026 /**
6027 * Construct a RemoteViews for the ambient version of the notification.
6028 *
6029 * @hide
6030 */
6031 public RemoteViews makeAmbientNotification() {
6032 RemoteViews headsUpContentView = createHeadsUpContentView(false /* increasedHeight */);
6033 if (headsUpContentView != null) {
6034 return headsUpContentView;
6035 }
6036 return createContentView();
6037 }
6038
6039 /**
6040 * Adapt the Notification header if this view is used as an expanded view.
6041 *
6042 * @hide
6043 */
6044 public static void makeHeaderExpanded(RemoteViews result) {
6045 if (result != null) {
6046 result.setBoolean(R.id.expand_button, "setExpanded", true);
6047 }
6048 }
6049
6050 /**
6051 * Construct a RemoteViews for the final heads-up notification layout.
6052 *
6053 * @param increasedHeight true if this layout be created with an increased height. Some
6054 * styles may support showing more then just that basic 1U size
6055 * and the system may decide to render important notifications
6056 * slightly bigger even when collapsed.
6057 *
6058 * @hide
6059 */
6060 public RemoteViews createHeadsUpContentView(boolean increasedHeight) {
6061 if (useExistingRemoteView(mN.headsUpContentView)) {
6062 return fullyCustomViewRequiresDecoration(false /* fromStyle */)
6063 ? minimallyDecoratedHeadsUpContentView(mN.headsUpContentView)
6064 : mN.headsUpContentView;
6065 } else if (mStyle != null) {
6066 final RemoteViews styleView = mStyle.makeHeadsUpContentView(increasedHeight);
6067 if (styleView != null) {
6068 return fullyCustomViewRequiresDecoration(true /* fromStyle */)
6069 ? minimallyDecoratedHeadsUpContentView(styleView) : styleView;
6070 }
6071 } else if (mActions.size() == 0) {
6072 return null;
6073 }
6074
6075 // We only want at most a single remote input history to be shown here, otherwise
6076 // the content would become squished.
6077 StandardTemplateParams p = mParams.reset()
6078 .viewType(StandardTemplateParams.VIEW_TYPE_HEADS_UP)
6079 .fillTextsFrom(this)
6080 .setMaxRemoteInputHistory(1);
6081 return applyStandardTemplateWithActions(getHeadsUpBaseLayoutResource(), p,
6082 null /* result */);
6083 }
6084
6085 /**
6086 * Construct a RemoteViews for the final heads-up notification layout.
6087 */
6088 public RemoteViews createHeadsUpContentView() {
6089 return createHeadsUpContentView(false /* useIncreasedHeight */);
6090 }
6091
6092 /**
6093 * Construct a RemoteViews for the display in public contexts like on the lockscreen.
6094 *
6095 * @param isLowPriority is this notification low priority
6096 * @hide
6097 */
6098 @UnsupportedAppUsage
6099 public RemoteViews makePublicContentView(boolean isLowPriority) {
6100 if (mN.publicVersion != null) {
6101 final Builder builder = recoverBuilder(mContext, mN.publicVersion);
6102 return builder.createContentView();
6103 }
6104 Bundle savedBundle = mN.extras;
6105 Style style = mStyle;
6106 mStyle = null;
6107 Icon largeIcon = mN.mLargeIcon;
6108 mN.mLargeIcon = null;
6109 Bitmap largeIconLegacy = mN.largeIcon;
6110 mN.largeIcon = null;
6111 ArrayList<Action> actions = mActions;
6112 mActions = new ArrayList<>();
6113 Bundle publicExtras = new Bundle();
6114 publicExtras.putBoolean(EXTRA_SHOW_WHEN,
6115 savedBundle.getBoolean(EXTRA_SHOW_WHEN));
6116 publicExtras.putBoolean(EXTRA_SHOW_CHRONOMETER,
6117 savedBundle.getBoolean(EXTRA_SHOW_CHRONOMETER));
6118 publicExtras.putBoolean(EXTRA_CHRONOMETER_COUNT_DOWN,
6119 savedBundle.getBoolean(EXTRA_CHRONOMETER_COUNT_DOWN));
6120 String appName = savedBundle.getString(EXTRA_SUBSTITUTE_APP_NAME);
6121 if (appName != null) {
6122 publicExtras.putString(EXTRA_SUBSTITUTE_APP_NAME, appName);
6123 }
6124 mN.extras = publicExtras;
6125 RemoteViews view;
6126 StandardTemplateParams params = mParams.reset()
6127 .viewType(StandardTemplateParams.VIEW_TYPE_PUBLIC)
6128 .fillTextsFrom(this);
6129 if (isLowPriority) {
6130 params.highlightExpander(false);
6131 }
6132 view = makeNotificationHeader(params);
6133 view.setBoolean(R.id.notification_header, "setExpandOnlyOnButton", true);
6134 mN.extras = savedBundle;
6135 mN.mLargeIcon = largeIcon;
6136 mN.largeIcon = largeIconLegacy;
6137 mActions = actions;
6138 mStyle = style;
6139 return view;
6140 }
6141
6142 /**
6143 * Construct a content view for the display when low - priority
6144 *
6145 * @param useRegularSubtext uses the normal subtext set if there is one available. Otherwise
6146 * a new subtext is created consisting of the content of the
6147 * notification.
6148 * @hide
6149 */
6150 public RemoteViews makeLowPriorityContentView(boolean useRegularSubtext) {
6151 StandardTemplateParams p = mParams.reset()
6152 .viewType(StandardTemplateParams.VIEW_TYPE_MINIMIZED)
6153 .highlightExpander(false)
6154 .fillTextsFrom(this);
6155 if (!useRegularSubtext || TextUtils.isEmpty(p.summaryText)) {
6156 p.summaryText(createSummaryText());
6157 }
6158 RemoteViews header = makeNotificationHeader(p);
6159 header.setBoolean(R.id.notification_header, "setAcceptAllTouches", true);
6160 // The low priority header has no app name and shows the text
6161 header.setBoolean(R.id.notification_header, "styleTextAsTitle", true);
6162 return header;
6163 }
6164
6165 private CharSequence createSummaryText() {
6166 CharSequence titleText = mN.extras.getCharSequence(Notification.EXTRA_TITLE);
6167 if (USE_ONLY_TITLE_IN_LOW_PRIORITY_SUMMARY) {
6168 return titleText;
6169 }
6170 SpannableStringBuilder summary = new SpannableStringBuilder();
6171 if (titleText == null) {
6172 titleText = mN.extras.getCharSequence(Notification.EXTRA_TITLE_BIG);
6173 }
6174 BidiFormatter bidi = BidiFormatter.getInstance();
6175 if (titleText != null) {
6176 summary.append(bidi.unicodeWrap(titleText));
6177 }
6178 CharSequence contentText = mN.extras.getCharSequence(Notification.EXTRA_TEXT);
6179 if (titleText != null && contentText != null) {
6180 summary.append(bidi.unicodeWrap(mContext.getText(
6181 R.string.notification_header_divider_symbol_with_spaces)));
6182 }
6183 if (contentText != null) {
6184 summary.append(bidi.unicodeWrap(contentText));
6185 }
6186 return summary;
6187 }
6188
6189 private RemoteViews generateActionButton(Action action, boolean emphasizedMode,
6190 StandardTemplateParams p) {
6191 final boolean tombstone = (action.actionIntent == null);
6192 RemoteViews button = new BuilderRemoteViews(mContext.getApplicationInfo(),
6193 emphasizedMode ? getEmphasizedActionLayoutResource()
6194 : tombstone ? getActionTombstoneLayoutResource()
6195 : getActionLayoutResource());
6196 if (!tombstone) {
6197 button.setOnClickPendingIntent(R.id.action0, action.actionIntent);
6198 }
6199 button.setContentDescription(R.id.action0, action.title);
6200 if (action.mRemoteInputs != null) {
6201 button.setRemoteInputs(R.id.action0, action.mRemoteInputs);
6202 }
6203 if (emphasizedMode) {
6204 // change the background bgColor
6205 CharSequence title = action.title;
6206 int buttonFillColor = getColors(p).getSecondaryAccentColor();
6207 if (isLegacy()) {
6208 title = ContrastColorUtil.clearColorSpans(title);
6209 } else {
6210 // Check for a full-length span color to use as the button fill color.
6211 Integer fullLengthColor = getFullLengthSpanColor(title);
6212 if (fullLengthColor != null) {
6213 // Ensure the custom button fill has 1.3:1 contrast w/ notification bg.
6214 int notifBackgroundColor = getColors(p).getBackgroundColor();
6215 buttonFillColor = ensureButtonFillContrast(
6216 fullLengthColor, notifBackgroundColor);
6217 }
6218 // Remove full-length color spans and ensure text contrast with the button fill.
6219 title = ensureColorSpanContrast(title, buttonFillColor);
6220 }
6221 button.setTextViewText(R.id.action0, processTextSpans(title));
6222 final int textColor = ContrastColorUtil.resolvePrimaryColor(mContext,
6223 buttonFillColor, mInNightMode);
6224 button.setTextColor(R.id.action0, textColor);
6225 // We only want about 20% alpha for the ripple
6226 final int rippleColor = (textColor & 0x00ffffff) | 0x33000000;
6227 button.setColorStateList(R.id.action0, "setRippleColor",
6228 ColorStateList.valueOf(rippleColor));
6229 button.setColorStateList(R.id.action0, "setButtonBackground",
6230 ColorStateList.valueOf(buttonFillColor));
6231 if (p.mCallStyleActions) {
6232 button.setImageViewIcon(R.id.action0, action.getIcon());
6233 boolean priority = action.getExtras().getBoolean(CallStyle.KEY_ACTION_PRIORITY);
6234 button.setBoolean(R.id.action0, "setIsPriority", priority);
6235 int minWidthDimen =
6236 priority ? R.dimen.call_notification_system_action_min_width : 0;
6237 button.setIntDimen(R.id.action0, "setMinimumWidth", minWidthDimen);
6238 }
6239 } else {
6240 button.setTextViewText(R.id.action0, processTextSpans(
6241 processLegacyText(action.title)));
6242 button.setTextColor(R.id.action0, getStandardActionColor(p));
6243 }
6244 // CallStyle notifications add action buttons which don't actually exist in mActions,
6245 // so we have to omit the index in that case.
6246 int actionIndex = mActions.indexOf(action);
6247 if (actionIndex != -1) {
6248 button.setIntTag(R.id.action0, R.id.notification_action_index_tag, actionIndex);
6249 }
6250 return button;
6251 }
6252
6253 /**
6254 * Extract the color from a full-length span from the text.
6255 *
6256 * @param charSequence the charSequence containing spans
6257 * @return the raw color of the text's last full-length span containing a color, or null if
6258 * no full-length span sets the text color.
6259 * @hide
6260 */
6261 @VisibleForTesting
6262 @Nullable
6263 public static Integer getFullLengthSpanColor(CharSequence charSequence) {
6264 // NOTE: this method preserves the functionality that for a CharSequence with multiple
6265 // full-length spans, the color of the last one is used.
6266 Integer result = null;
6267 if (charSequence instanceof Spanned) {
6268 Spanned ss = (Spanned) charSequence;
6269 Object[] spans = ss.getSpans(0, ss.length(), Object.class);
6270 // First read through all full-length spans to get the button fill color, which will
6271 // be used as the background color for ensuring contrast of non-full-length spans.
6272 for (Object span : spans) {
6273 int spanStart = ss.getSpanStart(span);
6274 int spanEnd = ss.getSpanEnd(span);
6275 boolean fullLength = (spanEnd - spanStart) == charSequence.length();
6276 if (!fullLength) {
6277 continue;
6278 }
6279 if (span instanceof TextAppearanceSpan) {
6280 TextAppearanceSpan originalSpan = (TextAppearanceSpan) span;
6281 ColorStateList textColor = originalSpan.getTextColor();
6282 if (textColor != null) {
6283 result = textColor.getDefaultColor();
6284 }
6285 } else if (span instanceof ForegroundColorSpan) {
6286 ForegroundColorSpan originalSpan = (ForegroundColorSpan) span;
6287 result = originalSpan.getForegroundColor();
6288 }
6289 }
6290 }
6291 return result;
6292 }
6293
6294 /**
6295 * Ensures contrast on color spans against a background color.
6296 * Note that any full-length color spans will be removed instead of being contrasted.
6297 *
6298 * @param charSequence the charSequence on which the spans are
6299 * @param background the background color to ensure the contrast against
6300 * @return the contrasted charSequence
6301 * @hide
6302 */
6303 @VisibleForTesting
6304 public static CharSequence ensureColorSpanContrast(CharSequence charSequence,
6305 int background) {
6306 if (charSequence instanceof Spanned) {
6307 Spanned ss = (Spanned) charSequence;
6308 Object[] spans = ss.getSpans(0, ss.length(), Object.class);
6309 SpannableStringBuilder builder = new SpannableStringBuilder(ss.toString());
6310 for (Object span : spans) {
6311 Object resultSpan = span;
6312 int spanStart = ss.getSpanStart(span);
6313 int spanEnd = ss.getSpanEnd(span);
6314 boolean fullLength = (spanEnd - spanStart) == charSequence.length();
6315 if (resultSpan instanceof CharacterStyle) {
6316 resultSpan = ((CharacterStyle) span).getUnderlying();
6317 }
6318 if (resultSpan instanceof TextAppearanceSpan) {
6319 TextAppearanceSpan originalSpan = (TextAppearanceSpan) resultSpan;
6320 ColorStateList textColor = originalSpan.getTextColor();
6321 if (textColor != null) {
6322 if (fullLength) {
6323 // Let's drop the color from the span
6324 textColor = null;
6325 } else {
6326 int[] colors = textColor.getColors();
6327 int[] newColors = new int[colors.length];
6328 for (int i = 0; i < newColors.length; i++) {
6329 boolean isBgDark = isColorDark(background);
6330 newColors[i] = ContrastColorUtil.ensureLargeTextContrast(
6331 colors[i], background, isBgDark);
6332 }
6333 textColor = new ColorStateList(textColor.getStates().clone(),
6334 newColors);
6335 }
6336 resultSpan = new TextAppearanceSpan(
6337 originalSpan.getFamily(),
6338 originalSpan.getTextStyle(),
6339 originalSpan.getTextSize(),
6340 textColor,
6341 originalSpan.getLinkTextColor());
6342 }
6343 } else if (resultSpan instanceof ForegroundColorSpan) {
6344 if (fullLength) {
6345 resultSpan = null;
6346 } else {
6347 ForegroundColorSpan originalSpan = (ForegroundColorSpan) resultSpan;
6348 int foregroundColor = originalSpan.getForegroundColor();
6349 boolean isBgDark = isColorDark(background);
6350 foregroundColor = ContrastColorUtil.ensureLargeTextContrast(
6351 foregroundColor, background, isBgDark);
6352 resultSpan = new ForegroundColorSpan(foregroundColor);
6353 }
6354 } else {
6355 resultSpan = span;
6356 }
6357 if (resultSpan != null) {
6358 builder.setSpan(resultSpan, spanStart, spanEnd, ss.getSpanFlags(span));
6359 }
6360 }
6361 return builder;
6362 }
6363 return charSequence;
6364 }
6365
6366 /**
6367 * Determines if the color is light or dark. Specifically, this is using the same metric as
6368 * {@link ContrastColorUtil#resolvePrimaryColor(Context, int, boolean)} and peers so that
6369 * the direction of color shift is consistent.
6370 *
6371 * @param color the color to check
6372 * @return true if the color has higher contrast with white than black
6373 * @hide
6374 */
6375 public static boolean isColorDark(int color) {
6376 // as per ContrastColorUtil.shouldUseDark, this uses the color contrast midpoint.
6377 return ContrastColorUtil.calculateLuminance(color) <= 0.17912878474;
6378 }
6379
6380 /**
6381 * Finds a button fill color with sufficient contrast over bg (1.3:1) that has the same hue
6382 * as the original color, but is lightened or darkened depending on whether the background
6383 * is dark or light.
6384 *
6385 * @hide
6386 */
6387 @VisibleForTesting
6388 public static int ensureButtonFillContrast(int color, int bg) {
6389 return isColorDark(bg)
6390 ? ContrastColorUtil.findContrastColorAgainstDark(color, bg, true, 1.3)
6391 : ContrastColorUtil.findContrastColor(color, bg, true, 1.3);
6392 }
6393
6394
6395 /**
6396 * @return Whether we are currently building a notification from a legacy (an app that
6397 * doesn't create material notifications by itself) app.
6398 */
6399 private boolean isLegacy() {
6400 if (!mIsLegacyInitialized) {
6401 mIsLegacy = mContext.getApplicationInfo().targetSdkVersion
6402 < Build.VERSION_CODES.LOLLIPOP;
6403 mIsLegacyInitialized = true;
6404 }
6405 return mIsLegacy;
6406 }
6407
6408 private CharSequence processLegacyText(CharSequence charSequence) {
6409 boolean isAlreadyLightText = isLegacy() || textColorsNeedInversion();
6410 if (isAlreadyLightText) {
6411 return getColorUtil().invertCharSequenceColors(charSequence);
6412 } else {
6413 return charSequence;
6414 }
6415 }
6416
6417 /**
6418 * Apply any necessary colors to the small icon
6419 */
6420 private void processSmallIconColor(Icon smallIcon, RemoteViews contentView,
6421 StandardTemplateParams p) {
6422 boolean colorable = !isLegacy() || getColorUtil().isGrayscaleIcon(mContext, smallIcon);
6423 int color = getSmallIconColor(p);
6424 contentView.setInt(R.id.icon, "setBackgroundColor",
6425 getBackgroundColor(p));
6426 contentView.setInt(R.id.icon, "setOriginalIconColor",
6427 colorable ? color : COLOR_INVALID);
6428 }
6429
6430 /**
6431 * Make the largeIcon dark if it's a fake smallIcon (that is,
6432 * if it's grayscale).
6433 */
6434 // TODO: also check bounds, transparency, that sort of thing.
6435 private void processLargeLegacyIcon(Icon largeIcon, RemoteViews contentView,
6436 StandardTemplateParams p) {
6437 if (largeIcon != null && isLegacy()
6438 && getColorUtil().isGrayscaleIcon(mContext, largeIcon)) {
6439 // resolve color will fall back to the default when legacy
6440 int color = getSmallIconColor(p);
6441 contentView.setInt(R.id.icon, "setOriginalIconColor", color);
6442 }
6443 }
6444
6445 private void sanitizeColor() {
6446 if (mN.color != COLOR_DEFAULT) {
6447 mN.color |= 0xFF000000; // no alpha for custom colors
6448 }
6449 }
6450
6451 /**
6452 * Gets the standard action button color
6453 */
6454 private @ColorInt int getStandardActionColor(Notification.StandardTemplateParams p) {
6455 return mTintActionButtons || isBackgroundColorized(p)
6456 ? getPrimaryAccentColor(p) : getSecondaryTextColor(p);
6457 }
6458
6459 /**
6460 * Gets the foreground color of the small icon. If the notification is colorized, this
6461 * is the primary text color, otherwise it's the contrast-adjusted app-provided color.
6462 */
6463 private @ColorInt int getSmallIconColor(StandardTemplateParams p) {
6464 return getColors(p).getContrastColor();
6465 }
6466
6467 /** @return the theme's accent color for colored UI elements. */
6468 private @ColorInt int getPrimaryAccentColor(StandardTemplateParams p) {
6469 return getColors(p).getPrimaryAccentColor();
6470 }
6471
6472 /**
6473 * Apply the unstyled operations and return a new {@link Notification} object.
6474 * @hide
6475 */
6476 @NonNull
6477 public Notification buildUnstyled() {
6478 if (mActions.size() > 0) {
6479 mN.actions = new Action[mActions.size()];
6480 mActions.toArray(mN.actions);
6481 }
6482 if (!mPersonList.isEmpty()) {
6483 mN.extras.putParcelableArrayList(EXTRA_PEOPLE_LIST, mPersonList);
6484 }
6485 if (mN.bigContentView != null || mN.contentView != null
6486 || mN.headsUpContentView != null) {
6487 mN.extras.putBoolean(EXTRA_CONTAINS_CUSTOM_VIEW, true);
6488 }
6489 return mN;
6490 }
6491
6492 /**
6493 * Creates a Builder from an existing notification so further changes can be made.
6494 * @param context The context for your application / activity.
6495 * @param n The notification to create a Builder from.
6496 */
6497 @NonNull
6498 public static Notification.Builder recoverBuilder(Context context, Notification n) {
6499 // Re-create notification context so we can access app resources.
6500 ApplicationInfo applicationInfo = n.extras.getParcelable(
6501 EXTRA_BUILDER_APPLICATION_INFO, ApplicationInfo.class);
6502 Context builderContext;
6503 if (applicationInfo != null) {
6504 try {
6505 builderContext = context.createApplicationContext(applicationInfo,
6506 Context.CONTEXT_RESTRICTED);
6507 } catch (NameNotFoundException e) {
6508 Log.e(TAG, "ApplicationInfo " + applicationInfo + " not found");
6509 builderContext = context; // try with our context
6510 }
6511 } else {
6512 builderContext = context; // try with given context
6513 }
6514
6515 return new Builder(builderContext, n);
6516 }
6517
6518 /**
6519 * Determines whether the platform can generate contextual actions for a notification.
6520 * By default this is true.
6521 */
6522 @NonNull
6523 public Builder setAllowSystemGeneratedContextualActions(boolean allowed) {
6524 mN.mAllowSystemGeneratedContextualActions = allowed;
6525 return this;
6526 }
6527
6528 /**
6529 * @deprecated Use {@link #build()} instead.
6530 */
6531 @Deprecated
6532 public Notification getNotification() {
6533 return build();
6534 }
6535
6536 /**
6537 * Combine all of the options that have been set and return a new {@link Notification}
6538 * object.
6539 *
6540 * If this notification has {@link BubbleMetadata} attached that was created with
6541 * a shortcutId a check will be performed to ensure the shortcutId supplied to bubble
6542 * metadata matches the shortcutId set on the notification builder, if one was set.
6543 * If the shortcutId's were specified but do not match, an exception is thrown here.
6544 *
6545 * @see BubbleMetadata.Builder#Builder(String)
6546 * @see #setShortcutId(String)
6547 */
6548 @NonNull
6549 public Notification build() {
6550 // Check shortcut id matches
6551 if (mN.mShortcutId != null
6552 && mN.mBubbleMetadata != null
6553 && mN.mBubbleMetadata.getShortcutId() != null
6554 && !mN.mShortcutId.equals(mN.mBubbleMetadata.getShortcutId())) {
6555 throw new IllegalArgumentException(
6556 "Notification and BubbleMetadata shortcut id's don't match,"
6557 + " notification: " + mN.mShortcutId
6558 + " vs bubble: " + mN.mBubbleMetadata.getShortcutId());
6559 }
6560
6561 // first, add any extras from the calling code
6562 if (mUserExtras != null) {
6563 mN.extras = getAllExtras();
6564 }
6565
6566 mN.creationTime = System.currentTimeMillis();
6567
6568 // lazy stuff from mContext; see comment in Builder(Context, Notification)
6569 Notification.addFieldsFromContext(mContext, mN);
6570
6571 buildUnstyled();
6572
6573 if (mStyle != null) {
6574 mStyle.reduceImageSizes(mContext);
6575 mStyle.purgeResources();
6576 mStyle.validate(mContext);
6577 mStyle.buildStyled(mN);
6578 }
6579 mN.reduceImageSizes(mContext);
6580
6581 if (mContext.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N
6582 && !styleDisplaysCustomViewInline()) {
6583 RemoteViews newContentView = mN.contentView;
6584 RemoteViews newBigContentView = mN.bigContentView;
6585 RemoteViews newHeadsUpContentView = mN.headsUpContentView;
6586 if (newContentView == null) {
6587 newContentView = createContentView();
6588 mN.extras.putInt(EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT,
6589 newContentView.getSequenceNumber());
6590 }
6591 if (newBigContentView == null) {
6592 newBigContentView = createBigContentView();
6593 if (newBigContentView != null) {
6594 mN.extras.putInt(EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT,
6595 newBigContentView.getSequenceNumber());
6596 }
6597 }
6598 if (newHeadsUpContentView == null) {
6599 newHeadsUpContentView = createHeadsUpContentView();
6600 if (newHeadsUpContentView != null) {
6601 mN.extras.putInt(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT,
6602 newHeadsUpContentView.getSequenceNumber());
6603 }
6604 }
6605 // Don't set any of the content views until after they have all been generated,
6606 // to avoid the generated .contentView triggering the logic which skips generating
6607 // the .bigContentView.
6608 mN.contentView = newContentView;
6609 mN.bigContentView = newBigContentView;
6610 mN.headsUpContentView = newHeadsUpContentView;
6611 }
6612
6613 if ((mN.defaults & DEFAULT_LIGHTS) != 0) {
6614 mN.flags |= FLAG_SHOW_LIGHTS;
6615 }
6616
6617 mN.allPendingIntents = null;
6618
6619 return mN;
6620 }
6621
6622 private boolean styleDisplaysCustomViewInline() {
6623 return mStyle != null && mStyle.displayCustomViewInline();
6624 }
6625
6626 /**
6627 * Apply this Builder to an existing {@link Notification} object.
6628 *
6629 * @hide
6630 */
6631 @NonNull
6632 public Notification buildInto(@NonNull Notification n) {
6633 build().cloneInto(n, true);
6634 return n;
6635 }
6636
6637 /**
6638 * Removes RemoteViews that were created for compatibility from {@param n}, if they did not
6639 * change.
6640 *
6641 * @return {@param n}, if no stripping is needed, otherwise a stripped clone of {@param n}.
6642 *
6643 * @hide
6644 */
6645 public static Notification maybeCloneStrippedForDelivery(Notification n) {
6646 String templateClass = n.extras.getString(EXTRA_TEMPLATE);
6647
6648 // Only strip views for known Styles because we won't know how to
6649 // re-create them otherwise.
6650 if (!TextUtils.isEmpty(templateClass)
6651 && getNotificationStyleClass(templateClass) == null) {
6652 return n;
6653 }
6654
6655 // Only strip unmodified BuilderRemoteViews.
6656 boolean stripContentView = n.contentView instanceof BuilderRemoteViews &&
6657 n.extras.getInt(EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT, -1) ==
6658 n.contentView.getSequenceNumber();
6659 boolean stripBigContentView = n.bigContentView instanceof BuilderRemoteViews &&
6660 n.extras.getInt(EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT, -1) ==
6661 n.bigContentView.getSequenceNumber();
6662 boolean stripHeadsUpContentView = n.headsUpContentView instanceof BuilderRemoteViews &&
6663 n.extras.getInt(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT, -1) ==
6664 n.headsUpContentView.getSequenceNumber();
6665
6666 // Nothing to do here, no need to clone.
6667 if (!stripContentView && !stripBigContentView && !stripHeadsUpContentView) {
6668 return n;
6669 }
6670
6671 Notification clone = n.clone();
6672 if (stripContentView) {
6673 clone.contentView = null;
6674 clone.extras.remove(EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT);
6675 }
6676 if (stripBigContentView) {
6677 clone.bigContentView = null;
6678 clone.extras.remove(EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT);
6679 }
6680 if (stripHeadsUpContentView) {
6681 clone.headsUpContentView = null;
6682 clone.extras.remove(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT);
6683 }
6684 return clone;
6685 }
6686
6687 @UnsupportedAppUsage
6688 private int getBaseLayoutResource() {
6689 return R.layout.notification_template_material_base;
6690 }
6691
6692 private int getHeadsUpBaseLayoutResource() {
6693 return R.layout.notification_template_material_heads_up_base;
6694 }
6695
6696 private int getBigBaseLayoutResource() {
6697 return R.layout.notification_template_material_big_base;
6698 }
6699
6700 private int getBigPictureLayoutResource() {
6701 return R.layout.notification_template_material_big_picture;
6702 }
6703
6704 private int getBigTextLayoutResource() {
6705 return R.layout.notification_template_material_big_text;
6706 }
6707
6708 private int getInboxLayoutResource() {
6709 return R.layout.notification_template_material_inbox;
6710 }
6711
6712 private int getMessagingLayoutResource() {
6713 return R.layout.notification_template_material_messaging;
6714 }
6715
6716 private int getBigMessagingLayoutResource() {
6717 return R.layout.notification_template_material_big_messaging;
6718 }
6719
6720 private int getConversationLayoutResource() {
6721 return R.layout.notification_template_material_conversation;
6722 }
6723
6724 private int getActionLayoutResource() {
6725 return R.layout.notification_material_action;
6726 }
6727
6728 private int getEmphasizedActionLayoutResource() {
6729 return R.layout.notification_material_action_emphasized;
6730 }
6731
6732 private int getActionTombstoneLayoutResource() {
6733 return R.layout.notification_material_action_tombstone;
6734 }
6735
6736 private @ColorInt int getBackgroundColor(StandardTemplateParams p) {
6737 return getColors(p).getBackgroundColor();
6738 }
6739
6740 private boolean textColorsNeedInversion() {
6741 if (mStyle == null || !MediaStyle.class.equals(mStyle.getClass())) {
6742 return false;
6743 }
6744 int targetSdkVersion = mContext.getApplicationInfo().targetSdkVersion;
6745 return targetSdkVersion > Build.VERSION_CODES.M
6746 && targetSdkVersion < Build.VERSION_CODES.O;
6747 }
6748
6749 /**
6750 * Get the text that should be displayed in the statusBar when heads upped. This is
6751 * usually just the app name, but may be different depending on the style.
6752 *
6753 * @param publicMode If true, return a text that is safe to display in public.
6754 *
6755 * @hide
6756 */
6757 public CharSequence getHeadsUpStatusBarText(boolean publicMode) {
6758 if (mStyle != null && !publicMode) {
6759 CharSequence text = mStyle.getHeadsUpStatusBarText();
6760 if (!TextUtils.isEmpty(text)) {
6761 return text;
6762 }
6763 }
6764 return loadHeaderAppName();
6765 }
6766
6767 /**
6768 * @return if this builder uses a template
6769 *
6770 * @hide
6771 */
6772 public boolean usesTemplate() {
6773 return (mN.contentView == null && mN.headsUpContentView == null
6774 && mN.bigContentView == null)
6775 || styleDisplaysCustomViewInline();
6776 }
6777 }
6778
6779 /**
6780 * Reduces the image sizes to conform to a maximum allowed size. This also processes all custom
6781 * remote views.
6782 *
6783 * @hide
6784 */
6785 void reduceImageSizes(Context context) {
6786 if (extras.getBoolean(EXTRA_REDUCED_IMAGES)) {
6787 return;
6788 }
6789 boolean isLowRam = ActivityManager.isLowRamDeviceStatic();
6790
6791 if (mSmallIcon != null
6792 // Only bitmap icons can be downscaled.
6793 && (mSmallIcon.getType() == Icon.TYPE_BITMAP
6794 || mSmallIcon.getType() == Icon.TYPE_ADAPTIVE_BITMAP)) {
6795 Resources resources = context.getResources();
6796 int maxSize = resources.getDimensionPixelSize(
6797 isLowRam ? R.dimen.notification_small_icon_size_low_ram
6798 : R.dimen.notification_small_icon_size);
6799 mSmallIcon.scaleDownIfNecessary(maxSize, maxSize);
6800 }
6801
6802 if (mLargeIcon != null || largeIcon != null) {
6803 Resources resources = context.getResources();
6804 Class<? extends Style> style = getNotificationStyle();
6805 int maxSize = resources.getDimensionPixelSize(isLowRam
6806 ? R.dimen.notification_right_icon_size_low_ram
6807 : R.dimen.notification_right_icon_size);
6808 if (mLargeIcon != null) {
6809 mLargeIcon.scaleDownIfNecessary(maxSize, maxSize);
6810 }
6811 if (largeIcon != null) {
6812 largeIcon = Icon.scaleDownIfNecessary(largeIcon, maxSize, maxSize);
6813 }
6814 }
6815 reduceImageSizesForRemoteView(contentView, context, isLowRam);
6816 reduceImageSizesForRemoteView(headsUpContentView, context, isLowRam);
6817 reduceImageSizesForRemoteView(bigContentView, context, isLowRam);
6818 extras.putBoolean(EXTRA_REDUCED_IMAGES, true);
6819 }
6820
6821 private void reduceImageSizesForRemoteView(RemoteViews remoteView, Context context,
6822 boolean isLowRam) {
6823 if (remoteView != null) {
6824 Resources resources = context.getResources();
6825 int maxWidth = resources.getDimensionPixelSize(isLowRam
6826 ? R.dimen.notification_custom_view_max_image_width_low_ram
6827 : R.dimen.notification_custom_view_max_image_width);
6828 int maxHeight = resources.getDimensionPixelSize(isLowRam
6829 ? R.dimen.notification_custom_view_max_image_height_low_ram
6830 : R.dimen.notification_custom_view_max_image_height);
6831 remoteView.reduceImageSizes(maxWidth, maxHeight);
6832 }
6833 }
6834
6835 /**
6836 * @return whether this notification is a foreground service notification
6837 * @hide
6838 */
6839 public boolean isForegroundService() {
6840 return (flags & Notification.FLAG_FOREGROUND_SERVICE) != 0;
6841 }
6842
6843 /**
6844 * Describe whether this notification's content such that it should always display
6845 * immediately when tied to a foreground service, even if the system might generally
6846 * avoid showing the notifications for short-lived foreground service lifetimes.
6847 *
6848 * Immediate visibility of the Notification is indicated when:
6849 * <ul>
6850 * <li>The app specifically indicated it with
6851 * {@link Notification.Builder#setForegroundServiceBehavior(int)
6852 * setForegroundServiceBehavior(BEHAVIOR_IMMEDIATE_DISPLAY)}</li>
6853 * <li>It is a media notification or has an associated media session</li>
6854 * <li>It is a call or navigation notification</li>
6855 * <li>It provides additional action affordances</li>
6856 * </ul>
6857 *
6858 * If the app has specified
6859 * {@code NotificationBuilder.setForegroundServiceBehavior(BEHAVIOR_DEFERRED_DISPLAY)}
6860 * then this method will return {@code false} and notification visibility will be
6861 * deferred following the service's transition to the foreground state even in the
6862 * circumstances described above.
6863 *
6864 * @return whether this notification should be displayed immediately when
6865 * its associated service transitions to the foreground state
6866 * @hide
6867 */
6868 @TestApi
6869 public boolean shouldShowForegroundImmediately() {
6870 // Has the app demanded immediate display?
6871 if (mFgsDeferBehavior == FOREGROUND_SERVICE_IMMEDIATE) {
6872 return true;
6873 }
6874
6875 // Has the app demanded deferred display?
6876 if (mFgsDeferBehavior == FOREGROUND_SERVICE_DEFERRED) {
6877 return false;
6878 }
6879
6880 // We show these sorts of notifications immediately in the absence of
6881 // any explicit app declaration
6882 if (isMediaNotification()
6883 || CATEGORY_CALL.equals(category)
6884 || CATEGORY_NAVIGATION.equals(category)
6885 || (actions != null && actions.length > 0)) {
6886 return true;
6887 }
6888
6889 // No extenuating circumstances: defer visibility
6890 return false;
6891 }
6892
6893 /**
6894 * Has forced deferral for FGS purposes been specified?
6895 * @hide
6896 */
6897 public boolean isForegroundDisplayForceDeferred() {
6898 return FOREGROUND_SERVICE_DEFERRED == mFgsDeferBehavior;
6899 }
6900
6901 /**
6902 * @return the style class of this notification
6903 * @hide
6904 */
6905 public Class<? extends Notification.Style> getNotificationStyle() {
6906 String templateClass = extras.getString(Notification.EXTRA_TEMPLATE);
6907
6908 if (!TextUtils.isEmpty(templateClass)) {
6909 return Notification.getNotificationStyleClass(templateClass);
6910 }
6911 return null;
6912 }
6913
6914 /**
6915 * @return whether the style of this notification is the one provided
6916 * @hide
6917 */
6918 public boolean isStyle(@NonNull Class<? extends Style> styleClass) {
6919 String templateClass = extras.getString(Notification.EXTRA_TEMPLATE);
6920 return Objects.equals(templateClass, styleClass.getName());
6921 }
6922
6923 /**
6924 * @return true if this notification is colorized *for the purposes of ranking*. If the
6925 * {@link #color} is {@link #COLOR_DEFAULT} this will be true, even though the actual
6926 * appearance of the notification may not be "colorized".
6927 *
6928 * @hide
6929 */
6930 public boolean isColorized() {
6931 return extras.getBoolean(EXTRA_COLORIZED)
6932 && (hasColorizedPermission() || isForegroundService());
6933 }
6934
6935 /**
6936 * Returns whether an app can colorize due to the android.permission.USE_COLORIZED_NOTIFICATIONS
6937 * permission. The permission is checked when a notification is enqueued.
6938 */
6939 private boolean hasColorizedPermission() {
6940 return (flags & Notification.FLAG_CAN_COLORIZE) != 0;
6941 }
6942
6943 /**
6944 * @return true if this is a media style notification with a media session
6945 *
6946 * @hide
6947 */
6948 public boolean isMediaNotification() {
6949 Class<? extends Style> style = getNotificationStyle();
6950 boolean isMediaStyle = (MediaStyle.class.equals(style)
6951 || DecoratedMediaCustomViewStyle.class.equals(style));
6952
6953 boolean hasMediaSession = extras.getParcelable(Notification.EXTRA_MEDIA_SESSION,
6954 MediaSession.Token.class) != null;
6955
6956 return isMediaStyle && hasMediaSession;
6957 }
6958
6959 /**
6960 * @return true if this notification is showing as a bubble
6961 *
6962 * @hide
6963 */
6964 public boolean isBubbleNotification() {
6965 return (flags & Notification.FLAG_BUBBLE) != 0;
6966 }
6967
6968 private boolean hasLargeIcon() {
6969 return mLargeIcon != null || largeIcon != null;
6970 }
6971
6972 /**
6973 * @return true if the notification will show the time; false otherwise
6974 * @hide
6975 */
6976 public boolean showsTime() {
6977 return when != 0 && extras.getBoolean(EXTRA_SHOW_WHEN);
6978 }
6979
6980 /**
6981 * @return true if the notification will show a chronometer; false otherwise
6982 * @hide
6983 */
6984 public boolean showsChronometer() {
6985 return when != 0 && extras.getBoolean(EXTRA_SHOW_CHRONOMETER);
6986 }
6987
6988 /**
6989 * @return true if the notification has image
6990 */
6991 public boolean hasImage() {
6992 if (isStyle(MessagingStyle.class) && extras != null) {
6993 final Parcelable[] messages = extras.getParcelableArray(EXTRA_MESSAGES);
6994 if (!ArrayUtils.isEmpty(messages)) {
6995 for (MessagingStyle.Message m : MessagingStyle.Message
6996 .getMessagesFromBundleArray(messages)) {
6997 if (m.getDataUri() != null
6998 && m.getDataMimeType() != null
6999 && m.getDataMimeType().startsWith("image/")) {
7000 return true;
7001 }
7002 }
7003 }
7004 } else if (hasLargeIcon()) {
7005 return true;
7006 } else if (extras.containsKey(EXTRA_BACKGROUND_IMAGE_URI)) {
7007 return true;
7008 }
7009 return false;
7010 }
7011
7012
7013 /**
7014 * @removed
7015 */
7016 @SystemApi
7017 public static Class<? extends Style> getNotificationStyleClass(String templateClass) {
7018 for (Class<? extends Style> innerClass : PLATFORM_STYLE_CLASSES) {
7019 if (templateClass.equals(innerClass.getName())) {
7020 return innerClass;
7021 }
7022 }
7023 return null;
7024 }
7025
7026 private static void buildCustomContentIntoTemplate(@NonNull Context context,
7027 @NonNull RemoteViews template, @Nullable RemoteViews customContent,
7028 @NonNull StandardTemplateParams p, @NonNull TemplateBindResult result) {
7029 int childIndex = -1;
7030 if (customContent != null) {
7031 // Need to clone customContent before adding, because otherwise it can no longer be
7032 // parceled independently of remoteViews.
7033 customContent = customContent.clone();
7034 if (p.mHeaderless) {
7035 template.removeFromParent(R.id.notification_top_line);
7036 // We do not know how many lines ar emote view has, so we presume it has 2; this
7037 // ensures that we don't under-pad the content, which could lead to abuse, at the
7038 // cost of making single-line custom content over-padded.
7039 Builder.setHeaderlessVerticalMargins(template, p, true /* hasSecondLine */);
7040 } else {
7041 // also update the end margin to account for the large icon or expander
7042 Resources resources = context.getResources();
7043 result.mTitleMarginSet.applyToView(template, R.id.notification_main_column,
7044 resources.getDimension(R.dimen.notification_content_margin_end)
7045 / resources.getDisplayMetrics().density);
7046 }
7047 template.removeAllViewsExceptId(R.id.notification_main_column, R.id.progress);
7048 template.addView(R.id.notification_main_column, customContent, 0 /* index */);
7049 template.addFlags(RemoteViews.FLAG_REAPPLY_DISALLOWED);
7050 childIndex = 0;
7051 }
7052 template.setIntTag(R.id.notification_main_column,
7053 com.android.internal.R.id.notification_custom_view_index_tag,
7054 childIndex);
7055 }
7056
7057 /**
7058 * An object that can apply a rich notification style to a {@link Notification.Builder}
7059 * object.
7060 */
7061 public static abstract class Style {
7062
7063 /**
7064 * The number of items allowed simulatanously in the remote input history.
7065 * @hide
7066 */
7067 static final int MAX_REMOTE_INPUT_HISTORY_LINES = 3;
7068 private CharSequence mBigContentTitle;
7069
7070 /**
7071 * @hide
7072 */
7073 protected CharSequence mSummaryText = null;
7074
7075 /**
7076 * @hide
7077 */
7078 protected boolean mSummaryTextSet = false;
7079
7080 protected Builder mBuilder;
7081
7082 /**
7083 * Overrides ContentTitle in the big form of the template.
7084 * This defaults to the value passed to setContentTitle().
7085 */
7086 protected void internalSetBigContentTitle(CharSequence title) {
7087 mBigContentTitle = title;
7088 }
7089
7090 /**
7091 * Set the first line of text after the detail section in the big form of the template.
7092 */
7093 protected void internalSetSummaryText(CharSequence cs) {
7094 mSummaryText = cs;
7095 mSummaryTextSet = true;
7096 }
7097
7098 public void setBuilder(Builder builder) {
7099 if (mBuilder != builder) {
7100 mBuilder = builder;
7101 if (mBuilder != null) {
7102 mBuilder.setStyle(this);
7103 }
7104 }
7105 }
7106
7107 protected void checkBuilder() {
7108 if (mBuilder == null) {
7109 throw new IllegalArgumentException("Style requires a valid Builder object");
7110 }
7111 }
7112
7113 protected RemoteViews getStandardView(int layoutId) {
7114 // TODO(jeffdq): set the view type based on the layout resource?
7115 StandardTemplateParams p = mBuilder.mParams.reset()
7116 .viewType(StandardTemplateParams.VIEW_TYPE_UNSPECIFIED)
7117 .fillTextsFrom(mBuilder);
7118 return getStandardView(layoutId, p, null);
7119 }
7120
7121
7122 /**
7123 * Get the standard view for this style.
7124 *
7125 * @param layoutId The layout id to use.
7126 * @param p the params for this inflation.
7127 * @param result The result where template bind information is saved.
7128 * @return A remoteView for this style.
7129 * @hide
7130 */
7131 protected RemoteViews getStandardView(int layoutId, StandardTemplateParams p,
7132 TemplateBindResult result) {
7133 checkBuilder();
7134
7135 if (mBigContentTitle != null) {
7136 p.title = mBigContentTitle;
7137 }
7138
7139 return mBuilder.applyStandardTemplateWithActions(layoutId, p, result);
7140 }
7141
7142 /**
7143 * Construct a Style-specific RemoteViews for the collapsed notification layout.
7144 * The default implementation has nothing additional to add.
7145 *
7146 * @param increasedHeight true if this layout be created with an increased height.
7147 * @hide
7148 */
7149 public RemoteViews makeContentView(boolean increasedHeight) {
7150 return null;
7151 }
7152
7153 /**
7154 * Construct a Style-specific RemoteViews for the final big notification layout.
7155 * @hide
7156 */
7157 public RemoteViews makeBigContentView() {
7158 return null;
7159 }
7160
7161 /**
7162 * Construct a Style-specific RemoteViews for the final HUN layout.
7163 *
7164 * @param increasedHeight true if this layout be created with an increased height.
7165 * @hide
7166 */
7167 public RemoteViews makeHeadsUpContentView(boolean increasedHeight) {
7168 return null;
7169 }
7170
7171 /**
7172 * Apply any style-specific extras to this notification before shipping it out.
7173 * @hide
7174 */
7175 public void addExtras(Bundle extras) {
7176 if (mSummaryTextSet) {
7177 extras.putCharSequence(EXTRA_SUMMARY_TEXT, mSummaryText);
7178 }
7179 if (mBigContentTitle != null) {
7180 extras.putCharSequence(EXTRA_TITLE_BIG, mBigContentTitle);
7181 }
7182 extras.putString(EXTRA_TEMPLATE, this.getClass().getName());
7183 }
7184
7185 /**
7186 * Reconstruct the internal state of this Style object from extras.
7187 * @hide
7188 */
7189 protected void restoreFromExtras(Bundle extras) {
7190 if (extras.containsKey(EXTRA_SUMMARY_TEXT)) {
7191 mSummaryText = extras.getCharSequence(EXTRA_SUMMARY_TEXT);
7192 mSummaryTextSet = true;
7193 }
7194 if (extras.containsKey(EXTRA_TITLE_BIG)) {
7195 mBigContentTitle = extras.getCharSequence(EXTRA_TITLE_BIG);
7196 }
7197 }
7198
7199
7200 /**
7201 * @hide
7202 */
7203 public Notification buildStyled(Notification wip) {
7204 addExtras(wip.extras);
7205 return wip;
7206 }
7207
7208 /**
7209 * @hide
7210 */
7211 public void purgeResources() {}
7212
7213 /**
7214 * Calls {@link android.app.Notification.Builder#build()} on the Builder this Style is
7215 * attached to.
7216 *
7217 * @return the fully constructed Notification.
7218 */
7219 public Notification build() {
7220 checkBuilder();
7221 return mBuilder.build();
7222 }
7223
7224 /**
7225 * @hide
7226 * @return Whether we should put the summary be put into the notification header
7227 */
7228 public boolean hasSummaryInHeader() {
7229 return true;
7230 }
7231
7232 /**
7233 * @hide
7234 * @return Whether custom content views are displayed inline in the style
7235 */
7236 public boolean displayCustomViewInline() {
7237 return false;
7238 }
7239
7240 /**
7241 * Reduces the image sizes contained in this style.
7242 *
7243 * @hide
7244 */
7245 public void reduceImageSizes(Context context) {
7246 }
7247
7248 /**
7249 * Validate that this style was properly composed. This is called at build time.
7250 * @hide
7251 */
7252 public void validate(Context context) {
7253 }
7254
7255 /**
7256 * @hide
7257 */
7258 public abstract boolean areNotificationsVisiblyDifferent(Style other);
7259
7260 /**
7261 * @return the text that should be displayed in the statusBar when heads-upped.
7262 * If {@code null} is returned, the default implementation will be used.
7263 *
7264 * @hide
7265 */
7266 public CharSequence getHeadsUpStatusBarText() {
7267 return null;
7268 }
7269 }
7270
7271 /**
7272 * Helper class for generating large-format notifications that include a large image attachment.
7273 *
7274 * Here's how you'd set the <code>BigPictureStyle</code> on a notification:
7275 * <pre class="prettyprint">
7276 * Notification notif = new Notification.Builder(mContext)
7277 * .setContentTitle(&quot;New photo from &quot; + sender.toString())
7278 * .setContentText(subject)
7279 * .setSmallIcon(R.drawable.new_post)
7280 * .setLargeIcon(aBitmap)
7281 * .setStyle(new Notification.BigPictureStyle()
7282 * .bigPicture(aBigBitmap))
7283 * .build();
7284 * </pre>
7285 *
7286 * @see Notification#bigContentView
7287 */
7288 public static class BigPictureStyle extends Style {
7289 private Icon mPictureIcon;
7290 private Icon mBigLargeIcon;
7291 private boolean mBigLargeIconSet = false;
7292 private CharSequence mPictureContentDescription;
7293 private boolean mShowBigPictureWhenCollapsed;
7294
7295 public BigPictureStyle() {
7296 }
7297
7298 /**
7299 * @deprecated use {@code BigPictureStyle()}.
7300 */
7301 @Deprecated
7302 public BigPictureStyle(Builder builder) {
7303 setBuilder(builder);
7304 }
7305
7306 /**
7307 * Overrides ContentTitle in the big form of the template.
7308 * This defaults to the value passed to setContentTitle().
7309 */
7310 @NonNull
7311 public BigPictureStyle setBigContentTitle(@Nullable CharSequence title) {
7312 internalSetBigContentTitle(safeCharSequence(title));
7313 return this;
7314 }
7315
7316 /**
7317 * Set the first line of text after the detail section in the big form of the template.
7318 */
7319 @NonNull
7320 public BigPictureStyle setSummaryText(@Nullable CharSequence cs) {
7321 internalSetSummaryText(safeCharSequence(cs));
7322 return this;
7323 }
7324
7325 /**
7326 * Set the content description of the big picture.
7327 */
7328 @NonNull
7329 public BigPictureStyle setContentDescription(
7330 @Nullable CharSequence contentDescription) {
7331 mPictureContentDescription = contentDescription;
7332 return this;
7333 }
7334
7335 /**
7336 * @hide
7337 */
7338 @Nullable
7339 public Icon getBigPicture() {
7340 if (mPictureIcon != null) {
7341 return mPictureIcon;
7342 }
7343 return null;
7344 }
7345
7346 /**
7347 * Provide the bitmap to be used as the payload for the BigPicture notification.
7348 */
7349 @NonNull
7350 public BigPictureStyle bigPicture(@Nullable Bitmap b) {
7351 mPictureIcon = b == null ? null : Icon.createWithBitmap(b);
7352 return this;
7353 }
7354
7355 /**
7356 * Provide the content Uri to be used as the payload for the BigPicture notification.
7357 */
7358 @NonNull
7359 public BigPictureStyle bigPicture(@Nullable Icon icon) {
7360 mPictureIcon = icon;
7361 return this;
7362 }
7363
7364 /**
7365 * When set, the {@link #bigPicture(Bitmap) big picture} of this style will be promoted and
7366 * shown in place of the {@link Builder#setLargeIcon(Icon) large icon} in the collapsed
7367 * state of this notification.
7368 */
7369 @NonNull
7370 public BigPictureStyle showBigPictureWhenCollapsed(boolean show) {
7371 mShowBigPictureWhenCollapsed = show;
7372 return this;
7373 }
7374
7375 /**
7376 * Override the large icon when the big notification is shown.
7377 */
7378 @NonNull
7379 public BigPictureStyle bigLargeIcon(@Nullable Bitmap b) {
7380 return bigLargeIcon(b != null ? Icon.createWithBitmap(b) : null);
7381 }
7382
7383 /**
7384 * Override the large icon when the big notification is shown.
7385 */
7386 @NonNull
7387 public BigPictureStyle bigLargeIcon(@Nullable Icon icon) {
7388 mBigLargeIconSet = true;
7389 mBigLargeIcon = icon;
7390 return this;
7391 }
7392
7393 /** @hide */
7394 public static final int MIN_ASHMEM_BITMAP_SIZE = 128 * (1 << 10);
7395
7396 /**
7397 * @hide
7398 */
7399 @Override
7400 public void purgeResources() {
7401 super.purgeResources();
7402 if (mPictureIcon != null) {
7403 mPictureIcon.convertToAshmem();
7404 }
7405 if (mBigLargeIcon != null) {
7406 mBigLargeIcon.convertToAshmem();
7407 }
7408 }
7409
7410 /**
7411 * @hide
7412 */
7413 @Override
7414 public void reduceImageSizes(Context context) {
7415 super.reduceImageSizes(context);
7416 Resources resources = context.getResources();
7417 boolean isLowRam = ActivityManager.isLowRamDeviceStatic();
7418 if (mPictureIcon != null) {
7419 int maxPictureWidth = resources.getDimensionPixelSize(isLowRam
7420 ? R.dimen.notification_big_picture_max_height_low_ram
7421 : R.dimen.notification_big_picture_max_height);
7422 int maxPictureHeight = resources.getDimensionPixelSize(isLowRam
7423 ? R.dimen.notification_big_picture_max_width_low_ram
7424 : R.dimen.notification_big_picture_max_width);
7425 mPictureIcon.scaleDownIfNecessary(maxPictureWidth, maxPictureHeight);
7426 }
7427 if (mBigLargeIcon != null) {
7428 int rightIconSize = resources.getDimensionPixelSize(isLowRam
7429 ? R.dimen.notification_right_icon_size_low_ram
7430 : R.dimen.notification_right_icon_size);
7431 mBigLargeIcon.scaleDownIfNecessary(rightIconSize, rightIconSize);
7432 }
7433 }
7434
7435 /**
7436 * @hide
7437 */
7438 @Override
7439 public RemoteViews makeContentView(boolean increasedHeight) {
7440 if (mPictureIcon == null || !mShowBigPictureWhenCollapsed) {
7441 return super.makeContentView(increasedHeight);
7442 }
7443
7444 StandardTemplateParams p = mBuilder.mParams.reset()
7445 .viewType(StandardTemplateParams.VIEW_TYPE_NORMAL)
7446 .fillTextsFrom(mBuilder)
7447 .promotedPicture(mPictureIcon);
7448 return getStandardView(mBuilder.getBaseLayoutResource(), p, null /* result */);
7449 }
7450
7451 /**
7452 * @hide
7453 */
7454 @Override
7455 public RemoteViews makeHeadsUpContentView(boolean increasedHeight) {
7456 if (mPictureIcon == null || !mShowBigPictureWhenCollapsed) {
7457 return super.makeHeadsUpContentView(increasedHeight);
7458 }
7459
7460 StandardTemplateParams p = mBuilder.mParams.reset()
7461 .viewType(StandardTemplateParams.VIEW_TYPE_HEADS_UP)
7462 .fillTextsFrom(mBuilder)
7463 .promotedPicture(mPictureIcon);
7464 return getStandardView(mBuilder.getHeadsUpBaseLayoutResource(), p, null /* result */);
7465 }
7466
7467 /**
7468 * @hide
7469 */
7470 public RemoteViews makeBigContentView() {
7471 // Replace mN.mLargeIcon with mBigLargeIcon if mBigLargeIconSet
7472 // This covers the following cases:
7473 // 1. mBigLargeIconSet -> mBigLargeIcon (null or non-null) applies, overrides
7474 // mN.mLargeIcon
7475 // 2. !mBigLargeIconSet -> mN.mLargeIcon applies
7476 Icon oldLargeIcon = null;
7477 Bitmap largeIconLegacy = null;
7478 if (mBigLargeIconSet) {
7479 oldLargeIcon = mBuilder.mN.mLargeIcon;
7480 mBuilder.mN.mLargeIcon = mBigLargeIcon;
7481 // The legacy largeIcon might not allow us to clear the image, as it's taken in
7482 // replacement if the other one is null. Because we're restoring these legacy icons
7483 // for old listeners, this is in general non-null.
7484 largeIconLegacy = mBuilder.mN.largeIcon;
7485 mBuilder.mN.largeIcon = null;
7486 }
7487
7488 StandardTemplateParams p = mBuilder.mParams.reset()
7489 .viewType(StandardTemplateParams.VIEW_TYPE_BIG).fillTextsFrom(mBuilder);
7490 RemoteViews contentView = getStandardView(mBuilder.getBigPictureLayoutResource(),
7491 p, null /* result */);
7492 if (mSummaryTextSet) {
7493 contentView.setTextViewText(R.id.text, mBuilder.processTextSpans(
7494 mBuilder.processLegacyText(mSummaryText)));
7495 mBuilder.setTextViewColorSecondary(contentView, R.id.text, p);
7496 contentView.setViewVisibility(R.id.text, View.VISIBLE);
7497 }
7498
7499 if (mBigLargeIconSet) {
7500 mBuilder.mN.mLargeIcon = oldLargeIcon;
7501 mBuilder.mN.largeIcon = largeIconLegacy;
7502 }
7503
7504 contentView.setImageViewIcon(R.id.big_picture, mPictureIcon);
7505
7506 if (mPictureContentDescription != null) {
7507 contentView.setContentDescription(R.id.big_picture, mPictureContentDescription);
7508 }
7509
7510 return contentView;
7511 }
7512
7513 /**
7514 * @hide
7515 */
7516 public void addExtras(Bundle extras) {
7517 super.addExtras(extras);
7518
7519 if (mBigLargeIconSet) {
7520 extras.putParcelable(EXTRA_LARGE_ICON_BIG, mBigLargeIcon);
7521 }
7522 if (mPictureContentDescription != null) {
7523 extras.putCharSequence(EXTRA_PICTURE_CONTENT_DESCRIPTION,
7524 mPictureContentDescription);
7525 }
7526 extras.putBoolean(EXTRA_SHOW_BIG_PICTURE_WHEN_COLLAPSED, mShowBigPictureWhenCollapsed);
7527
7528 // If the icon contains a bitmap, use the old extra so that listeners which look for
7529 // that extra can still find the picture. Don't include the new extra in that case,
7530 // to avoid duplicating data.
7531 if (mPictureIcon != null && mPictureIcon.getType() == Icon.TYPE_BITMAP) {
7532 extras.putParcelable(EXTRA_PICTURE, mPictureIcon.getBitmap());
7533 extras.putParcelable(EXTRA_PICTURE_ICON, null);
7534 } else {
7535 extras.putParcelable(EXTRA_PICTURE, null);
7536 extras.putParcelable(EXTRA_PICTURE_ICON, mPictureIcon);
7537 }
7538 }
7539
7540 /**
7541 * @hide
7542 */
7543 @Override
7544 protected void restoreFromExtras(Bundle extras) {
7545 super.restoreFromExtras(extras);
7546
7547 if (extras.containsKey(EXTRA_LARGE_ICON_BIG)) {
7548 mBigLargeIconSet = true;
7549 mBigLargeIcon = extras.getParcelable(EXTRA_LARGE_ICON_BIG, Icon.class);
7550 }
7551
7552 if (extras.containsKey(EXTRA_PICTURE_CONTENT_DESCRIPTION)) {
7553 mPictureContentDescription =
7554 extras.getCharSequence(EXTRA_PICTURE_CONTENT_DESCRIPTION);
7555 }
7556
7557 mShowBigPictureWhenCollapsed = extras.getBoolean(EXTRA_SHOW_BIG_PICTURE_WHEN_COLLAPSED);
7558
7559 mPictureIcon = getPictureIcon(extras);
7560 }
7561
7562 /** @hide */
7563 @Nullable
7564 public static Icon getPictureIcon(@Nullable Bundle extras) {
7565 if (extras == null) return null;
7566 // When this style adds a picture, we only add one of the keys. If both were added,
7567 // it would most likely be a legacy app trying to override the picture in some way.
7568 // Because of that case it's better to give precedence to the legacy field.
7569 Bitmap bitmapPicture = extras.getParcelable(EXTRA_PICTURE, Bitmap.class);
7570 if (bitmapPicture != null) {
7571 return Icon.createWithBitmap(bitmapPicture);
7572 } else {
7573 return extras.getParcelable(EXTRA_PICTURE_ICON, Icon.class);
7574 }
7575 }
7576
7577 /**
7578 * @hide
7579 */
7580 @Override
7581 public boolean hasSummaryInHeader() {
7582 return false;
7583 }
7584
7585 /**
7586 * @hide
7587 * Note that we aren't actually comparing the contents of the bitmaps here, so this
7588 * is only doing a cursory inspection. Bitmaps of equal size will appear the same.
7589 */
7590 @Override
7591 public boolean areNotificationsVisiblyDifferent(Style other) {
7592 if (other == null || getClass() != other.getClass()) {
7593 return true;
7594 }
7595 BigPictureStyle otherS = (BigPictureStyle) other;
7596 return areIconsObviouslyDifferent(getBigPicture(), otherS.getBigPicture());
7597 }
7598
7599 private static boolean areIconsObviouslyDifferent(Icon a, Icon b) {
7600 if (a == b) {
7601 return false;
7602 }
7603 if (a == null || b == null) {
7604 return true;
7605 }
7606 if (a.sameAs(b)) {
7607 return false;
7608 }
7609 final int aType = a.getType();
7610 if (aType != b.getType()) {
7611 return true;
7612 }
7613 if (aType == Icon.TYPE_BITMAP || aType == Icon.TYPE_ADAPTIVE_BITMAP) {
7614 final Bitmap aBitmap = a.getBitmap();
7615 final Bitmap bBitmap = b.getBitmap();
7616 return aBitmap.getWidth() != bBitmap.getWidth()
7617 || aBitmap.getHeight() != bBitmap.getHeight()
7618 || aBitmap.getConfig() != bBitmap.getConfig()
7619 || aBitmap.getGenerationId() != bBitmap.getGenerationId();
7620 }
7621 return true;
7622 }
7623 }
7624
7625 /**
7626 * Helper class for generating large-format notifications that include a lot of text.
7627 *
7628 * Here's how you'd set the <code>BigTextStyle</code> on a notification:
7629 * <pre class="prettyprint">
7630 * Notification notif = new Notification.Builder(mContext)
7631 * .setContentTitle(&quot;New mail from &quot; + sender.toString())
7632 * .setContentText(subject)
7633 * .setSmallIcon(R.drawable.new_mail)
7634 * .setLargeIcon(aBitmap)
7635 * .setStyle(new Notification.BigTextStyle()
7636 * .bigText(aVeryLongString))
7637 * .build();
7638 * </pre>
7639 *
7640 * @see Notification#bigContentView
7641 */
7642 public static class BigTextStyle extends Style {
7643
7644 private CharSequence mBigText;
7645
7646 public BigTextStyle() {
7647 }
7648
7649 /**
7650 * @deprecated use {@code BigTextStyle()}.
7651 */
7652 @Deprecated
7653 public BigTextStyle(Builder builder) {
7654 setBuilder(builder);
7655 }
7656
7657 /**
7658 * Overrides ContentTitle in the big form of the template.
7659 * This defaults to the value passed to setContentTitle().
7660 */
7661 public BigTextStyle setBigContentTitle(CharSequence title) {
7662 internalSetBigContentTitle(safeCharSequence(title));
7663 return this;
7664 }
7665
7666 /**
7667 * Set the first line of text after the detail section in the big form of the template.
7668 */
7669 public BigTextStyle setSummaryText(CharSequence cs) {
7670 internalSetSummaryText(safeCharSequence(cs));
7671 return this;
7672 }
7673
7674 /**
7675 * Provide the longer text to be displayed in the big form of the
7676 * template in place of the content text.
7677 */
7678 public BigTextStyle bigText(CharSequence cs) {
7679 mBigText = safeCharSequence(cs);
7680 return this;
7681 }
7682
7683 /**
7684 * @hide
7685 */
7686 public CharSequence getBigText() {
7687 return mBigText;
7688 }
7689
7690 /**
7691 * @hide
7692 */
7693 public void addExtras(Bundle extras) {
7694 super.addExtras(extras);
7695
7696 extras.putCharSequence(EXTRA_BIG_TEXT, mBigText);
7697 }
7698
7699 /**
7700 * @hide
7701 */
7702 @Override
7703 protected void restoreFromExtras(Bundle extras) {
7704 super.restoreFromExtras(extras);
7705
7706 mBigText = extras.getCharSequence(EXTRA_BIG_TEXT);
7707 }
7708
7709 /**
7710 * @param increasedHeight true if this layout be created with an increased height.
7711 *
7712 * @hide
7713 */
7714 @Override
7715 public RemoteViews makeContentView(boolean increasedHeight) {
7716 if (increasedHeight) {
7717 ArrayList<Action> originalActions = mBuilder.mActions;
7718 mBuilder.mActions = new ArrayList<>();
7719 RemoteViews remoteViews = makeBigContentView();
7720 mBuilder.mActions = originalActions;
7721 return remoteViews;
7722 }
7723 return super.makeContentView(increasedHeight);
7724 }
7725
7726 /**
7727 * @hide
7728 */
7729 @Override
7730 public RemoteViews makeHeadsUpContentView(boolean increasedHeight) {
7731 if (increasedHeight && mBuilder.mActions.size() > 0) {
7732 // TODO(b/163626038): pass VIEW_TYPE_HEADS_UP?
7733 return makeBigContentView();
7734 }
7735 return super.makeHeadsUpContentView(increasedHeight);
7736 }
7737
7738 /**
7739 * @hide
7740 */
7741 public RemoteViews makeBigContentView() {
7742 StandardTemplateParams p = mBuilder.mParams.reset()
7743 .viewType(StandardTemplateParams.VIEW_TYPE_BIG)
7744 .allowTextWithProgress(true)
7745 .textViewId(R.id.big_text)
7746 .fillTextsFrom(mBuilder);
7747
7748 // Replace the text with the big text, but only if the big text is not empty.
7749 CharSequence bigTextText = mBuilder.processLegacyText(mBigText);
7750 if (!TextUtils.isEmpty(bigTextText)) {
7751 p.text(bigTextText);
7752 }
7753
7754 return getStandardView(mBuilder.getBigTextLayoutResource(), p, null /* result */);
7755 }
7756
7757 /**
7758 * @hide
7759 * Spans are ignored when comparing text for visual difference.
7760 */
7761 @Override
7762 public boolean areNotificationsVisiblyDifferent(Style other) {
7763 if (other == null || getClass() != other.getClass()) {
7764 return true;
7765 }
7766 BigTextStyle newS = (BigTextStyle) other;
7767 return !Objects.equals(String.valueOf(getBigText()), String.valueOf(newS.getBigText()));
7768 }
7769
7770 }
7771
7772 /**
7773 * Helper class for generating large-format notifications that include multiple back-and-forth
7774 * messages of varying types between any number of people.
7775 *
7776 * <p>
7777 * If the platform does not provide large-format notifications, this method has no effect. The
7778 * user will always see the normal notification view.
7779 *
7780 * <p>
7781 * If the app is targeting Android {@link android.os.Build.VERSION_CODES#P} and above, it is
7782 * required to use the {@link Person} class in order to get an optimal rendering of the
7783 * notification and its avatars. For conversations involving multiple people, the app should
7784 * also make sure that it marks the conversation as a group with
7785 * {@link #setGroupConversation(boolean)}.
7786 *
7787 * <p>
7788 * This class is a "rebuilder": It attaches to a Builder object and modifies its behavior.
7789 * Here's an example of how this may be used:
7790 * <pre class="prettyprint">
7791 *
7792 * Person user = new Person.Builder().setIcon(userIcon).setName(userName).build();
7793 * MessagingStyle style = new MessagingStyle(user)
7794 * .addMessage(messages[1].getText(), messages[1].getTime(), messages[1].getPerson())
7795 * .addMessage(messages[2].getText(), messages[2].getTime(), messages[2].getPerson())
7796 * .setGroupConversation(hasMultiplePeople());
7797 *
7798 * Notification noti = new Notification.Builder()
7799 * .setContentTitle(&quot;2 new messages with &quot; + sender.toString())
7800 * .setContentText(subject)
7801 * .setSmallIcon(R.drawable.new_message)
7802 * .setLargeIcon(aBitmap)
7803 * .setStyle(style)
7804 * .build();
7805 * </pre>
7806 */
7807 public static class MessagingStyle extends Style {
7808
7809 /**
7810 * The maximum number of messages that will be retained in the Notification itself (the
7811 * number displayed is up to the platform).
7812 */
7813 public static final int MAXIMUM_RETAINED_MESSAGES = 25;
7814
7815
7816 /** @hide */
7817 public static final int CONVERSATION_TYPE_LEGACY = 0;
7818 /** @hide */
7819 public static final int CONVERSATION_TYPE_NORMAL = 1;
7820 /** @hide */
7821 public static final int CONVERSATION_TYPE_IMPORTANT = 2;
7822
7823 /** @hide */
7824 @IntDef(prefix = {"CONVERSATION_TYPE_"}, value = {
7825 CONVERSATION_TYPE_LEGACY, CONVERSATION_TYPE_NORMAL, CONVERSATION_TYPE_IMPORTANT
7826 })
7827 @Retention(RetentionPolicy.SOURCE)
7828 public @interface ConversationType {}
7829
7830 @NonNull Person mUser;
7831 @Nullable CharSequence mConversationTitle;
7832 @Nullable Icon mShortcutIcon;
7833 List<Message> mMessages = new ArrayList<>();
7834 List<Message> mHistoricMessages = new ArrayList<>();
7835 boolean mIsGroupConversation;
7836 @ConversationType int mConversationType = CONVERSATION_TYPE_LEGACY;
7837 int mUnreadMessageCount;
7838
7839 MessagingStyle() {
7840 }
7841
7842 /**
7843 * @param userDisplayName Required - the name to be displayed for any replies sent by the
7844 * user before the posting app reposts the notification with those messages after they've
7845 * been actually sent and in previous messages sent by the user added in
7846 * {@link #addMessage(Notification.MessagingStyle.Message)}
7847 *
7848 * @deprecated use {@code MessagingStyle(Person)}
7849 */
7850 public MessagingStyle(@NonNull CharSequence userDisplayName) {
7851 this(new Person.Builder().setName(userDisplayName).build());
7852 }
7853
7854 /**
7855 * @param user Required - The person displayed for any messages that are sent by the
7856 * user. Any messages added with {@link #addMessage(Notification.MessagingStyle.Message)}
7857 * who don't have a Person associated with it will be displayed as if they were sent
7858 * by this user. The user also needs to have a valid name associated with it, which is
7859 * enforced starting in Android {@link android.os.Build.VERSION_CODES#P}.
7860 */
7861 public MessagingStyle(@NonNull Person user) {
7862 mUser = user;
7863 }
7864
7865 /**
7866 * Validate that this style was properly composed. This is called at build time.
7867 * @hide
7868 */
7869 @Override
7870 public void validate(Context context) {
7871 super.validate(context);
7872 if (context.getApplicationInfo().targetSdkVersion
7873 >= Build.VERSION_CODES.P && (mUser == null || mUser.getName() == null)) {
7874 throw new RuntimeException("User must be valid and have a name.");
7875 }
7876 }
7877
7878 /**
7879 * @return the text that should be displayed in the statusBar when heads upped.
7880 * If {@code null} is returned, the default implementation will be used.
7881 *
7882 * @hide
7883 */
7884 @Override
7885 public CharSequence getHeadsUpStatusBarText() {
7886 CharSequence conversationTitle = !TextUtils.isEmpty(super.mBigContentTitle)
7887 ? super.mBigContentTitle
7888 : mConversationTitle;
7889 if (mConversationType == CONVERSATION_TYPE_LEGACY
7890 && !TextUtils.isEmpty(conversationTitle) && !hasOnlyWhiteSpaceSenders()) {
7891 return conversationTitle;
7892 }
7893 return null;
7894 }
7895
7896 /**
7897 * @return the user to be displayed for any replies sent by the user
7898 */
7899 @NonNull
7900 public Person getUser() {
7901 return mUser;
7902 }
7903
7904 /**
7905 * Returns the name to be displayed for any replies sent by the user
7906 *
7907 * @deprecated use {@link #getUser()} instead
7908 */
7909 public CharSequence getUserDisplayName() {
7910 return mUser.getName();
7911 }
7912
7913 /**
7914 * Sets the title to be displayed on this conversation. May be set to {@code null}.
7915 *
7916 * <p>Starting in {@link Build.VERSION_CODES#R}, this conversation title will be ignored
7917 * if a valid shortcutId is added via {@link Notification.Builder#setShortcutId(String)}.
7918 * In this case, {@link ShortcutInfo#getLongLabel()} (or, if missing,
7919 * {@link ShortcutInfo#getShortLabel()}) will be shown as the conversation title
7920 * instead.
7921 *
7922 * <p>This API's behavior was changed in SDK version {@link Build.VERSION_CODES#P}. If your
7923 * application's target version is less than {@link Build.VERSION_CODES#P}, setting a
7924 * conversation title to a non-null value will make {@link #isGroupConversation()} return
7925 * {@code true} and passing {@code null} will make it return {@code false}. In
7926 * {@link Build.VERSION_CODES#P} and beyond, use {@link #setGroupConversation(boolean)}
7927 * to set group conversation status.
7928 *
7929 * @param conversationTitle Title displayed for this conversation
7930 * @return this object for method chaining
7931 */
7932 public MessagingStyle setConversationTitle(@Nullable CharSequence conversationTitle) {
7933 mConversationTitle = conversationTitle;
7934 return this;
7935 }
7936
7937 /**
7938 * Return the title to be displayed on this conversation. May return {@code null}.
7939 */
7940 @Nullable
7941 public CharSequence getConversationTitle() {
7942 return mConversationTitle;
7943 }
7944
7945 /**
7946 * Sets the icon to be displayed on the conversation, derived from the shortcutId.
7947 *
7948 * @hide
7949 */
7950 public MessagingStyle setShortcutIcon(@Nullable Icon conversationIcon) {
7951 // TODO(b/228941516): This icon should be downscaled to avoid using too much memory,
7952 // see reduceImageSizes.
7953 mShortcutIcon = conversationIcon;
7954 return this;
7955 }
7956
7957 /**
7958 * Return the icon to be displayed on this conversation, derived from the shortcutId. May
7959 * return {@code null}.
7960 *
7961 * @hide
7962 */
7963 @Nullable
7964 public Icon getShortcutIcon() {
7965 return mShortcutIcon;
7966 }
7967
7968 /**
7969 * Sets the conversation type of this MessageStyle notification.
7970 * {@link #CONVERSATION_TYPE_LEGACY} will use the "older" layout from pre-R,
7971 * {@link #CONVERSATION_TYPE_NORMAL} will use the new "conversation" layout, and
7972 * {@link #CONVERSATION_TYPE_IMPORTANT} will add additional "important" treatments.
7973 *
7974 * @hide
7975 */
7976 public MessagingStyle setConversationType(@ConversationType int conversationType) {
7977 mConversationType = conversationType;
7978 return this;
7979 }
7980
7981 /** @hide */
7982 @ConversationType
7983 public int getConversationType() {
7984 return mConversationType;
7985 }
7986
7987 /** @hide */
7988 public int getUnreadMessageCount() {
7989 return mUnreadMessageCount;
7990 }
7991
7992 /** @hide */
7993 public MessagingStyle setUnreadMessageCount(int unreadMessageCount) {
7994 mUnreadMessageCount = unreadMessageCount;
7995 return this;
7996 }
7997
7998 /**
7999 * Adds a message for display by this notification. Convenience call for a simple
8000 * {@link Message} in {@link #addMessage(Notification.MessagingStyle.Message)}.
8001 * @param text A {@link CharSequence} to be displayed as the message content
8002 * @param timestamp Time in milliseconds at which the message arrived
8003 * @param sender A {@link CharSequence} to be used for displaying the name of the
8004 * sender. Should be <code>null</code> for messages by the current user, in which case
8005 * the platform will insert {@link #getUserDisplayName()}.
8006 * Should be unique amongst all individuals in the conversation, and should be
8007 * consistent during re-posts of the notification.
8008 *
8009 * @see Message#Message(CharSequence, long, CharSequence)
8010 *
8011 * @return this object for method chaining
8012 *
8013 * @deprecated use {@link #addMessage(CharSequence, long, Person)}
8014 */
8015 public MessagingStyle addMessage(CharSequence text, long timestamp, CharSequence sender) {
8016 return addMessage(text, timestamp,
8017 sender == null ? null : new Person.Builder().setName(sender).build());
8018 }
8019
8020 /**
8021 * Adds a message for display by this notification. Convenience call for a simple
8022 * {@link Message} in {@link #addMessage(Notification.MessagingStyle.Message)}.
8023 * @param text A {@link CharSequence} to be displayed as the message content
8024 * @param timestamp Time in milliseconds at which the message arrived
8025 * @param sender The {@link Person} who sent the message.
8026 * Should be <code>null</code> for messages by the current user, in which case
8027 * the platform will insert the user set in {@code MessagingStyle(Person)}.
8028 *
8029 * @see Message#Message(CharSequence, long, CharSequence)
8030 *
8031 * @return this object for method chaining
8032 */
8033 public MessagingStyle addMessage(@NonNull CharSequence text, long timestamp,
8034 @Nullable Person sender) {
8035 return addMessage(new Message(text, timestamp, sender));
8036 }
8037
8038 /**
8039 * Adds a {@link Message} for display in this notification.
8040 *
8041 * <p>The messages should be added in chronologic order, i.e. the oldest first,
8042 * the newest last.
8043 *
8044 * @param message The {@link Message} to be displayed
8045 * @return this object for method chaining
8046 */
8047 public MessagingStyle addMessage(Message message) {
8048 mMessages.add(message);
8049 if (mMessages.size() > MAXIMUM_RETAINED_MESSAGES) {
8050 mMessages.remove(0);
8051 }
8052 return this;
8053 }
8054
8055 /**
8056 * Adds a {@link Message} for historic context in this notification.
8057 *
8058 * <p>Messages should be added as historic if they are not the main subject of the
8059 * notification but may give context to a conversation. The system may choose to present
8060 * them only when relevant, e.g. when replying to a message through a {@link RemoteInput}.
8061 *
8062 * <p>The messages should be added in chronologic order, i.e. the oldest first,
8063 * the newest last.
8064 *
8065 * @param message The historic {@link Message} to be added
8066 * @return this object for method chaining
8067 */
8068 public MessagingStyle addHistoricMessage(Message message) {
8069 mHistoricMessages.add(message);
8070 if (mHistoricMessages.size() > MAXIMUM_RETAINED_MESSAGES) {
8071 mHistoricMessages.remove(0);
8072 }
8073 return this;
8074 }
8075
8076 /**
8077 * Gets the list of {@code Message} objects that represent the notification.
8078 */
8079 public List<Message> getMessages() {
8080 return mMessages;
8081 }
8082
8083 /**
8084 * Gets the list of historic {@code Message}s in the notification.
8085 */
8086 public List<Message> getHistoricMessages() {
8087 return mHistoricMessages;
8088 }
8089
8090 /**
8091 * Sets whether this conversation notification represents a group. If the app is targeting
8092 * Android P, this is required if the app wants to display the largeIcon set with
8093 * {@link Notification.Builder#setLargeIcon(Bitmap)}, otherwise it will be hidden.
8094 *
8095 * @param isGroupConversation {@code true} if the conversation represents a group,
8096 * {@code false} otherwise.
8097 * @return this object for method chaining
8098 */
8099 public MessagingStyle setGroupConversation(boolean isGroupConversation) {
8100 mIsGroupConversation = isGroupConversation;
8101 return this;
8102 }
8103
8104 /**
8105 * Returns {@code true} if this notification represents a group conversation, otherwise
8106 * {@code false}.
8107 *
8108 * <p> If the application that generated this {@link MessagingStyle} targets an SDK version
8109 * less than {@link Build.VERSION_CODES#P}, this method becomes dependent on whether or
8110 * not the conversation title is set; returning {@code true} if the conversation title is
8111 * a non-null value, or {@code false} otherwise. From {@link Build.VERSION_CODES#P} forward,
8112 * this method returns what's set by {@link #setGroupConversation(boolean)} allowing for
8113 * named, non-group conversations.
8114 *
8115 * @see #setConversationTitle(CharSequence)
8116 */
8117 public boolean isGroupConversation() {
8118 // When target SDK version is < P, a non-null conversation title dictates if this is
8119 // as group conversation.
8120 if (mBuilder != null
8121 && mBuilder.mContext.getApplicationInfo().targetSdkVersion
8122 < Build.VERSION_CODES.P) {
8123 return mConversationTitle != null;
8124 }
8125
8126 return mIsGroupConversation;
8127 }
8128
8129 /**
8130 * @hide
8131 */
8132 @Override
8133 public void addExtras(Bundle extras) {
8134 super.addExtras(extras);
8135 if (mUser != null) {
8136 // For legacy usages
8137 extras.putCharSequence(EXTRA_SELF_DISPLAY_NAME, mUser.getName());
8138 extras.putParcelable(EXTRA_MESSAGING_PERSON, mUser);
8139 }
8140 if (mConversationTitle != null) {
8141 extras.putCharSequence(EXTRA_CONVERSATION_TITLE, mConversationTitle);
8142 }
8143 if (!mMessages.isEmpty()) { extras.putParcelableArray(EXTRA_MESSAGES,
8144 Message.getBundleArrayForMessages(mMessages));
8145 }
8146 if (!mHistoricMessages.isEmpty()) { extras.putParcelableArray(EXTRA_HISTORIC_MESSAGES,
8147 Message.getBundleArrayForMessages(mHistoricMessages));
8148 }
8149 if (mShortcutIcon != null) {
8150 extras.putParcelable(EXTRA_CONVERSATION_ICON, mShortcutIcon);
8151 }
8152 extras.putInt(EXTRA_CONVERSATION_UNREAD_MESSAGE_COUNT, mUnreadMessageCount);
8153
8154 fixTitleAndTextExtras(extras);
8155 extras.putBoolean(EXTRA_IS_GROUP_CONVERSATION, mIsGroupConversation);
8156 }
8157
8158 private void fixTitleAndTextExtras(Bundle extras) {
8159 Message m = findLatestIncomingMessage();
8160 CharSequence text = (m == null) ? null : m.mText;
8161 CharSequence sender = m == null ? null
8162 : m.mSender == null || TextUtils.isEmpty(m.mSender.getName())
8163 ? mUser.getName() : m.mSender.getName();
8164 CharSequence title;
8165 if (!TextUtils.isEmpty(mConversationTitle)) {
8166 if (!TextUtils.isEmpty(sender)) {
8167 BidiFormatter bidi = BidiFormatter.getInstance();
8168 title = mBuilder.mContext.getString(
8169 com.android.internal.R.string.notification_messaging_title_template,
8170 bidi.unicodeWrap(mConversationTitle), bidi.unicodeWrap(sender));
8171 } else {
8172 title = mConversationTitle;
8173 }
8174 } else {
8175 title = sender;
8176 }
8177
8178 if (title != null) {
8179 extras.putCharSequence(EXTRA_TITLE, title);
8180 }
8181 if (text != null) {
8182 extras.putCharSequence(EXTRA_TEXT, text);
8183 }
8184 }
8185
8186 /**
8187 * @hide
8188 */
8189 @Override
8190 protected void restoreFromExtras(Bundle extras) {
8191 super.restoreFromExtras(extras);
8192
8193 mUser = extras.getParcelable(EXTRA_MESSAGING_PERSON, Person.class);
8194 if (mUser == null) {
8195 CharSequence displayName = extras.getCharSequence(EXTRA_SELF_DISPLAY_NAME);
8196 mUser = new Person.Builder().setName(displayName).build();
8197 }
8198 mConversationTitle = extras.getCharSequence(EXTRA_CONVERSATION_TITLE);
8199 Parcelable[] messages = extras.getParcelableArray(EXTRA_MESSAGES);
8200 mMessages = Message.getMessagesFromBundleArray(messages);
8201 Parcelable[] histMessages = extras.getParcelableArray(EXTRA_HISTORIC_MESSAGES);
8202 mHistoricMessages = Message.getMessagesFromBundleArray(histMessages);
8203 mIsGroupConversation = extras.getBoolean(EXTRA_IS_GROUP_CONVERSATION);
8204 mUnreadMessageCount = extras.getInt(EXTRA_CONVERSATION_UNREAD_MESSAGE_COUNT);
8205 mShortcutIcon = extras.getParcelable(EXTRA_CONVERSATION_ICON, Icon.class);
8206 }
8207
8208 /**
8209 * @hide
8210 */
8211 @Override
8212 public RemoteViews makeContentView(boolean increasedHeight) {
8213 // All messaging templates contain the actions
8214 ArrayList<Action> originalActions = mBuilder.mActions;
8215 try {
8216 mBuilder.mActions = new ArrayList<>();
8217 return makeMessagingView(StandardTemplateParams.VIEW_TYPE_NORMAL);
8218 } finally {
8219 mBuilder.mActions = originalActions;
8220 }
8221 }
8222
8223 /**
8224 * @hide
8225 * Spans are ignored when comparing text for visual difference.
8226 */
8227 @Override
8228 public boolean areNotificationsVisiblyDifferent(Style other) {
8229 if (other == null || getClass() != other.getClass()) {
8230 return true;
8231 }
8232 MessagingStyle newS = (MessagingStyle) other;
8233 List<MessagingStyle.Message> oldMs = getMessages();
8234 List<MessagingStyle.Message> newMs = newS.getMessages();
8235
8236 if (oldMs == null || newMs == null) {
8237 newMs = new ArrayList<>();
8238 }
8239
8240 int n = oldMs.size();
8241 if (n != newMs.size()) {
8242 return true;
8243 }
8244 for (int i = 0; i < n; i++) {
8245 MessagingStyle.Message oldM = oldMs.get(i);
8246 MessagingStyle.Message newM = newMs.get(i);
8247 if (!Objects.equals(
8248 String.valueOf(oldM.getText()),
8249 String.valueOf(newM.getText()))) {
8250 return true;
8251 }
8252 if (!Objects.equals(oldM.getDataUri(), newM.getDataUri())) {
8253 return true;
8254 }
8255 String oldSender = String.valueOf(oldM.getSenderPerson() == null
8256 ? oldM.getSender()
8257 : oldM.getSenderPerson().getName());
8258 String newSender = String.valueOf(newM.getSenderPerson() == null
8259 ? newM.getSender()
8260 : newM.getSenderPerson().getName());
8261 if (!Objects.equals(oldSender, newSender)) {
8262 return true;
8263 }
8264
8265 String oldKey = oldM.getSenderPerson() == null
8266 ? null : oldM.getSenderPerson().getKey();
8267 String newKey = newM.getSenderPerson() == null
8268 ? null : newM.getSenderPerson().getKey();
8269 if (!Objects.equals(oldKey, newKey)) {
8270 return true;
8271 }
8272 // Other fields (like timestamp) intentionally excluded
8273 }
8274 return false;
8275 }
8276
8277 private Message findLatestIncomingMessage() {
8278 return findLatestIncomingMessage(mMessages);
8279 }
8280
8281 /**
8282 * @hide
8283 */
8284 @Nullable
8285 public static Message findLatestIncomingMessage(
8286 List<Message> messages) {
8287 for (int i = messages.size() - 1; i >= 0; i--) {
8288 Message m = messages.get(i);
8289 // Incoming messages have a non-empty sender.
8290 if (m.mSender != null && !TextUtils.isEmpty(m.mSender.getName())) {
8291 return m;
8292 }
8293 }
8294 if (!messages.isEmpty()) {
8295 // No incoming messages, fall back to outgoing message
8296 return messages.get(messages.size() - 1);
8297 }
8298 return null;
8299 }
8300
8301 /**
8302 * @hide
8303 */
8304 @Override
8305 public RemoteViews makeBigContentView() {
8306 return makeMessagingView(StandardTemplateParams.VIEW_TYPE_BIG);
8307 }
8308
8309 /**
8310 * Create a messaging layout.
8311 *
8312 * @param viewType one of StandardTemplateParams.VIEW_TYPE_NORMAL, VIEW_TYPE_BIG,
8313 * VIEW_TYPE_HEADS_UP
8314 * @return the created remoteView.
8315 */
8316 @NonNull
8317 private RemoteViews makeMessagingView(int viewType) {
8318 boolean isCollapsed = viewType != StandardTemplateParams.VIEW_TYPE_BIG;
8319 boolean hideRightIcons = viewType != StandardTemplateParams.VIEW_TYPE_NORMAL;
8320 boolean isConversationLayout = mConversationType != CONVERSATION_TYPE_LEGACY;
8321 boolean isImportantConversation = mConversationType == CONVERSATION_TYPE_IMPORTANT;
8322 boolean isHeaderless = !isConversationLayout && isCollapsed;
8323
8324 CharSequence conversationTitle = !TextUtils.isEmpty(super.mBigContentTitle)
8325 ? super.mBigContentTitle
8326 : mConversationTitle;
8327 boolean atLeastP = mBuilder.mContext.getApplicationInfo().targetSdkVersion
8328 >= Build.VERSION_CODES.P;
8329 boolean isOneToOne;
8330 CharSequence nameReplacement = null;
8331 if (!atLeastP) {
8332 isOneToOne = TextUtils.isEmpty(conversationTitle);
8333 if (hasOnlyWhiteSpaceSenders()) {
8334 isOneToOne = true;
8335 nameReplacement = conversationTitle;
8336 conversationTitle = null;
8337 }
8338 } else {
8339 isOneToOne = !isGroupConversation();
8340 }
8341 if (isHeaderless && isOneToOne && TextUtils.isEmpty(conversationTitle)) {
8342 conversationTitle = getOtherPersonName();
8343 }
8344
8345 Icon largeIcon = mBuilder.mN.mLargeIcon;
8346 TemplateBindResult bindResult = new TemplateBindResult();
8347 StandardTemplateParams p = mBuilder.mParams.reset()
8348 .viewType(viewType)
8349 .highlightExpander(isConversationLayout)
8350 .hideProgress(true)
8351 .title(isHeaderless ? conversationTitle : null)
8352 .text(null)
8353 .hideLeftIcon(isOneToOne)
8354 .hideRightIcon(hideRightIcons || isOneToOne)
8355 .headerTextSecondary(isHeaderless ? null : conversationTitle);
8356 RemoteViews contentView = mBuilder.applyStandardTemplateWithActions(
8357 isConversationLayout
8358 ? mBuilder.getConversationLayoutResource()
8359 : isCollapsed
8360 ? mBuilder.getMessagingLayoutResource()
8361 : mBuilder.getBigMessagingLayoutResource(),
8362 p,
8363 bindResult);
8364 if (isConversationLayout) {
8365 mBuilder.setTextViewColorPrimary(contentView, R.id.conversation_text, p);
8366 mBuilder.setTextViewColorSecondary(contentView, R.id.app_name_divider, p);
8367 }
8368
8369 addExtras(mBuilder.mN.extras);
8370 contentView.setInt(R.id.status_bar_latest_event_content, "setLayoutColor",
8371 mBuilder.getSmallIconColor(p));
8372 contentView.setInt(R.id.status_bar_latest_event_content, "setSenderTextColor",
8373 mBuilder.getPrimaryTextColor(p));
8374 contentView.setInt(R.id.status_bar_latest_event_content, "setMessageTextColor",
8375 mBuilder.getSecondaryTextColor(p));
8376 contentView.setInt(R.id.status_bar_latest_event_content,
8377 "setNotificationBackgroundColor",
8378 mBuilder.getBackgroundColor(p));
8379 contentView.setBoolean(R.id.status_bar_latest_event_content, "setIsCollapsed",
8380 isCollapsed);
8381 contentView.setIcon(R.id.status_bar_latest_event_content, "setAvatarReplacement",
8382 mBuilder.mN.mLargeIcon);
8383 contentView.setCharSequence(R.id.status_bar_latest_event_content, "setNameReplacement",
8384 nameReplacement);
8385 contentView.setBoolean(R.id.status_bar_latest_event_content, "setIsOneToOne",
8386 isOneToOne);
8387 contentView.setCharSequence(R.id.status_bar_latest_event_content,
8388 "setConversationTitle", conversationTitle);
8389 if (isConversationLayout) {
8390 contentView.setIcon(R.id.status_bar_latest_event_content,
8391 "setShortcutIcon", mShortcutIcon);
8392 contentView.setBoolean(R.id.status_bar_latest_event_content,
8393 "setIsImportantConversation", isImportantConversation);
8394 }
8395 if (isHeaderless) {
8396 // Collapsed legacy messaging style has a 1-line limit.
8397 contentView.setInt(R.id.notification_messaging, "setMaxDisplayedLines", 1);
8398 }
8399 contentView.setIcon(R.id.status_bar_latest_event_content, "setLargeIcon",
8400 largeIcon);
8401 contentView.setBundle(R.id.status_bar_latest_event_content, "setData",
8402 mBuilder.mN.extras);
8403 return contentView;
8404 }
8405
8406 private CharSequence getKey(Person person) {
8407 return person == null ? null
8408 : person.getKey() == null ? person.getName() : person.getKey();
8409 }
8410
8411 private CharSequence getOtherPersonName() {
8412 CharSequence userKey = getKey(mUser);
8413 for (int i = mMessages.size() - 1; i >= 0; i--) {
8414 Person sender = mMessages.get(i).getSenderPerson();
8415 if (sender != null && !TextUtils.equals(userKey, getKey(sender))) {
8416 return sender.getName();
8417 }
8418 }
8419 return null;
8420 }
8421
8422 private boolean hasOnlyWhiteSpaceSenders() {
8423 for (int i = 0; i < mMessages.size(); i++) {
8424 Message m = mMessages.get(i);
8425 Person sender = m.getSenderPerson();
8426 if (sender != null && !isWhiteSpace(sender.getName())) {
8427 return false;
8428 }
8429 }
8430 return true;
8431 }
8432
8433 private boolean isWhiteSpace(CharSequence sender) {
8434 if (TextUtils.isEmpty(sender)) {
8435 return true;
8436 }
8437 if (sender.toString().matches("^\\s*$")) {
8438 return true;
8439 }
8440 // Let's check if we only have 0 whitespace chars. Some apps did this as a workaround
8441 // For the presentation that we had.
8442 for (int i = 0; i < sender.length(); i++) {
8443 char c = sender.charAt(i);
8444 if (c != '\u200B') {
8445 return false;
8446 }
8447 }
8448 return true;
8449 }
8450
8451 /**
8452 * @hide
8453 */
8454 @Override
8455 public RemoteViews makeHeadsUpContentView(boolean increasedHeight) {
8456 return makeMessagingView(StandardTemplateParams.VIEW_TYPE_HEADS_UP);
8457 }
8458
8459 /**
8460 * @hide
8461 */
8462 @Override
8463 public void reduceImageSizes(Context context) {
8464 super.reduceImageSizes(context);
8465 Resources resources = context.getResources();
8466 boolean isLowRam = ActivityManager.isLowRamDeviceStatic();
8467 if (mShortcutIcon != null) {
8468 int maxSize = resources.getDimensionPixelSize(
8469 isLowRam ? R.dimen.notification_small_icon_size_low_ram
8470 : R.dimen.notification_small_icon_size);
8471 mShortcutIcon.scaleDownIfNecessary(maxSize, maxSize);
8472 }
8473
8474 int maxAvatarSize = resources.getDimensionPixelSize(
8475 isLowRam ? R.dimen.notification_person_icon_max_size_low_ram
8476 : R.dimen.notification_person_icon_max_size);
8477 if (mUser != null && mUser.getIcon() != null) {
8478 mUser.getIcon().scaleDownIfNecessary(maxAvatarSize, maxAvatarSize);
8479 }
8480
8481 reduceMessagesIconSizes(mMessages, maxAvatarSize);
8482 reduceMessagesIconSizes(mHistoricMessages, maxAvatarSize);
8483 }
8484
8485 /**
8486 * @hide
8487 */
8488 private static void reduceMessagesIconSizes(@Nullable List<Message> messages, int maxSize) {
8489 if (messages == null) {
8490 return;
8491 }
8492
8493 for (Message message : messages) {
8494 Person sender = message.mSender;
8495 if (sender != null) {
8496 Icon icon = sender.getIcon();
8497 if (icon != null) {
8498 icon.scaleDownIfNecessary(maxSize, maxSize);
8499 }
8500 }
8501 }
8502 }
8503
8504 public static final class Message {
8505 /** @hide */
8506 public static final String KEY_TEXT = "text";
8507 static final String KEY_TIMESTAMP = "time";
8508 static final String KEY_SENDER = "sender";
8509 static final String KEY_SENDER_PERSON = "sender_person";
8510 static final String KEY_DATA_MIME_TYPE = "type";
8511 static final String KEY_DATA_URI= "uri";
8512 static final String KEY_EXTRAS_BUNDLE = "extras";
8513 static final String KEY_REMOTE_INPUT_HISTORY = "remote_input_history";
8514
8515 private final CharSequence mText;
8516 private final long mTimestamp;
8517 @Nullable
8518 private final Person mSender;
8519 /** True if this message was generated from the extra
8520 * {@link Notification#EXTRA_REMOTE_INPUT_HISTORY_ITEMS}
8521 */
8522 private final boolean mRemoteInputHistory;
8523
8524 private Bundle mExtras = new Bundle();
8525 private String mDataMimeType;
8526 private Uri mDataUri;
8527
8528 /**
8529 * Constructor
8530 * @param text A {@link CharSequence} to be displayed as the message content
8531 * @param timestamp Time at which the message arrived
8532 * @param sender A {@link CharSequence} to be used for displaying the name of the
8533 * sender. Should be <code>null</code> for messages by the current user, in which case
8534 * the platform will insert {@link MessagingStyle#getUserDisplayName()}.
8535 * Should be unique amongst all individuals in the conversation, and should be
8536 * consistent during re-posts of the notification.
8537 *
8538 * @deprecated use {@code Message(CharSequence, long, Person)}
8539 */
8540 public Message(CharSequence text, long timestamp, CharSequence sender){
8541 this(text, timestamp, sender == null ? null
8542 : new Person.Builder().setName(sender).build());
8543 }
8544
8545 /**
8546 * Constructor
8547 * @param text A {@link CharSequence} to be displayed as the message content
8548 * @param timestamp Time at which the message arrived
8549 * @param sender The {@link Person} who sent the message.
8550 * Should be <code>null</code> for messages by the current user, in which case
8551 * the platform will insert the user set in {@code MessagingStyle(Person)}.
8552 * <p>
8553 * The person provided should contain an Icon, set with
8554 * {@link Person.Builder#setIcon(Icon)} and also have a name provided
8555 * with {@link Person.Builder#setName(CharSequence)}. If multiple users have the same
8556 * name, consider providing a key with {@link Person.Builder#setKey(String)} in order
8557 * to differentiate between the different users.
8558 * </p>
8559 */
8560 public Message(@NonNull CharSequence text, long timestamp, @Nullable Person sender) {
8561 this(text, timestamp, sender, false /* remoteHistory */);
8562 }
8563
8564 /**
8565 * Constructor
8566 * @param text A {@link CharSequence} to be displayed as the message content
8567 * @param timestamp Time at which the message arrived
8568 * @param sender The {@link Person} who sent the message.
8569 * Should be <code>null</code> for messages by the current user, in which case
8570 * the platform will insert the user set in {@code MessagingStyle(Person)}.
8571 * @param remoteInputHistory True if the messages was generated from the extra
8572 * {@link Notification#EXTRA_REMOTE_INPUT_HISTORY_ITEMS}.
8573 * <p>
8574 * The person provided should contain an Icon, set with
8575 * {@link Person.Builder#setIcon(Icon)} and also have a name provided
8576 * with {@link Person.Builder#setName(CharSequence)}. If multiple users have the same
8577 * name, consider providing a key with {@link Person.Builder#setKey(String)} in order
8578 * to differentiate between the different users.
8579 * </p>
8580 * @hide
8581 */
8582 public Message(@NonNull CharSequence text, long timestamp, @Nullable Person sender,
8583 boolean remoteInputHistory) {
8584 mText = safeCharSequence(text);
8585 mTimestamp = timestamp;
8586 mSender = sender;
8587 mRemoteInputHistory = remoteInputHistory;
8588 }
8589
8590 /**
8591 * Sets a binary blob of data and an associated MIME type for a message. In the case
8592 * where the platform doesn't support the MIME type, the original text provided in the
8593 * constructor will be used.
8594 * @param dataMimeType The MIME type of the content. See
8595 * <a href="{@docRoot}notifications/messaging.html"> for the list of supported MIME
8596 * types on Android and Android Wear.
8597 * @param dataUri The uri containing the content whose type is given by the MIME type.
8598 * <p class="note">
8599 * <ol>
8600 * <li>Notification Listeners including the System UI need permission to access the
8601 * data the Uri points to. The recommended ways to do this are:</li>
8602 * <li>Store the data in your own ContentProvider, making sure that other apps have
8603 * the correct permission to access your provider. The preferred mechanism for
8604 * providing access is to use per-URI permissions which are temporary and only
8605 * grant access to the receiving application. An easy way to create a
8606 * ContentProvider like this is to use the FileProvider helper class.</li>
8607 * <li>Use the system MediaStore. The MediaStore is primarily aimed at video, audio
8608 * and image MIME types, however beginning with Android 3.0 (API level 11) it can
8609 * also store non-media types (see MediaStore.Files for more info). Files can be
8610 * inserted into the MediaStore using scanFile() after which a content:// style
8611 * Uri suitable for sharing is passed to the provided onScanCompleted() callback.
8612 * Note that once added to the system MediaStore the content is accessible to any
8613 * app on the device.</li>
8614 * </ol>
8615 * @return this object for method chaining
8616 */
8617 public Message setData(String dataMimeType, Uri dataUri) {
8618 mDataMimeType = dataMimeType;
8619 mDataUri = dataUri;
8620 return this;
8621 }
8622
8623 /**
8624 * Get the text to be used for this message, or the fallback text if a type and content
8625 * Uri have been set
8626 */
8627 public CharSequence getText() {
8628 return mText;
8629 }
8630
8631 /**
8632 * Get the time at which this message arrived
8633 */
8634 public long getTimestamp() {
8635 return mTimestamp;
8636 }
8637
8638 /**
8639 * Get the extras Bundle for this message.
8640 */
8641 public Bundle getExtras() {
8642 return mExtras;
8643 }
8644
8645 /**
8646 * Get the text used to display the contact's name in the messaging experience
8647 *
8648 * @deprecated use {@link #getSenderPerson()}
8649 */
8650 public CharSequence getSender() {
8651 return mSender == null ? null : mSender.getName();
8652 }
8653
8654 /**
8655 * Get the sender associated with this message.
8656 */
8657 @Nullable
8658 public Person getSenderPerson() {
8659 return mSender;
8660 }
8661
8662 /**
8663 * Get the MIME type of the data pointed to by the Uri
8664 */
8665 public String getDataMimeType() {
8666 return mDataMimeType;
8667 }
8668
8669 /**
8670 * Get the Uri pointing to the content of the message. Can be null, in which case
8671 * {@see #getText()} is used.
8672 */
8673 public Uri getDataUri() {
8674 return mDataUri;
8675 }
8676
8677 /**
8678 * @return True if the message was generated from
8679 * {@link Notification#EXTRA_REMOTE_INPUT_HISTORY_ITEMS}.
8680 * @hide
8681 */
8682 public boolean isRemoteInputHistory() {
8683 return mRemoteInputHistory;
8684 }
8685
8686 /**
8687 * @hide
8688 */
8689 @VisibleForTesting
8690 public Bundle toBundle() {
8691 Bundle bundle = new Bundle();
8692 if (mText != null) {
8693 bundle.putCharSequence(KEY_TEXT, mText);
8694 }
8695 bundle.putLong(KEY_TIMESTAMP, mTimestamp);
8696 if (mSender != null) {
8697 // Legacy listeners need this
8698 bundle.putCharSequence(KEY_SENDER, safeCharSequence(mSender.getName()));
8699 bundle.putParcelable(KEY_SENDER_PERSON, mSender);
8700 }
8701 if (mDataMimeType != null) {
8702 bundle.putString(KEY_DATA_MIME_TYPE, mDataMimeType);
8703 }
8704 if (mDataUri != null) {
8705 bundle.putParcelable(KEY_DATA_URI, mDataUri);
8706 }
8707 if (mExtras != null) {
8708 bundle.putBundle(KEY_EXTRAS_BUNDLE, mExtras);
8709 }
8710 if (mRemoteInputHistory) {
8711 bundle.putBoolean(KEY_REMOTE_INPUT_HISTORY, mRemoteInputHistory);
8712 }
8713 return bundle;
8714 }
8715
8716 static Bundle[] getBundleArrayForMessages(List<Message> messages) {
8717 Bundle[] bundles = new Bundle[messages.size()];
8718 final int N = messages.size();
8719 for (int i = 0; i < N; i++) {
8720 bundles[i] = messages.get(i).toBundle();
8721 }
8722 return bundles;
8723 }
8724
8725 /**
8726 * Returns a list of messages read from the given bundle list, e.g.
8727 * {@link #EXTRA_MESSAGES} or {@link #EXTRA_HISTORIC_MESSAGES}.
8728 */
8729 @NonNull
8730 public static List<Message> getMessagesFromBundleArray(@Nullable Parcelable[] bundles) {
8731 if (bundles == null) {
8732 return new ArrayList<>();
8733 }
8734 List<Message> messages = new ArrayList<>(bundles.length);
8735 for (int i = 0; i < bundles.length; i++) {
8736 if (bundles[i] instanceof Bundle) {
8737 Message message = getMessageFromBundle((Bundle)bundles[i]);
8738 if (message != null) {
8739 messages.add(message);
8740 }
8741 }
8742 }
8743 return messages;
8744 }
8745
8746 /**
8747 * Returns the message that is stored in the bundle (e.g. one of the values in the lists
8748 * in {@link #EXTRA_MESSAGES} or {@link #EXTRA_HISTORIC_MESSAGES}) or null if the
8749 * message couldn't be resolved.
8750 * @hide
8751 */
8752 @Nullable
8753 public static Message getMessageFromBundle(@NonNull Bundle bundle) {
8754 try {
8755 if (!bundle.containsKey(KEY_TEXT) || !bundle.containsKey(KEY_TIMESTAMP)) {
8756 return null;
8757 } else {
8758
8759 Person senderPerson = bundle.getParcelable(KEY_SENDER_PERSON, Person.class);
8760 if (senderPerson == null) {
8761 // Legacy apps that use compat don't actually provide the sender objects
8762 // We need to fix the compat version to provide people / use
8763 // the native api instead
8764 CharSequence senderName = bundle.getCharSequence(KEY_SENDER);
8765 if (senderName != null) {
8766 senderPerson = new Person.Builder().setName(senderName).build();
8767 }
8768 }
8769 Message message = new Message(bundle.getCharSequence(KEY_TEXT),
8770 bundle.getLong(KEY_TIMESTAMP),
8771 senderPerson,
8772 bundle.getBoolean(KEY_REMOTE_INPUT_HISTORY, false));
8773 if (bundle.containsKey(KEY_DATA_MIME_TYPE) &&
8774 bundle.containsKey(KEY_DATA_URI)) {
8775 message.setData(bundle.getString(KEY_DATA_MIME_TYPE),
8776 bundle.getParcelable(KEY_DATA_URI, Uri.class));
8777 }
8778 if (bundle.containsKey(KEY_EXTRAS_BUNDLE)) {
8779 message.getExtras().putAll(bundle.getBundle(KEY_EXTRAS_BUNDLE));
8780 }
8781 return message;
8782 }
8783 } catch (ClassCastException e) {
8784 return null;
8785 }
8786 }
8787 }
8788 }
8789
8790 /**
8791 * Helper class for generating large-format notifications that include a list of (up to 5) strings.
8792 *
8793 * Here's how you'd set the <code>InboxStyle</code> on a notification:
8794 * <pre class="prettyprint">
8795 * Notification notif = new Notification.Builder(mContext)
8796 * .setContentTitle(&quot;5 New mails from &quot; + sender.toString())
8797 * .setContentText(subject)
8798 * .setSmallIcon(R.drawable.new_mail)
8799 * .setLargeIcon(aBitmap)
8800 * .setStyle(new Notification.InboxStyle()
8801 * .addLine(str1)
8802 * .addLine(str2)
8803 * .setContentTitle(&quot;&quot;)
8804 * .setSummaryText(&quot;+3 more&quot;))
8805 * .build();
8806 * </pre>
8807 *
8808 * @see Notification#bigContentView
8809 */
8810 public static class InboxStyle extends Style {
8811
8812 /**
8813 * The number of lines of remote input history allowed until we start reducing lines.
8814 */
8815 private static final int NUMBER_OF_HISTORY_ALLOWED_UNTIL_REDUCTION = 1;
8816 private ArrayList<CharSequence> mTexts = new ArrayList<CharSequence>(5);
8817
8818 public InboxStyle() {
8819 }
8820
8821 /**
8822 * @deprecated use {@code InboxStyle()}.
8823 */
8824 @Deprecated
8825 public InboxStyle(Builder builder) {
8826 setBuilder(builder);
8827 }
8828
8829 /**
8830 * Overrides ContentTitle in the big form of the template.
8831 * This defaults to the value passed to setContentTitle().
8832 */
8833 public InboxStyle setBigContentTitle(CharSequence title) {
8834 internalSetBigContentTitle(safeCharSequence(title));
8835 return this;
8836 }
8837
8838 /**
8839 * Set the first line of text after the detail section in the big form of the template.
8840 */
8841 public InboxStyle setSummaryText(CharSequence cs) {
8842 internalSetSummaryText(safeCharSequence(cs));
8843 return this;
8844 }
8845
8846 /**
8847 * Append a line to the digest section of the Inbox notification.
8848 */
8849 public InboxStyle addLine(CharSequence cs) {
8850 mTexts.add(safeCharSequence(cs));
8851 return this;
8852 }
8853
8854 /**
8855 * @hide
8856 */
8857 public ArrayList<CharSequence> getLines() {
8858 return mTexts;
8859 }
8860
8861 /**
8862 * @hide
8863 */
8864 public void addExtras(Bundle extras) {
8865 super.addExtras(extras);
8866
8867 CharSequence[] a = new CharSequence[mTexts.size()];
8868 extras.putCharSequenceArray(EXTRA_TEXT_LINES, mTexts.toArray(a));
8869 }
8870
8871 /**
8872 * @hide
8873 */
8874 @Override
8875 protected void restoreFromExtras(Bundle extras) {
8876 super.restoreFromExtras(extras);
8877
8878 mTexts.clear();
8879 if (extras.containsKey(EXTRA_TEXT_LINES)) {
8880 Collections.addAll(mTexts, extras.getCharSequenceArray(EXTRA_TEXT_LINES));
8881 }
8882 }
8883
8884 /**
8885 * @hide
8886 */
8887 public RemoteViews makeBigContentView() {
8888 StandardTemplateParams p = mBuilder.mParams.reset()
8889 .viewType(StandardTemplateParams.VIEW_TYPE_BIG)
8890 .fillTextsFrom(mBuilder).text(null);
8891 TemplateBindResult result = new TemplateBindResult();
8892 RemoteViews contentView = getStandardView(mBuilder.getInboxLayoutResource(), p, result);
8893
8894 int[] rowIds = {R.id.inbox_text0, R.id.inbox_text1, R.id.inbox_text2, R.id.inbox_text3,
8895 R.id.inbox_text4, R.id.inbox_text5, R.id.inbox_text6};
8896
8897 // Make sure all rows are gone in case we reuse a view.
8898 for (int rowId : rowIds) {
8899 contentView.setViewVisibility(rowId, View.GONE);
8900 }
8901
8902 int i=0;
8903 int topPadding = mBuilder.mContext.getResources().getDimensionPixelSize(
8904 R.dimen.notification_inbox_item_top_padding);
8905 boolean first = true;
8906 int onlyViewId = 0;
8907 int maxRows = rowIds.length;
8908 if (mBuilder.mActions.size() > 0) {
8909 maxRows--;
8910 }
8911 RemoteInputHistoryItem[] remoteInputHistory = getParcelableArrayFromBundle(
8912 mBuilder.mN.extras, EXTRA_REMOTE_INPUT_HISTORY_ITEMS,
8913 RemoteInputHistoryItem.class);
8914 if (remoteInputHistory != null
8915 && remoteInputHistory.length > NUMBER_OF_HISTORY_ALLOWED_UNTIL_REDUCTION) {
8916 // Let's remove some messages to make room for the remote input history.
8917 // 1 is always able to fit, but let's remove them if they are 2 or 3
8918 int numRemoteInputs = Math.min(remoteInputHistory.length,
8919 MAX_REMOTE_INPUT_HISTORY_LINES);
8920 int totalNumRows = mTexts.size() + numRemoteInputs
8921 - NUMBER_OF_HISTORY_ALLOWED_UNTIL_REDUCTION;
8922 if (totalNumRows > maxRows) {
8923 int overflow = totalNumRows - maxRows;
8924 if (mTexts.size() > maxRows) {
8925 // Heuristic: if the Texts don't fit anyway, we'll rather drop the last
8926 // few messages, even with the remote input
8927 maxRows -= overflow;
8928 } else {
8929 // otherwise we drop the first messages
8930 i = overflow;
8931 }
8932 }
8933 }
8934 while (i < mTexts.size() && i < maxRows) {
8935 CharSequence str = mTexts.get(i);
8936 if (!TextUtils.isEmpty(str)) {
8937 contentView.setViewVisibility(rowIds[i], View.VISIBLE);
8938 contentView.setTextViewText(rowIds[i],
8939 mBuilder.processTextSpans(mBuilder.processLegacyText(str)));
8940 mBuilder.setTextViewColorSecondary(contentView, rowIds[i], p);
8941 contentView.setViewPadding(rowIds[i], 0, topPadding, 0, 0);
8942 if (first) {
8943 onlyViewId = rowIds[i];
8944 } else {
8945 onlyViewId = 0;
8946 }
8947 first = false;
8948 }
8949 i++;
8950 }
8951 if (onlyViewId != 0) {
8952 // We only have 1 entry, lets make it look like the normal Text of a Bigtext
8953 topPadding = mBuilder.mContext.getResources().getDimensionPixelSize(
8954 R.dimen.notification_text_margin_top);
8955 contentView.setViewPadding(onlyViewId, 0, topPadding, 0, 0);
8956 }
8957
8958 return contentView;
8959 }
8960
8961 /**
8962 * @hide
8963 */
8964 @Override
8965 public boolean areNotificationsVisiblyDifferent(Style other) {
8966 if (other == null || getClass() != other.getClass()) {
8967 return true;
8968 }
8969 InboxStyle newS = (InboxStyle) other;
8970
8971 final ArrayList<CharSequence> myLines = getLines();
8972 final ArrayList<CharSequence> newLines = newS.getLines();
8973 final int n = myLines.size();
8974 if (n != newLines.size()) {
8975 return true;
8976 }
8977
8978 for (int i = 0; i < n; i++) {
8979 if (!Objects.equals(
8980 String.valueOf(myLines.get(i)),
8981 String.valueOf(newLines.get(i)))) {
8982 return true;
8983 }
8984 }
8985 return false;
8986 }
8987 }
8988
8989 /**
8990 * Notification style for media playback notifications.
8991 *
8992 * In the expanded form, {@link Notification#bigContentView}, up to 5
8993 * {@link Notification.Action}s specified with
8994 * {@link Notification.Builder#addAction(Action) addAction} will be
8995 * shown as icon-only pushbuttons, suitable for transport controls. The Bitmap given to
8996 * {@link Notification.Builder#setLargeIcon(android.graphics.Bitmap) setLargeIcon()} will be
8997 * treated as album artwork.
8998 * <p>
8999 * Unlike the other styles provided here, MediaStyle can also modify the standard-size
9000 * {@link Notification#contentView}; by providing action indices to
9001 * {@link #setShowActionsInCompactView(int...)} you can promote up to 3 actions to be displayed
9002 * in the standard view alongside the usual content.
9003 * <p>
9004 * Notifications created with MediaStyle will have their category set to
9005 * {@link Notification#CATEGORY_TRANSPORT CATEGORY_TRANSPORT} unless you set a different
9006 * category using {@link Notification.Builder#setCategory(String) setCategory()}.
9007 * <p>
9008 * Finally, if you attach a {@link android.media.session.MediaSession.Token} using
9009 * {@link android.app.Notification.MediaStyle#setMediaSession(MediaSession.Token)},
9010 * the System UI can identify this as a notification representing an active media session
9011 * and respond accordingly (by showing album artwork in the lockscreen, for example).
9012 *
9013 * <p>
9014 * Starting at {@link android.os.Build.VERSION_CODES#O Android O} any notification that has a
9015 * media session attached with {@link #setMediaSession(MediaSession.Token)} will be colorized.
9016 * You can opt-out of this behavior by using {@link Notification.Builder#setColorized(boolean)}.
9017 * <p>
9018 *
9019 * To use this style with your Notification, feed it to
9020 * {@link Notification.Builder#setStyle(android.app.Notification.Style)} like so:
9021 * <pre class="prettyprint">
9022 * Notification noti = new Notification.Builder()
9023 * .setSmallIcon(R.drawable.ic_stat_player)
9024 * .setContentTitle(&quot;Track title&quot;)
9025 * .setContentText(&quot;Artist - Album&quot;)
9026 * .setLargeIcon(albumArtBitmap))
9027 * .setStyle(<b>new Notification.MediaStyle()</b>
9028 * .setMediaSession(mySession))
9029 * .build();
9030 * </pre>
9031 *
9032 * @see Notification#bigContentView
9033 * @see Notification.Builder#setColorized(boolean)
9034 */
9035 public static class MediaStyle extends Style {
9036 // Changing max media buttons requires also changing templates
9037 // (notification_template_material_media and notification_template_material_big_media).
9038 static final int MAX_MEDIA_BUTTONS_IN_COMPACT = 3;
9039 static final int MAX_MEDIA_BUTTONS = 5;
9040 @IdRes private static final int[] MEDIA_BUTTON_IDS = {
9041 R.id.action0,
9042 R.id.action1,
9043 R.id.action2,
9044 R.id.action3,
9045 R.id.action4,
9046 };
9047
9048 private int[] mActionsToShowInCompact = null;
9049 private MediaSession.Token mToken;
9050 private CharSequence mDeviceName;
9051 private int mDeviceIcon;
9052 private PendingIntent mDeviceIntent;
9053
9054 public MediaStyle() {
9055 }
9056
9057 /**
9058 * @deprecated use {@code MediaStyle()}.
9059 */
9060 @Deprecated
9061 public MediaStyle(Builder builder) {
9062 setBuilder(builder);
9063 }
9064
9065 /**
9066 * Request up to 3 actions (by index in the order of addition) to be shown in the compact
9067 * notification view.
9068 *
9069 * @param actions the indices of the actions to show in the compact notification view
9070 */
9071 public MediaStyle setShowActionsInCompactView(int...actions) {
9072 mActionsToShowInCompact = actions;
9073 return this;
9074 }
9075
9076 /**
9077 * Attach a {@link android.media.session.MediaSession.Token} to this Notification
9078 * to provide additional playback information and control to the SystemUI.
9079 */
9080 public MediaStyle setMediaSession(MediaSession.Token token) {
9081 mToken = token;
9082 return this;
9083 }
9084
9085 /**
9086 * For media notifications associated with playback on a remote device, provide device
9087 * information that will replace the default values for the output switcher chip on the
9088 * media control, as well as an intent to use when the output switcher chip is tapped,
9089 * on devices where this is supported.
9090 * <p>
9091 * This method is intended for system applications to provide information and/or
9092 * functionality that would otherwise be unavailable to the default output switcher because
9093 * the media originated on a remote device.
9094 *
9095 * @param deviceName The name of the remote device to display
9096 * @param iconResource Icon resource representing the device
9097 * @param chipIntent PendingIntent to send when the output switcher is tapped. May be
9098 * {@code null}, in which case the output switcher will be disabled.
9099 * This intent should open an Activity or it will be ignored.
9100 * @return MediaStyle
9101 *
9102 * @hide
9103 */
9104 @SystemApi
9105 @RequiresPermission(android.Manifest.permission.MEDIA_CONTENT_CONTROL)
9106 @NonNull
9107 public MediaStyle setRemotePlaybackInfo(@NonNull CharSequence deviceName,
9108 @DrawableRes int iconResource, @Nullable PendingIntent chipIntent) {
9109 mDeviceName = deviceName;
9110 mDeviceIcon = iconResource;
9111 mDeviceIntent = chipIntent;
9112 return this;
9113 }
9114
9115 /**
9116 * @hide
9117 */
9118 @Override
9119 @UnsupportedAppUsage
9120 public Notification buildStyled(Notification wip) {
9121 super.buildStyled(wip);
9122 if (wip.category == null) {
9123 wip.category = Notification.CATEGORY_TRANSPORT;
9124 }
9125 return wip;
9126 }
9127
9128 /**
9129 * @hide
9130 */
9131 @Override
9132 public RemoteViews makeContentView(boolean increasedHeight) {
9133 return makeMediaContentView(null /* customContent */);
9134 }
9135
9136 /**
9137 * @hide
9138 */
9139 @Override
9140 public RemoteViews makeBigContentView() {
9141 return makeMediaBigContentView(null /* customContent */);
9142 }
9143
9144 /**
9145 * @hide
9146 */
9147 @Override
9148 public RemoteViews makeHeadsUpContentView(boolean increasedHeight) {
9149 return makeMediaContentView(null /* customContent */);
9150 }
9151
9152 /** @hide */
9153 @Override
9154 public void addExtras(Bundle extras) {
9155 super.addExtras(extras);
9156
9157 if (mToken != null) {
9158 extras.putParcelable(EXTRA_MEDIA_SESSION, mToken);
9159 }
9160 if (mActionsToShowInCompact != null) {
9161 extras.putIntArray(EXTRA_COMPACT_ACTIONS, mActionsToShowInCompact);
9162 }
9163 if (mDeviceName != null) {
9164 extras.putCharSequence(EXTRA_MEDIA_REMOTE_DEVICE, mDeviceName);
9165 }
9166 if (mDeviceIcon > 0) {
9167 extras.putInt(EXTRA_MEDIA_REMOTE_ICON, mDeviceIcon);
9168 }
9169 if (mDeviceIntent != null) {
9170 extras.putParcelable(EXTRA_MEDIA_REMOTE_INTENT, mDeviceIntent);
9171 }
9172 }
9173
9174 /**
9175 * @hide
9176 */
9177 @Override
9178 protected void restoreFromExtras(Bundle extras) {
9179 super.restoreFromExtras(extras);
9180
9181 if (extras.containsKey(EXTRA_MEDIA_SESSION)) {
9182 mToken = extras.getParcelable(EXTRA_MEDIA_SESSION, MediaSession.Token.class);
9183 }
9184 if (extras.containsKey(EXTRA_COMPACT_ACTIONS)) {
9185 mActionsToShowInCompact = extras.getIntArray(EXTRA_COMPACT_ACTIONS);
9186 }
9187 if (extras.containsKey(EXTRA_MEDIA_REMOTE_DEVICE)) {
9188 mDeviceName = extras.getCharSequence(EXTRA_MEDIA_REMOTE_DEVICE);
9189 }
9190 if (extras.containsKey(EXTRA_MEDIA_REMOTE_ICON)) {
9191 mDeviceIcon = extras.getInt(EXTRA_MEDIA_REMOTE_ICON);
9192 }
9193 if (extras.containsKey(EXTRA_MEDIA_REMOTE_INTENT)) {
9194 mDeviceIntent = extras.getParcelable(
9195 EXTRA_MEDIA_REMOTE_INTENT, PendingIntent.class);
9196 }
9197 }
9198
9199 /**
9200 * @hide
9201 */
9202 @Override
9203 public boolean areNotificationsVisiblyDifferent(Style other) {
9204 if (other == null || getClass() != other.getClass()) {
9205 return true;
9206 }
9207 // All fields to compare are on the Notification object
9208 return false;
9209 }
9210
9211 private void bindMediaActionButton(RemoteViews container, @IdRes int buttonId,
9212 Action action, StandardTemplateParams p) {
9213 final boolean tombstone = (action.actionIntent == null);
9214 container.setViewVisibility(buttonId, View.VISIBLE);
9215 container.setImageViewIcon(buttonId, action.getIcon());
9216
9217 // If the action buttons should not be tinted, then just use the default
9218 // notification color. Otherwise, just use the passed-in color.
9219 int tintColor = mBuilder.getStandardActionColor(p);
9220
9221 container.setDrawableTint(buttonId, false, tintColor,
9222 PorterDuff.Mode.SRC_ATOP);
9223
9224 int rippleAlpha = mBuilder.getColors(p).getRippleAlpha();
9225 int rippleColor = Color.argb(rippleAlpha, Color.red(tintColor), Color.green(tintColor),
9226 Color.blue(tintColor));
9227 container.setRippleDrawableColor(buttonId, ColorStateList.valueOf(rippleColor));
9228
9229 if (!tombstone) {
9230 container.setOnClickPendingIntent(buttonId, action.actionIntent);
9231 }
9232 container.setContentDescription(buttonId, action.title);
9233 }
9234
9235 /** @hide */
9236 protected RemoteViews makeMediaContentView(@Nullable RemoteViews customContent) {
9237 final int numActions = mBuilder.mActions.size();
9238 final int numActionsToShow = Math.min(mActionsToShowInCompact == null
9239 ? 0 : mActionsToShowInCompact.length, MAX_MEDIA_BUTTONS_IN_COMPACT);
9240 if (numActionsToShow > numActions) {
9241 throw new IllegalArgumentException(String.format(
9242 "setShowActionsInCompactView: action %d out of bounds (max %d)",
9243 numActions, numActions - 1));
9244 }
9245
9246 StandardTemplateParams p = mBuilder.mParams.reset()
9247 .viewType(StandardTemplateParams.VIEW_TYPE_NORMAL)
9248 .hideTime(numActionsToShow > 1) // hide if actions wider than a right icon
9249 .hideSubText(numActionsToShow > 1) // hide if actions wider than a right icon
9250 .hideLeftIcon(false) // allow large icon on left when grouped
9251 .hideRightIcon(numActionsToShow > 0) // right icon or actions; not both
9252 .hideProgress(true)
9253 .fillTextsFrom(mBuilder);
9254 TemplateBindResult result = new TemplateBindResult();
9255 RemoteViews template = mBuilder.applyStandardTemplate(
9256 R.layout.notification_template_material_media, p,
9257 null /* result */);
9258
9259 for (int i = 0; i < MAX_MEDIA_BUTTONS_IN_COMPACT; i++) {
9260 if (i < numActionsToShow) {
9261 final Action action = mBuilder.mActions.get(mActionsToShowInCompact[i]);
9262 bindMediaActionButton(template, MEDIA_BUTTON_IDS[i], action, p);
9263 } else {
9264 template.setViewVisibility(MEDIA_BUTTON_IDS[i], View.GONE);
9265 }
9266 }
9267 // Prevent a swooping expand animation when there are no actions
9268 boolean hasActions = numActionsToShow != 0;
9269 template.setViewVisibility(R.id.media_actions, hasActions ? View.VISIBLE : View.GONE);
9270
9271 // Add custom view if provided by subclass.
9272 buildCustomContentIntoTemplate(mBuilder.mContext, template, customContent, p, result);
9273 return template;
9274 }
9275
9276 /** @hide */
9277 protected RemoteViews makeMediaBigContentView(@Nullable RemoteViews customContent) {
9278 final int actionCount = Math.min(mBuilder.mActions.size(), MAX_MEDIA_BUTTONS);
9279 StandardTemplateParams p = mBuilder.mParams.reset()
9280 .viewType(StandardTemplateParams.VIEW_TYPE_BIG)
9281 .hideProgress(true)
9282 .fillTextsFrom(mBuilder);
9283 TemplateBindResult result = new TemplateBindResult();
9284 RemoteViews template = mBuilder.applyStandardTemplate(
9285 R.layout.notification_template_material_big_media, p , result);
9286
9287 for (int i = 0; i < MAX_MEDIA_BUTTONS; i++) {
9288 if (i < actionCount) {
9289 bindMediaActionButton(template,
9290 MEDIA_BUTTON_IDS[i], mBuilder.mActions.get(i), p);
9291 } else {
9292 template.setViewVisibility(MEDIA_BUTTON_IDS[i], View.GONE);
9293 }
9294 }
9295 buildCustomContentIntoTemplate(mBuilder.mContext, template, customContent, p, result);
9296 return template;
9297 }
9298 }
9299
9300 /**
9301 * Helper class for generating large-format notifications that include a large image attachment.
9302 *
9303 * Here's how you'd set the <code>CallStyle</code> on a notification:
9304 * <pre class="prettyprint">
9305 * Notification notif = new Notification.Builder(mContext)
9306 * .setSmallIcon(R.drawable.new_post)
9307 * .setStyle(Notification.CallStyle.forIncomingCall(caller, declineIntent, answerIntent))
9308 * .build();
9309 * </pre>
9310 */
9311 public static class CallStyle extends Style {
9312 /** @hide */
9313 public static final int CALL_TYPE_INCOMING = 1;
9314 /** @hide */
9315 public static final int CALL_TYPE_ONGOING = 2;
9316 /** @hide */
9317 public static final int CALL_TYPE_SCREENING = 3;
9318
9319 /**
9320 * This is a key used privately on the action.extras to give spacing priority
9321 * to the required call actions
9322 */
9323 private static final String KEY_ACTION_PRIORITY = "key_action_priority";
9324
9325 private int mCallType;
9326 private Person mPerson;
9327 private PendingIntent mAnswerIntent;
9328 private PendingIntent mDeclineIntent;
9329 private PendingIntent mHangUpIntent;
9330 private boolean mIsVideo;
9331 private Integer mAnswerButtonColor;
9332 private Integer mDeclineButtonColor;
9333 private Icon mVerificationIcon;
9334 private CharSequence mVerificationText;
9335
9336 CallStyle() {
9337 }
9338
9339 /**
9340 * Create a CallStyle for an incoming call.
9341 * This notification will have a decline and an answer action, will allow a single
9342 * custom {@link Builder#addAction(Action) action}, and will have a default
9343 * {@link Builder#setContentText(CharSequence) content text} for an incoming call.
9344 *
9345 * @param person The person displayed as the caller.
9346 * The person also needs to have a non-empty name associated with it.
9347 * @param declineIntent The intent to be sent when the user taps the decline action
9348 * @param answerIntent The intent to be sent when the user taps the answer action
9349 */
9350 @NonNull
9351 public static CallStyle forIncomingCall(@NonNull Person person,
9352 @NonNull PendingIntent declineIntent, @NonNull PendingIntent answerIntent) {
9353 return new CallStyle(CALL_TYPE_INCOMING, person,
9354 null /* hangUpIntent */,
9355 requireNonNull(declineIntent, "declineIntent is required"),
9356 requireNonNull(answerIntent, "answerIntent is required")
9357 );
9358 }
9359
9360 /**
9361 * Create a CallStyle for an ongoing call.
9362 * This notification will have a hang up action, will allow up to two
9363 * custom {@link Builder#addAction(Action) actions}, and will have a default
9364 * {@link Builder#setContentText(CharSequence) content text} for an ongoing call.
9365 *
9366 * @param person The person displayed as being on the other end of the call.
9367 * The person also needs to have a non-empty name associated with it.
9368 * @param hangUpIntent The intent to be sent when the user taps the hang up action
9369 */
9370 @NonNull
9371 public static CallStyle forOngoingCall(@NonNull Person person,
9372 @NonNull PendingIntent hangUpIntent) {
9373 return new CallStyle(CALL_TYPE_ONGOING, person,
9374 requireNonNull(hangUpIntent, "hangUpIntent is required"),
9375 null /* declineIntent */,
9376 null /* answerIntent */
9377 );
9378 }
9379
9380 /**
9381 * Create a CallStyle for a call that is being screened.
9382 * This notification will have a hang up and an answer action, will allow a single
9383 * custom {@link Builder#addAction(Action) action}, and will have a default
9384 * {@link Builder#setContentText(CharSequence) content text} for a call that is being
9385 * screened.
9386 *
9387 * @param person The person displayed as the caller.
9388 * The person also needs to have a non-empty name associated with it.
9389 * @param hangUpIntent The intent to be sent when the user taps the hang up action
9390 * @param answerIntent The intent to be sent when the user taps the answer action
9391 */
9392 @NonNull
9393 public static CallStyle forScreeningCall(@NonNull Person person,
9394 @NonNull PendingIntent hangUpIntent, @NonNull PendingIntent answerIntent) {
9395 return new CallStyle(CALL_TYPE_SCREENING, person,
9396 requireNonNull(hangUpIntent, "hangUpIntent is required"),
9397 null /* declineIntent */,
9398 requireNonNull(answerIntent, "answerIntent is required")
9399 );
9400 }
9401
9402 /**
9403 * @param person The person displayed for the incoming call.
9404 * The user also needs to have a non-empty name associated with it.
9405 * @param hangUpIntent The intent to be sent when the user taps the hang up action
9406 * @param declineIntent The intent to be sent when the user taps the decline action
9407 * @param answerIntent The intent to be sent when the user taps the answer action
9408 */
9409 private CallStyle(int callType, @NonNull Person person,
9410 @Nullable PendingIntent hangUpIntent, @Nullable PendingIntent declineIntent,
9411 @Nullable PendingIntent answerIntent) {
9412 if (person == null || TextUtils.isEmpty(person.getName())) {
9413 throw new IllegalArgumentException("person must have a non-empty a name");
9414 }
9415 mCallType = callType;
9416 mPerson = person;
9417 mAnswerIntent = answerIntent;
9418 mDeclineIntent = declineIntent;
9419 mHangUpIntent = hangUpIntent;
9420 }
9421
9422 /**
9423 * Sets whether the call is a video call, which may affect the icons or text used on the
9424 * required action buttons.
9425 */
9426 @NonNull
9427 public CallStyle setIsVideo(boolean isVideo) {
9428 mIsVideo = isVideo;
9429 return this;
9430 }
9431
9432 /**
9433 * Optional icon to be displayed with {@link #setVerificationText(CharSequence) text}
9434 * as a verification status of the caller.
9435 */
9436 @NonNull
9437 public CallStyle setVerificationIcon(@Nullable Icon verificationIcon) {
9438 mVerificationIcon = verificationIcon;
9439 return this;
9440 }
9441
9442 /**
9443 * Optional text to be displayed with an {@link #setVerificationIcon(Icon) icon}
9444 * as a verification status of the caller.
9445 */
9446 @NonNull
9447 public CallStyle setVerificationText(@Nullable CharSequence verificationText) {
9448 mVerificationText = safeCharSequence(verificationText);
9449 return this;
9450 }
9451
9452 /**
9453 * Optional color to be used as a hint for the Answer action button's color.
9454 * The system may change this color to ensure sufficient contrast with the background.
9455 * The system may choose to disregard this hint if the notification is not colorized.
9456 */
9457 @NonNull
9458 public CallStyle setAnswerButtonColorHint(@ColorInt int color) {
9459 mAnswerButtonColor = color;
9460 return this;
9461 }
9462
9463 /**
9464 * Optional color to be used as a hint for the Decline or Hang Up action button's color.
9465 * The system may change this color to ensure sufficient contrast with the background.
9466 * The system may choose to disregard this hint if the notification is not colorized.
9467 */
9468 @NonNull
9469 public CallStyle setDeclineButtonColorHint(@ColorInt int color) {
9470 mDeclineButtonColor = color;
9471 return this;
9472 }
9473
9474 /** @hide */
9475 @Override
9476 public Notification buildStyled(Notification wip) {
9477 wip = super.buildStyled(wip);
9478 // ensure that the actions in the builder and notification are corrected.
9479 mBuilder.mActions = getActionsListWithSystemActions();
9480 wip.actions = new Action[mBuilder.mActions.size()];
9481 mBuilder.mActions.toArray(wip.actions);
9482 return wip;
9483 }
9484
9485 /**
9486 * @hide
9487 */
9488 public boolean displayCustomViewInline() {
9489 // This is a lie; True is returned to make sure that the custom view is not used
9490 // instead of the template, but it will not actually be included.
9491 return true;
9492 }
9493
9494 /**
9495 * @hide
9496 */
9497 @Override
9498 public void purgeResources() {
9499 super.purgeResources();
9500 if (mVerificationIcon != null) {
9501 mVerificationIcon.convertToAshmem();
9502 }
9503 }
9504
9505 /**
9506 * @hide
9507 */
9508 @Override
9509 public void reduceImageSizes(Context context) {
9510 super.reduceImageSizes(context);
9511 if (mVerificationIcon != null) {
9512 int rightIconSize = context.getResources().getDimensionPixelSize(
9513 ActivityManager.isLowRamDeviceStatic()
9514 ? R.dimen.notification_right_icon_size_low_ram
9515 : R.dimen.notification_right_icon_size);
9516 mVerificationIcon.scaleDownIfNecessary(rightIconSize, rightIconSize);
9517 }
9518 }
9519
9520 /**
9521 * @hide
9522 */
9523 @Override
9524 public RemoteViews makeContentView(boolean increasedHeight) {
9525 return makeCallLayout(StandardTemplateParams.VIEW_TYPE_NORMAL);
9526 }
9527
9528 /**
9529 * @hide
9530 */
9531 @Override
9532 public RemoteViews makeHeadsUpContentView(boolean increasedHeight) {
9533 return makeCallLayout(StandardTemplateParams.VIEW_TYPE_HEADS_UP);
9534 }
9535
9536 /**
9537 * @hide
9538 */
9539 public RemoteViews makeBigContentView() {
9540 return makeCallLayout(StandardTemplateParams.VIEW_TYPE_BIG);
9541 }
9542
9543 @NonNull
9544 private Action makeNegativeAction() {
9545 if (mDeclineIntent == null) {
9546 return makeAction(R.drawable.ic_call_decline,
9547 R.string.call_notification_hang_up_action,
9548 mDeclineButtonColor, R.color.call_notification_decline_color,
9549 mHangUpIntent);
9550 } else {
9551 return makeAction(R.drawable.ic_call_decline,
9552 R.string.call_notification_decline_action,
9553 mDeclineButtonColor, R.color.call_notification_decline_color,
9554 mDeclineIntent);
9555 }
9556 }
9557
9558 @Nullable
9559 private Action makeAnswerAction() {
9560 return mAnswerIntent == null ? null : makeAction(
9561 mIsVideo ? R.drawable.ic_call_answer_video : R.drawable.ic_call_answer,
9562 mIsVideo ? R.string.call_notification_answer_video_action
9563 : R.string.call_notification_answer_action,
9564 mAnswerButtonColor, R.color.call_notification_answer_color,
9565 mAnswerIntent);
9566 }
9567
9568 @NonNull
9569 private Action makeAction(@DrawableRes int icon, @StringRes int title,
9570 @ColorInt Integer colorInt, @ColorRes int defaultColorRes, PendingIntent intent) {
9571 if (colorInt == null || !mBuilder.isCallActionColorCustomizable()) {
9572 colorInt = mBuilder.mContext.getColor(defaultColorRes);
9573 }
9574 Action action = new Action.Builder(Icon.createWithResource("", icon),
9575 new SpannableStringBuilder().append(mBuilder.mContext.getString(title),
9576 new ForegroundColorSpan(colorInt),
9577 SpannableStringBuilder.SPAN_INCLUSIVE_INCLUSIVE),
9578 intent).build();
9579 action.getExtras().putBoolean(KEY_ACTION_PRIORITY, true);
9580 return action;
9581 }
9582
9583 private boolean isActionAddedByCallStyle(Action action) {
9584 // This is an internal extra added by the style to these actions. If an app were to add
9585 // this extra to the action themselves, the action would be dropped. :shrug:
9586 return action != null && action.getExtras().getBoolean(KEY_ACTION_PRIORITY);
9587 }
9588
9589 /**
9590 * Gets the actions list for the call with the answer/decline/hangUp actions inserted in
9591 * the correct place. This returns the correct result even if the system actions have
9592 * already been added, and even if more actions were added since then.
9593 * @hide
9594 */
9595 @NonNull
9596 public ArrayList<Action> getActionsListWithSystemActions() {
9597 // Define the system actions we expect to see
9598 final Action firstAction = makeNegativeAction();
9599 final Action lastAction = makeAnswerAction();
9600
9601 // Start creating the result list.
9602 int nonContextualActionSlotsRemaining = MAX_ACTION_BUTTONS;
9603 ArrayList<Action> resultActions = new ArrayList<>(MAX_ACTION_BUTTONS);
9604
9605 // Always have a first action.
9606 resultActions.add(firstAction);
9607 --nonContextualActionSlotsRemaining;
9608
9609 // Copy actions into the new list, correcting system actions.
9610 if (mBuilder.mActions != null) {
9611 for (Notification.Action action : mBuilder.mActions) {
9612 if (action.isContextual()) {
9613 // Always include all contextual actions
9614 resultActions.add(action);
9615 } else if (isActionAddedByCallStyle(action)) {
9616 // Drop any old versions of system actions
9617 } else {
9618 // Copy non-contextual actions; decrement the remaining action slots.
9619 resultActions.add(action);
9620 --nonContextualActionSlotsRemaining;
9621 }
9622 // If there's exactly one action slot left, fill it with the lastAction.
9623 if (lastAction != null && nonContextualActionSlotsRemaining == 1) {
9624 resultActions.add(lastAction);
9625 --nonContextualActionSlotsRemaining;
9626 }
9627 }
9628 }
9629 // If there are any action slots left, the lastAction still needs to be added.
9630 if (lastAction != null && nonContextualActionSlotsRemaining >= 1) {
9631 resultActions.add(lastAction);
9632 }
9633 return resultActions;
9634 }
9635
9636 private RemoteViews makeCallLayout(int viewType) {
9637 final boolean isCollapsed = viewType == StandardTemplateParams.VIEW_TYPE_NORMAL;
9638 Bundle extras = mBuilder.mN.extras;
9639 CharSequence title = mPerson != null ? mPerson.getName() : null;
9640 CharSequence text = mBuilder.processLegacyText(extras.getCharSequence(EXTRA_TEXT));
9641 if (text == null) {
9642 text = getDefaultText();
9643 }
9644
9645 // Bind standard template
9646 StandardTemplateParams p = mBuilder.mParams.reset()
9647 .viewType(viewType)
9648 .callStyleActions(true)
9649 .allowTextWithProgress(true)
9650 .hideLeftIcon(true)
9651 .hideRightIcon(true)
9652 .hideAppName(isCollapsed)
9653 .titleViewId(R.id.conversation_text)
9654 .title(title)
9655 .text(text)
9656 .summaryText(mBuilder.processLegacyText(mVerificationText));
9657 mBuilder.mActions = getActionsListWithSystemActions();
9658 final RemoteViews contentView;
9659 if (isCollapsed) {
9660 contentView = mBuilder.applyStandardTemplate(
9661 R.layout.notification_template_material_call, p, null /* result */);
9662 } else {
9663 contentView = mBuilder.applyStandardTemplateWithActions(
9664 R.layout.notification_template_material_big_call, p, null /* result */);
9665 }
9666
9667 // Bind some extra conversation-specific header fields.
9668 if (!p.mHideAppName) {
9669 mBuilder.setTextViewColorSecondary(contentView, R.id.app_name_divider, p);
9670 contentView.setViewVisibility(R.id.app_name_divider, View.VISIBLE);
9671 }
9672 bindCallerVerification(contentView, p);
9673
9674 // Bind some custom CallLayout properties
9675 contentView.setInt(R.id.status_bar_latest_event_content, "setLayoutColor",
9676 mBuilder.getSmallIconColor(p));
9677 contentView.setInt(R.id.status_bar_latest_event_content,
9678 "setNotificationBackgroundColor", mBuilder.getBackgroundColor(p));
9679 contentView.setIcon(R.id.status_bar_latest_event_content, "setLargeIcon",
9680 mBuilder.mN.mLargeIcon);
9681 contentView.setBundle(R.id.status_bar_latest_event_content, "setData",
9682 mBuilder.mN.extras);
9683
9684 return contentView;
9685 }
9686
9687 private void bindCallerVerification(RemoteViews contentView, StandardTemplateParams p) {
9688 String iconContentDescription = null;
9689 boolean showDivider = true;
9690 if (mVerificationIcon != null) {
9691 contentView.setImageViewIcon(R.id.verification_icon, mVerificationIcon);
9692 contentView.setDrawableTint(R.id.verification_icon, false /* targetBackground */,
9693 mBuilder.getSecondaryTextColor(p), PorterDuff.Mode.SRC_ATOP);
9694 contentView.setViewVisibility(R.id.verification_icon, View.VISIBLE);
9695 iconContentDescription = mBuilder.mContext.getString(
9696 R.string.notification_verified_content_description);
9697 showDivider = false; // the icon replaces the divider
9698 } else {
9699 contentView.setViewVisibility(R.id.verification_icon, View.GONE);
9700 }
9701 if (!TextUtils.isEmpty(mVerificationText)) {
9702 contentView.setTextViewText(R.id.verification_text, mVerificationText);
9703 mBuilder.setTextViewColorSecondary(contentView, R.id.verification_text, p);
9704 contentView.setViewVisibility(R.id.verification_text, View.VISIBLE);
9705 iconContentDescription = null; // let the app's text take precedence
9706 } else {
9707 contentView.setViewVisibility(R.id.verification_text, View.GONE);
9708 showDivider = false; // no divider if no text
9709 }
9710 contentView.setContentDescription(R.id.verification_icon, iconContentDescription);
9711 if (showDivider) {
9712 contentView.setViewVisibility(R.id.verification_divider, View.VISIBLE);
9713 mBuilder.setTextViewColorSecondary(contentView, R.id.verification_divider, p);
9714 } else {
9715 contentView.setViewVisibility(R.id.verification_divider, View.GONE);
9716 }
9717 }
9718
9719 @Nullable
9720 private String getDefaultText() {
9721 switch (mCallType) {
9722 case CALL_TYPE_INCOMING:
9723 return mBuilder.mContext.getString(R.string.call_notification_incoming_text);
9724 case CALL_TYPE_ONGOING:
9725 return mBuilder.mContext.getString(R.string.call_notification_ongoing_text);
9726 case CALL_TYPE_SCREENING:
9727 return mBuilder.mContext.getString(R.string.call_notification_screening_text);
9728 }
9729 return null;
9730 }
9731
9732 /**
9733 * @hide
9734 */
9735 public void addExtras(Bundle extras) {
9736 super.addExtras(extras);
9737 extras.putInt(EXTRA_CALL_TYPE, mCallType);
9738 extras.putBoolean(EXTRA_CALL_IS_VIDEO, mIsVideo);
9739 extras.putParcelable(EXTRA_CALL_PERSON, mPerson);
9740 if (mVerificationIcon != null) {
9741 extras.putParcelable(EXTRA_VERIFICATION_ICON, mVerificationIcon);
9742 }
9743 if (mVerificationText != null) {
9744 extras.putCharSequence(EXTRA_VERIFICATION_TEXT, mVerificationText);
9745 }
9746 if (mAnswerIntent != null) {
9747 extras.putParcelable(EXTRA_ANSWER_INTENT, mAnswerIntent);
9748 }
9749 if (mDeclineIntent != null) {
9750 extras.putParcelable(EXTRA_DECLINE_INTENT, mDeclineIntent);
9751 }
9752 if (mHangUpIntent != null) {
9753 extras.putParcelable(EXTRA_HANG_UP_INTENT, mHangUpIntent);
9754 }
9755 if (mAnswerButtonColor != null) {
9756 extras.putInt(EXTRA_ANSWER_COLOR, mAnswerButtonColor);
9757 }
9758 if (mDeclineButtonColor != null) {
9759 extras.putInt(EXTRA_DECLINE_COLOR, mDeclineButtonColor);
9760 }
9761 fixTitleAndTextExtras(extras);
9762 }
9763
9764 private void fixTitleAndTextExtras(Bundle extras) {
9765 CharSequence sender = mPerson != null ? mPerson.getName() : null;
9766 if (sender != null) {
9767 extras.putCharSequence(EXTRA_TITLE, sender);
9768 }
9769 if (extras.getCharSequence(EXTRA_TEXT) == null) {
9770 extras.putCharSequence(EXTRA_TEXT, getDefaultText());
9771 }
9772 }
9773
9774 /**
9775 * @hide
9776 */
9777 @Override
9778 protected void restoreFromExtras(Bundle extras) {
9779 super.restoreFromExtras(extras);
9780 mCallType = extras.getInt(EXTRA_CALL_TYPE);
9781 mIsVideo = extras.getBoolean(EXTRA_CALL_IS_VIDEO);
9782 mPerson = extras.getParcelable(EXTRA_CALL_PERSON, Person.class);
9783 mVerificationIcon = extras.getParcelable(EXTRA_VERIFICATION_ICON);
9784 mVerificationText = extras.getCharSequence(EXTRA_VERIFICATION_TEXT);
9785 mAnswerIntent = extras.getParcelable(EXTRA_ANSWER_INTENT, PendingIntent.class);
9786 mDeclineIntent = extras.getParcelable(EXTRA_DECLINE_INTENT, PendingIntent.class);
9787 mHangUpIntent = extras.getParcelable(EXTRA_HANG_UP_INTENT, PendingIntent.class);
9788 mAnswerButtonColor = extras.containsKey(EXTRA_ANSWER_COLOR)
9789 ? extras.getInt(EXTRA_ANSWER_COLOR) : null;
9790 mDeclineButtonColor = extras.containsKey(EXTRA_DECLINE_COLOR)
9791 ? extras.getInt(EXTRA_DECLINE_COLOR) : null;
9792 }
9793
9794 /**
9795 * @hide
9796 */
9797 @Override
9798 public boolean hasSummaryInHeader() {
9799 return false;
9800 }
9801
9802 /**
9803 * @hide
9804 */
9805 @Override
9806 public boolean areNotificationsVisiblyDifferent(Style other) {
9807 if (other == null || getClass() != other.getClass()) {
9808 return true;
9809 }
9810 CallStyle otherS = (CallStyle) other;
9811 return !Objects.equals(mCallType, otherS.mCallType)
9812 || !Objects.equals(mPerson, otherS.mPerson)
9813 || !Objects.equals(mVerificationText, otherS.mVerificationText);
9814 }
9815 }
9816
9817 /**
9818 * Notification style for custom views that are decorated by the system
9819 *
9820 * <p>Instead of providing a notification that is completely custom, a developer can set this
9821 * style and still obtain system decorations like the notification header with the expand
9822 * affordance and actions.
9823 *
9824 * <p>Use {@link android.app.Notification.Builder#setCustomContentView(RemoteViews)},
9825 * {@link android.app.Notification.Builder#setCustomBigContentView(RemoteViews)} and
9826 * {@link android.app.Notification.Builder#setCustomHeadsUpContentView(RemoteViews)} to set the
9827 * corresponding custom views to display.
9828 *
9829 * To use this style with your Notification, feed it to
9830 * {@link Notification.Builder#setStyle(android.app.Notification.Style)} like so:
9831 * <pre class="prettyprint">
9832 * Notification noti = new Notification.Builder()
9833 * .setSmallIcon(R.drawable.ic_stat_player)
9834 * .setLargeIcon(albumArtBitmap))
9835 * .setCustomContentView(contentView);
9836 * .setStyle(<b>new Notification.DecoratedCustomViewStyle()</b>)
9837 * .build();
9838 * </pre>
9839 */
9840 public static class DecoratedCustomViewStyle extends Style {
9841
9842 public DecoratedCustomViewStyle() {
9843 }
9844
9845 /**
9846 * @hide
9847 */
9848 public boolean displayCustomViewInline() {
9849 return true;
9850 }
9851
9852 /**
9853 * @hide
9854 */
9855 @Override
9856 public RemoteViews makeContentView(boolean increasedHeight) {
9857 return makeStandardTemplateWithCustomContent(mBuilder.mN.contentView);
9858 }
9859
9860 /**
9861 * @hide
9862 */
9863 @Override
9864 public RemoteViews makeBigContentView() {
9865 return makeDecoratedBigContentView();
9866 }
9867
9868 /**
9869 * @hide
9870 */
9871 @Override
9872 public RemoteViews makeHeadsUpContentView(boolean increasedHeight) {
9873 return makeDecoratedHeadsUpContentView();
9874 }
9875
9876 private RemoteViews makeDecoratedHeadsUpContentView() {
9877 RemoteViews headsUpContentView = mBuilder.mN.headsUpContentView == null
9878 ? mBuilder.mN.contentView
9879 : mBuilder.mN.headsUpContentView;
9880 if (headsUpContentView == null) {
9881 return null; // no custom view; use the default behavior
9882 }
9883 if (mBuilder.mActions.size() == 0) {
9884 return makeStandardTemplateWithCustomContent(headsUpContentView);
9885 }
9886 TemplateBindResult result = new TemplateBindResult();
9887 StandardTemplateParams p = mBuilder.mParams.reset()
9888 .viewType(StandardTemplateParams.VIEW_TYPE_HEADS_UP)
9889 .decorationType(StandardTemplateParams.DECORATION_PARTIAL)
9890 .fillTextsFrom(mBuilder);
9891 RemoteViews remoteViews = mBuilder.applyStandardTemplateWithActions(
9892 mBuilder.getHeadsUpBaseLayoutResource(), p, result);
9893 buildCustomContentIntoTemplate(mBuilder.mContext, remoteViews, headsUpContentView,
9894 p, result);
9895 return remoteViews;
9896 }
9897
9898 private RemoteViews makeStandardTemplateWithCustomContent(RemoteViews customContent) {
9899 if (customContent == null) {
9900 return null; // no custom view; use the default behavior
9901 }
9902 TemplateBindResult result = new TemplateBindResult();
9903 StandardTemplateParams p = mBuilder.mParams.reset()
9904 .viewType(StandardTemplateParams.VIEW_TYPE_NORMAL)
9905 .decorationType(StandardTemplateParams.DECORATION_PARTIAL)
9906 .fillTextsFrom(mBuilder);
9907 RemoteViews remoteViews = mBuilder.applyStandardTemplate(
9908 mBuilder.getBaseLayoutResource(), p, result);
9909 buildCustomContentIntoTemplate(mBuilder.mContext, remoteViews, customContent,
9910 p, result);
9911 return remoteViews;
9912 }
9913
9914 private RemoteViews makeDecoratedBigContentView() {
9915 RemoteViews bigContentView = mBuilder.mN.bigContentView == null
9916 ? mBuilder.mN.contentView
9917 : mBuilder.mN.bigContentView;
9918 if (bigContentView == null) {
9919 return null; // no custom view; use the default behavior
9920 }
9921 TemplateBindResult result = new TemplateBindResult();
9922 StandardTemplateParams p = mBuilder.mParams.reset()
9923 .viewType(StandardTemplateParams.VIEW_TYPE_BIG)
9924 .decorationType(StandardTemplateParams.DECORATION_PARTIAL)
9925 .fillTextsFrom(mBuilder);
9926 RemoteViews remoteViews = mBuilder.applyStandardTemplateWithActions(
9927 mBuilder.getBigBaseLayoutResource(), p, result);
9928 buildCustomContentIntoTemplate(mBuilder.mContext, remoteViews, bigContentView,
9929 p, result);
9930 return remoteViews;
9931 }
9932
9933 /**
9934 * @hide
9935 */
9936 @Override
9937 public boolean areNotificationsVisiblyDifferent(Style other) {
9938 if (other == null || getClass() != other.getClass()) {
9939 return true;
9940 }
9941 // Comparison done for all custom RemoteViews, independent of style
9942 return false;
9943 }
9944 }
9945
9946 /**
9947 * Notification style for media custom views that are decorated by the system
9948 *
9949 * <p>Instead of providing a media notification that is completely custom, a developer can set
9950 * this style and still obtain system decorations like the notification header with the expand
9951 * affordance and actions.
9952 *
9953 * <p>Use {@link android.app.Notification.Builder#setCustomContentView(RemoteViews)},
9954 * {@link android.app.Notification.Builder#setCustomBigContentView(RemoteViews)} and
9955 * {@link android.app.Notification.Builder#setCustomHeadsUpContentView(RemoteViews)} to set the
9956 * corresponding custom views to display.
9957 * <p>
9958 * Contrary to {@link MediaStyle} a developer has to opt-in to the colorizing of the
9959 * notification by using {@link Notification.Builder#setColorized(boolean)}.
9960 * <p>
9961 * To use this style with your Notification, feed it to
9962 * {@link Notification.Builder#setStyle(android.app.Notification.Style)} like so:
9963 * <pre class="prettyprint">
9964 * Notification noti = new Notification.Builder()
9965 * .setSmallIcon(R.drawable.ic_stat_player)
9966 * .setLargeIcon(albumArtBitmap))
9967 * .setCustomContentView(contentView);
9968 * .setStyle(<b>new Notification.DecoratedMediaCustomViewStyle()</b>
9969 * .setMediaSession(mySession))
9970 * .build();
9971 * </pre>
9972 *
9973 * @see android.app.Notification.DecoratedCustomViewStyle
9974 * @see android.app.Notification.MediaStyle
9975 */
9976 public static class DecoratedMediaCustomViewStyle extends MediaStyle {
9977
9978 public DecoratedMediaCustomViewStyle() {
9979 }
9980
9981 /**
9982 * @hide
9983 */
9984 public boolean displayCustomViewInline() {
9985 return true;
9986 }
9987
9988 /**
9989 * @hide
9990 */
9991 @Override
9992 public RemoteViews makeContentView(boolean increasedHeight) {
9993 return makeMediaContentView(mBuilder.mN.contentView);
9994 }
9995
9996 /**
9997 * @hide
9998 */
9999 @Override
10000 public RemoteViews makeBigContentView() {
10001 RemoteViews customContent = mBuilder.mN.bigContentView != null
10002 ? mBuilder.mN.bigContentView
10003 : mBuilder.mN.contentView;
10004 return makeMediaBigContentView(customContent);
10005 }
10006
10007 /**
10008 * @hide
10009 */
10010 @Override
10011 public RemoteViews makeHeadsUpContentView(boolean increasedHeight) {
10012 RemoteViews customContent = mBuilder.mN.headsUpContentView != null
10013 ? mBuilder.mN.headsUpContentView
10014 : mBuilder.mN.contentView;
10015 return makeMediaBigContentView(customContent);
10016 }
10017
10018 /**
10019 * @hide
10020 */
10021 @Override
10022 public boolean areNotificationsVisiblyDifferent(Style other) {
10023 if (other == null || getClass() != other.getClass()) {
10024 return true;
10025 }
10026 // Comparison done for all custom RemoteViews, independent of style
10027 return false;
10028 }
10029 }
10030
10031 /**
10032 * Encapsulates the information needed to display a notification as a bubble.
10033 *
10034 * <p>A bubble is used to display app content in a floating window over the existing
10035 * foreground activity. A bubble has a collapsed state represented by an icon and an
10036 * expanded state that displays an activity. These may be defined via
10037 * {@link Builder#Builder(PendingIntent, Icon)} or they may
10038 * be defined via an existing shortcut using {@link Builder#Builder(String)}.
10039 * </p>
10040 *
10041 * <b>Notifications with a valid and allowed bubble will display in collapsed state
10042 * outside of the notification shade on unlocked devices. When a user interacts with the
10043 * collapsed bubble, the bubble activity will be invoked and displayed.</b>
10044 *
10045 * @see Notification.Builder#setBubbleMetadata(BubbleMetadata)
10046 */
10047 public static final class BubbleMetadata implements Parcelable {
10048
10049 private PendingIntent mPendingIntent;
10050 private PendingIntent mDeleteIntent;
10051 private Icon mIcon;
10052 private int mDesiredHeight;
10053 @DimenRes private int mDesiredHeightResId;
10054 private int mFlags;
10055 private String mShortcutId;
10056
10057 /**
10058 * If set and the app creating the bubble is in the foreground, the bubble will be posted
10059 * in its expanded state.
10060 *
10061 * <p>This flag has no effect if the app posting the bubble is not in the foreground.
10062 * The app is considered foreground if it is visible and on the screen, note that
10063 * a foreground service does not qualify.
10064 * </p>
10065 *
10066 * <p>Generally this flag should only be set if the user has performed an action to request
10067 * or create a bubble.</p>
10068 *
10069 * @hide
10070 */
10071 public static final int FLAG_AUTO_EXPAND_BUBBLE = 0x00000001;
10072
10073 /**
10074 * Indicates whether the notification associated with the bubble is being visually
10075 * suppressed from the notification shade. When <code>true</code> the notification is
10076 * hidden, when <code>false</code> the notification shows as normal.
10077 *
10078 * <p>Apps sending bubbles may set this flag so that the bubble is posted <b>without</b>
10079 * the associated notification in the notification shade.</p>
10080 *
10081 * <p>Generally this flag should only be set by the app if the user has performed an
10082 * action to request or create a bubble, or if the user has seen the content in the
10083 * notification and the notification is no longer relevant. </p>
10084 *
10085 * <p>The system will also update this flag with <code>true</code> to hide the notification
10086 * from the user once the bubble has been expanded. </p>
10087 *
10088 * @hide
10089 */
10090 public static final int FLAG_SUPPRESS_NOTIFICATION = 0x00000002;
10091
10092 /**
10093 * Indicates whether the bubble should be visually suppressed from the bubble stack if the
10094 * user is viewing the same content outside of the bubble. For example, the user has a
10095 * bubble with Alice and then opens up the main app and navigates to Alice's page.
10096 *
10097 * @hide
10098 */
10099 public static final int FLAG_SUPPRESSABLE_BUBBLE = 0x00000004;
10100
10101 /**
10102 * Indicates whether the bubble is visually suppressed from the bubble stack.
10103 *
10104 * @hide
10105 */
10106 public static final int FLAG_SUPPRESS_BUBBLE = 0x00000008;
10107
10108 private BubbleMetadata(PendingIntent expandIntent, PendingIntent deleteIntent,
10109 Icon icon, int height, @DimenRes int heightResId, String shortcutId) {
10110 mPendingIntent = expandIntent;
10111 mIcon = icon;
10112 mDesiredHeight = height;
10113 mDesiredHeightResId = heightResId;
10114 mDeleteIntent = deleteIntent;
10115 mShortcutId = shortcutId;
10116 }
10117
10118 private BubbleMetadata(Parcel in) {
10119 if (in.readInt() != 0) {
10120 mPendingIntent = PendingIntent.CREATOR.createFromParcel(in);
10121 }
10122 if (in.readInt() != 0) {
10123 mIcon = Icon.CREATOR.createFromParcel(in);
10124 }
10125 mDesiredHeight = in.readInt();
10126 mFlags = in.readInt();
10127 if (in.readInt() != 0) {
10128 mDeleteIntent = PendingIntent.CREATOR.createFromParcel(in);
10129 }
10130 mDesiredHeightResId = in.readInt();
10131 if (in.readInt() != 0) {
10132 mShortcutId = in.readString8();
10133 }
10134 }
10135
10136 /**
10137 * @return the shortcut id used for this bubble if created via
10138 * {@link Builder#Builder(String)} or null if created
10139 * via {@link Builder#Builder(PendingIntent, Icon)}.
10140 */
10141 @Nullable
10142 public String getShortcutId() {
10143 return mShortcutId;
10144 }
10145
10146 /**
10147 * @return the pending intent used to populate the floating window for this bubble, or
10148 * null if this bubble is created via {@link Builder#Builder(String)}.
10149 */
10150 @SuppressLint("InvalidNullConversion")
10151 @Nullable
10152 public PendingIntent getIntent() {
10153 return mPendingIntent;
10154 }
10155
10156 /**
10157 * @deprecated use {@link #getIntent()} instead.
10158 * @removed Removed from the R SDK but was never publicly stable.
10159 */
10160 @Nullable
10161 @Deprecated
10162 public PendingIntent getBubbleIntent() {
10163 return mPendingIntent;
10164 }
10165
10166 /**
10167 * @return the pending intent to send when the bubble is dismissed by a user, if one exists.
10168 */
10169 @Nullable
10170 public PendingIntent getDeleteIntent() {
10171 return mDeleteIntent;
10172 }
10173
10174 /**
10175 * @return the icon that will be displayed for this bubble when it is collapsed, or null
10176 * if the bubble is created via {@link Builder#Builder(String)}.
10177 */
10178 @SuppressLint("InvalidNullConversion")
10179 @Nullable
10180 public Icon getIcon() {
10181 return mIcon;
10182 }
10183
10184 /**
10185 * @deprecated use {@link #getIcon()} instead.
10186 * @removed Removed from the R SDK but was never publicly stable.
10187 */
10188 @Nullable
10189 @Deprecated
10190 public Icon getBubbleIcon() {
10191 return mIcon;
10192 }
10193
10194 /**
10195 * @return the ideal height, in DPs, for the floating window that app content defined by
10196 * {@link #getIntent()} for this bubble. A value of 0 indicates a desired height has
10197 * not been set.
10198 */
10199 @Dimension(unit = DP)
10200 public int getDesiredHeight() {
10201 return mDesiredHeight;
10202 }
10203
10204 /**
10205 * @return the resId of ideal height for the floating window that app content defined by
10206 * {@link #getIntent()} for this bubble. A value of 0 indicates a res value has not
10207 * been provided for the desired height.
10208 */
10209 @DimenRes
10210 public int getDesiredHeightResId() {
10211 return mDesiredHeightResId;
10212 }
10213
10214 /**
10215 * @return whether this bubble should auto expand when it is posted.
10216 *
10217 * @see BubbleMetadata.Builder#setAutoExpandBubble(boolean)
10218 */
10219 public boolean getAutoExpandBubble() {
10220 return (mFlags & FLAG_AUTO_EXPAND_BUBBLE) != 0;
10221 }
10222
10223 /**
10224 * Indicates whether the notification associated with the bubble is being visually
10225 * suppressed from the notification shade. When <code>true</code> the notification is
10226 * hidden, when <code>false</code> the notification shows as normal.
10227 *
10228 * <p>Apps sending bubbles may set this flag so that the bubble is posted <b>without</b>
10229 * the associated notification in the notification shade.</p>
10230 *
10231 * <p>Generally the app should only set this flag if the user has performed an
10232 * action to request or create a bubble, or if the user has seen the content in the
10233 * notification and the notification is no longer relevant. </p>
10234 *
10235 * <p>The system will update this flag with <code>true</code> to hide the notification
10236 * from the user once the bubble has been expanded.</p>
10237 *
10238 * @return whether this bubble should suppress the notification when it is posted.
10239 *
10240 * @see BubbleMetadata.Builder#setSuppressNotification(boolean)
10241 */
10242 public boolean isNotificationSuppressed() {
10243 return (mFlags & FLAG_SUPPRESS_NOTIFICATION) != 0;
10244 }
10245
10246 /**
10247 * Indicates whether the bubble should be visually suppressed from the bubble stack if the
10248 * user is viewing the same content outside of the bubble. For example, the user has a
10249 * bubble with Alice and then opens up the main app and navigates to Alice's page.
10250 *
10251 * To match the activity and the bubble notification, the bubble notification should
10252 * have a locus id set that matches a locus id set on the activity.
10253 *
10254 * @return whether this bubble should be suppressed when the same content is visible
10255 * outside of the bubble.
10256 *
10257 * @see BubbleMetadata.Builder#setSuppressableBubble(boolean)
10258 */
10259 public boolean isBubbleSuppressable() {
10260 return (mFlags & FLAG_SUPPRESSABLE_BUBBLE) != 0;
10261 }
10262
10263 /**
10264 * Indicates whether the bubble is currently visually suppressed from the bubble stack.
10265 *
10266 * @see BubbleMetadata.Builder#setSuppressableBubble(boolean)
10267 */
10268 public boolean isBubbleSuppressed() {
10269 return (mFlags & FLAG_SUPPRESS_BUBBLE) != 0;
10270 }
10271
10272 /**
10273 * Sets whether the notification associated with the bubble is being visually
10274 * suppressed from the notification shade. When <code>true</code> the notification is
10275 * hidden, when <code>false</code> the notification shows as normal.
10276 *
10277 * @hide
10278 */
10279 public void setSuppressNotification(boolean suppressed) {
10280 if (suppressed) {
10281 mFlags |= Notification.BubbleMetadata.FLAG_SUPPRESS_NOTIFICATION;
10282 } else {
10283 mFlags &= ~Notification.BubbleMetadata.FLAG_SUPPRESS_NOTIFICATION;
10284 }
10285 }
10286
10287 /**
10288 * Sets whether the bubble should be visually suppressed from the bubble stack if the
10289 * user is viewing the same content outside of the bubble. For example, the user has a
10290 * bubble with Alice and then opens up the main app and navigates to Alice's page.
10291 *
10292 * @hide
10293 */
10294 public void setSuppressBubble(boolean suppressed) {
10295 if (suppressed) {
10296 mFlags |= Notification.BubbleMetadata.FLAG_SUPPRESS_BUBBLE;
10297 } else {
10298 mFlags &= ~Notification.BubbleMetadata.FLAG_SUPPRESS_BUBBLE;
10299 }
10300 }
10301
10302 /**
10303 * @hide
10304 */
10305 public void setFlags(int flags) {
10306 mFlags = flags;
10307 }
10308
10309 /**
10310 * @hide
10311 */
10312 public int getFlags() {
10313 return mFlags;
10314 }
10315
10316 public static final @android.annotation.NonNull Parcelable.Creator<BubbleMetadata> CREATOR =
10317 new Parcelable.Creator<BubbleMetadata>() {
10318
10319 @Override
10320 public BubbleMetadata createFromParcel(Parcel source) {
10321 return new BubbleMetadata(source);
10322 }
10323
10324 @Override
10325 public BubbleMetadata[] newArray(int size) {
10326 return new BubbleMetadata[size];
10327 }
10328 };
10329
10330 @Override
10331 public int describeContents() {
10332 return 0;
10333 }
10334
10335 @Override
10336 public void writeToParcel(Parcel out, int flags) {
10337 out.writeInt(mPendingIntent != null ? 1 : 0);
10338 if (mPendingIntent != null) {
10339 mPendingIntent.writeToParcel(out, 0);
10340 }
10341 out.writeInt(mIcon != null ? 1 : 0);
10342 if (mIcon != null) {
10343 mIcon.writeToParcel(out, 0);
10344 }
10345 out.writeInt(mDesiredHeight);
10346 out.writeInt(mFlags);
10347 out.writeInt(mDeleteIntent != null ? 1 : 0);
10348 if (mDeleteIntent != null) {
10349 mDeleteIntent.writeToParcel(out, 0);
10350 }
10351 out.writeInt(mDesiredHeightResId);
10352 out.writeInt(TextUtils.isEmpty(mShortcutId) ? 0 : 1);
10353 if (!TextUtils.isEmpty(mShortcutId)) {
10354 out.writeString8(mShortcutId);
10355 }
10356 }
10357
10358 /**
10359 * Builder to construct a {@link BubbleMetadata} object.
10360 */
10361 public static final class Builder {
10362
10363 private PendingIntent mPendingIntent;
10364 private Icon mIcon;
10365 private int mDesiredHeight;
10366 @DimenRes private int mDesiredHeightResId;
10367 private int mFlags;
10368 private PendingIntent mDeleteIntent;
10369 private String mShortcutId;
10370
10371 /**
10372 * @deprecated use {@link Builder#Builder(String)} for a bubble created via a
10373 * {@link ShortcutInfo} or {@link Builder#Builder(PendingIntent, Icon)} for a bubble
10374 * created via a {@link PendingIntent}.
10375 */
10376 @Deprecated
10377 public Builder() {
10378 }
10379
10380 /**
10381 * Creates a {@link BubbleMetadata.Builder} based on a {@link ShortcutInfo}. To create
10382 * a shortcut bubble, ensure that the shortcut associated with the provided
10383 * {@param shortcutId} is published as a dynamic shortcut that was built with
10384 * {@link ShortcutInfo.Builder#setLongLived(boolean)} being true, otherwise your
10385 * notification will not be able to bubble.
10386 *
10387 * <p>The shortcut icon will be used to represent the bubble when it is collapsed.</p>
10388 *
10389 * <p>The shortcut activity will be used when the bubble is expanded. This will display
10390 * the shortcut activity in a floating window over the existing foreground activity.</p>
10391 *
10392 * <p>When the activity is launched from a bubble,
10393 * {@link Activity#isLaunchedFromBubble()} will return with {@code true}.
10394 * </p>
10395 *
10396 * <p>If the shortcut has not been published when the bubble notification is sent,
10397 * no bubble will be produced. If the shortcut is deleted while the bubble is active,
10398 * the bubble will be removed.</p>
10399 *
10400 * @throws NullPointerException if shortcutId is null.
10401 *
10402 * @see ShortcutInfo
10403 * @see ShortcutInfo.Builder#setLongLived(boolean)
10404 * @see android.content.pm.ShortcutManager#addDynamicShortcuts(List)
10405 */
10406 public Builder(@NonNull String shortcutId) {
10407 if (TextUtils.isEmpty(shortcutId)) {
10408 throw new NullPointerException("Bubble requires a non-null shortcut id");
10409 }
10410 mShortcutId = shortcutId;
10411 }
10412
10413 /**
10414 * Creates a {@link BubbleMetadata.Builder} based on the provided intent and icon.
10415 *
10416 * <p>The icon will be used to represent the bubble when it is collapsed. An icon
10417 * should be representative of the content within the bubble. If your app produces
10418 * multiple bubbles, the icon should be unique for each of them.</p>
10419 *
10420 * <p>The intent that will be used when the bubble is expanded. This will display the
10421 * app content in a floating window over the existing foreground activity. The intent
10422 * should point to a resizable activity. </p>
10423 *
10424 * <p>When the activity is launched from a bubble,
10425 * {@link Activity#isLaunchedFromBubble()} will return with {@code true}.
10426 * </p>
10427 *
10428 * Note that the pending intent used here requires PendingIntent.FLAG_MUTABLE.
10429 *
10430 * @throws NullPointerException if intent is null.
10431 * @throws NullPointerException if icon is null.
10432 */
10433 public Builder(@NonNull PendingIntent intent, @NonNull Icon icon) {
10434 if (intent == null) {
10435 throw new NullPointerException("Bubble requires non-null pending intent");
10436 }
10437 if (icon == null) {
10438 throw new NullPointerException("Bubbles require non-null icon");
10439 }
10440 if (icon.getType() != TYPE_URI_ADAPTIVE_BITMAP
10441 && icon.getType() != TYPE_URI) {
10442 Log.w(TAG, "Bubbles work best with icons of TYPE_URI or "
10443 + "TYPE_URI_ADAPTIVE_BITMAP. "
10444 + "In the future, using an icon of this type will be required.");
10445 }
10446 mPendingIntent = intent;
10447 mIcon = icon;
10448 }
10449
10450 /**
10451 * @deprecated use {@link Builder#Builder(String)} instead.
10452 * @removed Removed from the R SDK but was never publicly stable.
10453 */
10454 @NonNull
10455 @Deprecated
10456 public BubbleMetadata.Builder createShortcutBubble(@NonNull String shortcutId) {
10457 if (!TextUtils.isEmpty(shortcutId)) {
10458 // If shortcut id is set, we don't use these if they were previously set.
10459 mPendingIntent = null;
10460 mIcon = null;
10461 }
10462 mShortcutId = shortcutId;
10463 return this;
10464 }
10465
10466 /**
10467 * @deprecated use {@link Builder#Builder(PendingIntent, Icon)} instead.
10468 * @removed Removed from the R SDK but was never publicly stable.
10469 */
10470 @NonNull
10471 @Deprecated
10472 public BubbleMetadata.Builder createIntentBubble(@NonNull PendingIntent intent,
10473 @NonNull Icon icon) {
10474 if (intent == null) {
10475 throw new IllegalArgumentException("Bubble requires non-null pending intent");
10476 }
10477 if (icon == null) {
10478 throw new IllegalArgumentException("Bubbles require non-null icon");
10479 }
10480 if (icon.getType() != TYPE_URI_ADAPTIVE_BITMAP
10481 && icon.getType() != TYPE_URI) {
10482 Log.w(TAG, "Bubbles work best with icons of TYPE_URI or "
10483 + "TYPE_URI_ADAPTIVE_BITMAP. "
10484 + "In the future, using an icon of this type will be required.");
10485 }
10486 mShortcutId = null;
10487 mPendingIntent = intent;
10488 mIcon = icon;
10489 return this;
10490 }
10491
10492 /**
10493 * Sets the intent for the bubble.
10494 *
10495 * <p>The intent that will be used when the bubble is expanded. This will display the
10496 * app content in a floating window over the existing foreground activity. The intent
10497 * should point to a resizable activity. </p>
10498 *
10499 * @throws NullPointerException if intent is null.
10500 * @throws IllegalStateException if this builder was created via
10501 * {@link Builder#Builder(String)}.
10502 */
10503 @NonNull
10504 public BubbleMetadata.Builder setIntent(@NonNull PendingIntent intent) {
10505 if (mShortcutId != null) {
10506 throw new IllegalStateException("Created as a shortcut bubble, cannot set a "
10507 + "PendingIntent. Consider using "
10508 + "BubbleMetadata.Builder(PendingIntent,Icon) instead.");
10509 }
10510 if (intent == null) {
10511 throw new NullPointerException("Bubble requires non-null pending intent");
10512 }
10513 mPendingIntent = intent;
10514 return this;
10515 }
10516
10517 /**
10518 * Sets the icon for the bubble. Can only be used if the bubble was created
10519 * via {@link Builder#Builder(PendingIntent, Icon)}.
10520 *
10521 * <p>The icon will be used to represent the bubble when it is collapsed. An icon
10522 * should be representative of the content within the bubble. If your app produces
10523 * multiple bubbles, the icon should be unique for each of them.</p>
10524 *
10525 * <p>It is recommended to use an {@link Icon} of type {@link Icon#TYPE_URI}
10526 * or {@link Icon#TYPE_URI_ADAPTIVE_BITMAP}</p>
10527 *
10528 * @throws NullPointerException if icon is null.
10529 * @throws IllegalStateException if this builder was created via
10530 * {@link Builder#Builder(String)}.
10531 */
10532 @NonNull
10533 public BubbleMetadata.Builder setIcon(@NonNull Icon icon) {
10534 if (mShortcutId != null) {
10535 throw new IllegalStateException("Created as a shortcut bubble, cannot set an "
10536 + "Icon. Consider using "
10537 + "BubbleMetadata.Builder(PendingIntent,Icon) instead.");
10538 }
10539 if (icon == null) {
10540 throw new NullPointerException("Bubbles require non-null icon");
10541 }
10542 if (icon.getType() != TYPE_URI_ADAPTIVE_BITMAP
10543 && icon.getType() != TYPE_URI) {
10544 Log.w(TAG, "Bubbles work best with icons of TYPE_URI or "
10545 + "TYPE_URI_ADAPTIVE_BITMAP. "
10546 + "In the future, using an icon of this type will be required.");
10547 }
10548 mIcon = icon;
10549 return this;
10550 }
10551
10552 /**
10553 * Sets the desired height in DPs for the expanded content of the bubble.
10554 *
10555 * <p>This height may not be respected if there is not enough space on the screen or if
10556 * the provided height is too small to be useful.</p>
10557 *
10558 * <p>If {@link #setDesiredHeightResId(int)} was previously called on this builder, the
10559 * previous value set will be cleared after calling this method, and this value will
10560 * be used instead.</p>
10561 *
10562 * <p>A desired height (in DPs or via resID) is optional.</p>
10563 *
10564 * @see #setDesiredHeightResId(int)
10565 */
10566 @NonNull
10567 public BubbleMetadata.Builder setDesiredHeight(@Dimension(unit = DP) int height) {
10568 mDesiredHeight = Math.max(height, 0);
10569 mDesiredHeightResId = 0;
10570 return this;
10571 }
10572
10573
10574 /**
10575 * Sets the desired height via resId for the expanded content of the bubble.
10576 *
10577 * <p>This height may not be respected if there is not enough space on the screen or if
10578 * the provided height is too small to be useful.</p>
10579 *
10580 * <p>If {@link #setDesiredHeight(int)} was previously called on this builder, the
10581 * previous value set will be cleared after calling this method, and this value will
10582 * be used instead.</p>
10583 *
10584 * <p>A desired height (in DPs or via resID) is optional.</p>
10585 *
10586 * @see #setDesiredHeight(int)
10587 */
10588 @NonNull
10589 public BubbleMetadata.Builder setDesiredHeightResId(@DimenRes int heightResId) {
10590 mDesiredHeightResId = heightResId;
10591 mDesiredHeight = 0;
10592 return this;
10593 }
10594
10595 /**
10596 * Sets whether the bubble will be posted in its expanded state.
10597 *
10598 * <p>This flag has no effect if the app posting the bubble is not in the foreground.
10599 * The app is considered foreground if it is visible and on the screen, note that
10600 * a foreground service does not qualify.
10601 * </p>
10602 *
10603 * <p>Generally, this flag should only be set if the user has performed an action to
10604 * request or create a bubble.</p>
10605 *
10606 * <p>Setting this flag is optional; it defaults to false.</p>
10607 */
10608 @NonNull
10609 public BubbleMetadata.Builder setAutoExpandBubble(boolean shouldExpand) {
10610 setFlag(FLAG_AUTO_EXPAND_BUBBLE, shouldExpand);
10611 return this;
10612 }
10613
10614 /**
10615 * Sets whether the bubble will be posted <b>without</b> the associated notification in
10616 * the notification shade.
10617 *
10618 * <p>Generally, this flag should only be set if the user has performed an action to
10619 * request or create a bubble, or if the user has seen the content in the notification
10620 * and the notification is no longer relevant.</p>
10621 *
10622 * <p>Setting this flag is optional; it defaults to false.</p>
10623 */
10624 @NonNull
10625 public BubbleMetadata.Builder setSuppressNotification(boolean shouldSuppressNotif) {
10626 setFlag(FLAG_SUPPRESS_NOTIFICATION, shouldSuppressNotif);
10627 return this;
10628 }
10629
10630 /**
10631 * Indicates whether the bubble should be visually suppressed from the bubble stack if
10632 * the user is viewing the same content outside of the bubble. For example, the user has
10633 * a bubble with Alice and then opens up the main app and navigates to Alice's page.
10634 *
10635 * To match the activity and the bubble notification, the bubble notification should
10636 * have a locus id set that matches a locus id set on the activity.
10637 *
10638 * {@link Notification.Builder#setLocusId(LocusId)}
10639 * {@link Activity#setLocusContext(LocusId, Bundle)}
10640 */
10641 @NonNull
10642 public BubbleMetadata.Builder setSuppressableBubble(boolean suppressBubble) {
10643 setFlag(FLAG_SUPPRESSABLE_BUBBLE, suppressBubble);
10644 return this;
10645 }
10646
10647 /**
10648 * Sets an intent to send when this bubble is explicitly removed by the user.
10649 *
10650 * <p>Setting a delete intent is optional.</p>
10651 */
10652 @NonNull
10653 public BubbleMetadata.Builder setDeleteIntent(@Nullable PendingIntent deleteIntent) {
10654 mDeleteIntent = deleteIntent;
10655 return this;
10656 }
10657
10658 /**
10659 * Creates the {@link BubbleMetadata} defined by this builder.
10660 *
10661 * @throws NullPointerException if required elements have not been set.
10662 */
10663 @NonNull
10664 public BubbleMetadata build() {
10665 if (mShortcutId == null && mPendingIntent == null) {
10666 throw new NullPointerException(
10667 "Must supply pending intent or shortcut to bubble");
10668 }
10669 if (mShortcutId == null && mIcon == null) {
10670 throw new NullPointerException(
10671 "Must supply an icon or shortcut for the bubble");
10672 }
10673 BubbleMetadata data = new BubbleMetadata(mPendingIntent, mDeleteIntent,
10674 mIcon, mDesiredHeight, mDesiredHeightResId, mShortcutId);
10675 data.setFlags(mFlags);
10676 return data;
10677 }
10678
10679 /**
10680 * @hide
10681 */
10682 public BubbleMetadata.Builder setFlag(int mask, boolean value) {
10683 if (value) {
10684 mFlags |= mask;
10685 } else {
10686 mFlags &= ~mask;
10687 }
10688 return this;
10689 }
10690 }
10691 }
10692
10693
10694 // When adding a new Style subclass here, don't forget to update
10695 // Builder.getNotificationStyleClass.
10696
10697 /**
10698 * Extender interface for use with {@link Builder#extend}. Extenders may be used to add
10699 * metadata or change options on a notification builder.
10700 */
10701 public interface Extender {
10702 /**
10703 * Apply this extender to a notification builder.
10704 * @param builder the builder to be modified.
10705 * @return the build object for chaining.
10706 */
10707 public Builder extend(Builder builder);
10708 }
10709
10710 /**
10711 * Helper class to add wearable extensions to notifications.
10712 * <p class="note"> See
10713 * <a href="{@docRoot}wear/notifications/creating.html">Creating Notifications
10714 * for Android Wear</a> for more information on how to use this class.
10715 * <p>
10716 * To create a notification with wearable extensions:
10717 * <ol>
10718 * <li>Create a {@link android.app.Notification.Builder}, setting any desired
10719 * properties.
10720 * <li>Create a {@link android.app.Notification.WearableExtender}.
10721 * <li>Set wearable-specific properties using the
10722 * {@code add} and {@code set} methods of {@link android.app.Notification.WearableExtender}.
10723 * <li>Call {@link android.app.Notification.Builder#extend} to apply the extensions to a
10724 * notification.
10725 * <li>Post the notification to the notification system with the
10726 * {@code NotificationManager.notify(...)} methods.
10727 * </ol>
10728 *
10729 * <pre class="prettyprint">
10730 * Notification notif = new Notification.Builder(mContext)
10731 * .setContentTitle(&quot;New mail from &quot; + sender.toString())
10732 * .setContentText(subject)
10733 * .setSmallIcon(R.drawable.new_mail)
10734 * .extend(new Notification.WearableExtender()
10735 * .setContentIcon(R.drawable.new_mail))
10736 * .build();
10737 * NotificationManager notificationManger =
10738 * (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
10739 * notificationManger.notify(0, notif);</pre>
10740 *
10741 * <p>Wearable extensions can be accessed on an existing notification by using the
10742 * {@code WearableExtender(Notification)} constructor,
10743 * and then using the {@code get} methods to access values.
10744 *
10745 * <pre class="prettyprint">
10746 * Notification.WearableExtender wearableExtender = new Notification.WearableExtender(
10747 * notification);
10748 * List&lt;Notification&gt; pages = wearableExtender.getPages();</pre>
10749 */
10750 public static final class WearableExtender implements Extender {
10751 /**
10752 * Sentinel value for an action index that is unset.
10753 */
10754 public static final int UNSET_ACTION_INDEX = -1;
10755
10756 /**
10757 * Size value for use with {@link #setCustomSizePreset} to show this notification with
10758 * default sizing.
10759 * <p>For custom display notifications created using {@link #setDisplayIntent},
10760 * the default is {@link #SIZE_MEDIUM}. All other notifications size automatically based
10761 * on their content.
10762 *
10763 * @deprecated Display intents are no longer supported.
10764 */
10765 @Deprecated
10766 public static final int SIZE_DEFAULT = 0;
10767
10768 /**
10769 * Size value for use with {@link #setCustomSizePreset} to show this notification
10770 * with an extra small size.
10771 * <p>This value is only applicable for custom display notifications created using
10772 * {@link #setDisplayIntent}.
10773 *
10774 * @deprecated Display intents are no longer supported.
10775 */
10776 @Deprecated
10777 public static final int SIZE_XSMALL = 1;
10778
10779 /**
10780 * Size value for use with {@link #setCustomSizePreset} to show this notification
10781 * with a small size.
10782 * <p>This value is only applicable for custom display notifications created using
10783 * {@link #setDisplayIntent}.
10784 *
10785 * @deprecated Display intents are no longer supported.
10786 */
10787 @Deprecated
10788 public static final int SIZE_SMALL = 2;
10789
10790 /**
10791 * Size value for use with {@link #setCustomSizePreset} to show this notification
10792 * with a medium size.
10793 * <p>This value is only applicable for custom display notifications created using
10794 * {@link #setDisplayIntent}.
10795 *
10796 * @deprecated Display intents are no longer supported.
10797 */
10798 @Deprecated
10799 public static final int SIZE_MEDIUM = 3;
10800
10801 /**
10802 * Size value for use with {@link #setCustomSizePreset} to show this notification
10803 * with a large size.
10804 * <p>This value is only applicable for custom display notifications created using
10805 * {@link #setDisplayIntent}.
10806 *
10807 * @deprecated Display intents are no longer supported.
10808 */
10809 @Deprecated
10810 public static final int SIZE_LARGE = 4;
10811
10812 /**
10813 * Size value for use with {@link #setCustomSizePreset} to show this notification
10814 * full screen.
10815 * <p>This value is only applicable for custom display notifications created using
10816 * {@link #setDisplayIntent}.
10817 *
10818 * @deprecated Display intents are no longer supported.
10819 */
10820 @Deprecated
10821 public static final int SIZE_FULL_SCREEN = 5;
10822
10823 /**
10824 * Sentinel value for use with {@link #setHintScreenTimeout} to keep the screen on for a
10825 * short amount of time when this notification is displayed on the screen. This
10826 * is the default value.
10827 *
10828 * @deprecated This feature is no longer supported.
10829 */
10830 @Deprecated
10831 public static final int SCREEN_TIMEOUT_SHORT = 0;
10832
10833 /**
10834 * Sentinel value for use with {@link #setHintScreenTimeout} to keep the screen on
10835 * for a longer amount of time when this notification is displayed on the screen.
10836 *
10837 * @deprecated This feature is no longer supported.
10838 */
10839 @Deprecated
10840 public static final int SCREEN_TIMEOUT_LONG = -1;
10841
10842 /** Notification extra which contains wearable extensions */
10843 private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS";
10844
10845 // Keys within EXTRA_WEARABLE_EXTENSIONS for wearable options.
10846 private static final String KEY_ACTIONS = "actions";
10847 private static final String KEY_FLAGS = "flags";
10848 static final String KEY_DISPLAY_INTENT = "displayIntent";
10849 private static final String KEY_PAGES = "pages";
10850 static final String KEY_BACKGROUND = "background";
10851 private static final String KEY_CONTENT_ICON = "contentIcon";
10852 private static final String KEY_CONTENT_ICON_GRAVITY = "contentIconGravity";
10853 private static final String KEY_CONTENT_ACTION_INDEX = "contentActionIndex";
10854 private static final String KEY_CUSTOM_SIZE_PRESET = "customSizePreset";
10855 private static final String KEY_CUSTOM_CONTENT_HEIGHT = "customContentHeight";
10856 private static final String KEY_GRAVITY = "gravity";
10857 private static final String KEY_HINT_SCREEN_TIMEOUT = "hintScreenTimeout";
10858 private static final String KEY_DISMISSAL_ID = "dismissalId";
10859 private static final String KEY_BRIDGE_TAG = "bridgeTag";
10860
10861 // Flags bitwise-ored to mFlags
10862 private static final int FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE = 0x1;
10863 private static final int FLAG_HINT_HIDE_ICON = 1 << 1;
10864 private static final int FLAG_HINT_SHOW_BACKGROUND_ONLY = 1 << 2;
10865 private static final int FLAG_START_SCROLL_BOTTOM = 1 << 3;
10866 private static final int FLAG_HINT_AVOID_BACKGROUND_CLIPPING = 1 << 4;
10867 private static final int FLAG_BIG_PICTURE_AMBIENT = 1 << 5;
10868 private static final int FLAG_HINT_CONTENT_INTENT_LAUNCHES_ACTIVITY = 1 << 6;
10869
10870 // Default value for flags integer
10871 private static final int DEFAULT_FLAGS = FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE;
10872
10873 private static final int DEFAULT_CONTENT_ICON_GRAVITY = Gravity.END;
10874 private static final int DEFAULT_GRAVITY = Gravity.BOTTOM;
10875
10876 private ArrayList<Action> mActions = new ArrayList<Action>();
10877 private int mFlags = DEFAULT_FLAGS;
10878 private PendingIntent mDisplayIntent;
10879 private ArrayList<Notification> mPages = new ArrayList<Notification>();
10880 private Bitmap mBackground;
10881 private int mContentIcon;
10882 private int mContentIconGravity = DEFAULT_CONTENT_ICON_GRAVITY;
10883 private int mContentActionIndex = UNSET_ACTION_INDEX;
10884 private int mCustomSizePreset = SIZE_DEFAULT;
10885 private int mCustomContentHeight;
10886 private int mGravity = DEFAULT_GRAVITY;
10887 private int mHintScreenTimeout;
10888 private String mDismissalId;
10889 private String mBridgeTag;
10890
10891 /**
10892 * Create a {@link android.app.Notification.WearableExtender} with default
10893 * options.
10894 */
10895 public WearableExtender() {
10896 }
10897
10898 public WearableExtender(Notification notif) {
10899 Bundle wearableBundle = notif.extras.getBundle(EXTRA_WEARABLE_EXTENSIONS);
10900 if (wearableBundle != null) {
10901 List<Action> actions = wearableBundle.getParcelableArrayList(KEY_ACTIONS);
10902 if (actions != null) {
10903 mActions.addAll(actions);
10904 }
10905
10906 mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS);
10907 mDisplayIntent = wearableBundle.getParcelable(
10908 KEY_DISPLAY_INTENT, PendingIntent.class);
10909
10910 Notification[] pages = getParcelableArrayFromBundle(
10911 wearableBundle, KEY_PAGES, Notification.class);
10912 if (pages != null) {
10913 Collections.addAll(mPages, pages);
10914 }
10915
10916 mBackground = wearableBundle.getParcelable(KEY_BACKGROUND, Bitmap.class);
10917 mContentIcon = wearableBundle.getInt(KEY_CONTENT_ICON);
10918 mContentIconGravity = wearableBundle.getInt(KEY_CONTENT_ICON_GRAVITY,
10919 DEFAULT_CONTENT_ICON_GRAVITY);
10920 mContentActionIndex = wearableBundle.getInt(KEY_CONTENT_ACTION_INDEX,
10921 UNSET_ACTION_INDEX);
10922 mCustomSizePreset = wearableBundle.getInt(KEY_CUSTOM_SIZE_PRESET,
10923 SIZE_DEFAULT);
10924 mCustomContentHeight = wearableBundle.getInt(KEY_CUSTOM_CONTENT_HEIGHT);
10925 mGravity = wearableBundle.getInt(KEY_GRAVITY, DEFAULT_GRAVITY);
10926 mHintScreenTimeout = wearableBundle.getInt(KEY_HINT_SCREEN_TIMEOUT);
10927 mDismissalId = wearableBundle.getString(KEY_DISMISSAL_ID);
10928 mBridgeTag = wearableBundle.getString(KEY_BRIDGE_TAG);
10929 }
10930 }
10931
10932 /**
10933 * Apply wearable extensions to a notification that is being built. This is typically
10934 * called by the {@link android.app.Notification.Builder#extend} method of
10935 * {@link android.app.Notification.Builder}.
10936 */
10937 @Override
10938 public Notification.Builder extend(Notification.Builder builder) {
10939 Bundle wearableBundle = new Bundle();
10940
10941 if (!mActions.isEmpty()) {
10942 wearableBundle.putParcelableArrayList(KEY_ACTIONS, mActions);
10943 }
10944 if (mFlags != DEFAULT_FLAGS) {
10945 wearableBundle.putInt(KEY_FLAGS, mFlags);
10946 }
10947 if (mDisplayIntent != null) {
10948 wearableBundle.putParcelable(KEY_DISPLAY_INTENT, mDisplayIntent);
10949 }
10950 if (!mPages.isEmpty()) {
10951 wearableBundle.putParcelableArray(KEY_PAGES, mPages.toArray(
10952 new Notification[mPages.size()]));
10953 }
10954 if (mBackground != null) {
10955 wearableBundle.putParcelable(KEY_BACKGROUND, mBackground);
10956 }
10957 if (mContentIcon != 0) {
10958 wearableBundle.putInt(KEY_CONTENT_ICON, mContentIcon);
10959 }
10960 if (mContentIconGravity != DEFAULT_CONTENT_ICON_GRAVITY) {
10961 wearableBundle.putInt(KEY_CONTENT_ICON_GRAVITY, mContentIconGravity);
10962 }
10963 if (mContentActionIndex != UNSET_ACTION_INDEX) {
10964 wearableBundle.putInt(KEY_CONTENT_ACTION_INDEX,
10965 mContentActionIndex);
10966 }
10967 if (mCustomSizePreset != SIZE_DEFAULT) {
10968 wearableBundle.putInt(KEY_CUSTOM_SIZE_PRESET, mCustomSizePreset);
10969 }
10970 if (mCustomContentHeight != 0) {
10971 wearableBundle.putInt(KEY_CUSTOM_CONTENT_HEIGHT, mCustomContentHeight);
10972 }
10973 if (mGravity != DEFAULT_GRAVITY) {
10974 wearableBundle.putInt(KEY_GRAVITY, mGravity);
10975 }
10976 if (mHintScreenTimeout != 0) {
10977 wearableBundle.putInt(KEY_HINT_SCREEN_TIMEOUT, mHintScreenTimeout);
10978 }
10979 if (mDismissalId != null) {
10980 wearableBundle.putString(KEY_DISMISSAL_ID, mDismissalId);
10981 }
10982 if (mBridgeTag != null) {
10983 wearableBundle.putString(KEY_BRIDGE_TAG, mBridgeTag);
10984 }
10985
10986 builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle);
10987 return builder;
10988 }
10989
10990 @Override
10991 public WearableExtender clone() {
10992 WearableExtender that = new WearableExtender();
10993 that.mActions = new ArrayList<Action>(this.mActions);
10994 that.mFlags = this.mFlags;
10995 that.mDisplayIntent = this.mDisplayIntent;
10996 that.mPages = new ArrayList<Notification>(this.mPages);
10997 that.mBackground = this.mBackground;
10998 that.mContentIcon = this.mContentIcon;
10999 that.mContentIconGravity = this.mContentIconGravity;
11000 that.mContentActionIndex = this.mContentActionIndex;
11001 that.mCustomSizePreset = this.mCustomSizePreset;
11002 that.mCustomContentHeight = this.mCustomContentHeight;
11003 that.mGravity = this.mGravity;
11004 that.mHintScreenTimeout = this.mHintScreenTimeout;
11005 that.mDismissalId = this.mDismissalId;
11006 that.mBridgeTag = this.mBridgeTag;
11007 return that;
11008 }
11009
11010 /**
11011 * Add a wearable action to this notification.
11012 *
11013 * <p>When wearable actions are added using this method, the set of actions that
11014 * show on a wearable device splits from devices that only show actions added
11015 * using {@link android.app.Notification.Builder#addAction}. This allows for customization
11016 * of which actions display on different devices.
11017 *
11018 * @param action the action to add to this notification
11019 * @return this object for method chaining
11020 * @see android.app.Notification.Action
11021 */
11022 public WearableExtender addAction(Action action) {
11023 mActions.add(action);
11024 return this;
11025 }
11026
11027 /**
11028 * Adds wearable actions to this notification.
11029 *
11030 * <p>When wearable actions are added using this method, the set of actions that
11031 * show on a wearable device splits from devices that only show actions added
11032 * using {@link android.app.Notification.Builder#addAction}. This allows for customization
11033 * of which actions display on different devices.
11034 *
11035 * @param actions the actions to add to this notification
11036 * @return this object for method chaining
11037 * @see android.app.Notification.Action
11038 */
11039 public WearableExtender addActions(List<Action> actions) {
11040 mActions.addAll(actions);
11041 return this;
11042 }
11043
11044 /**
11045 * Clear all wearable actions present on this builder.
11046 * @return this object for method chaining.
11047 * @see #addAction
11048 */
11049 public WearableExtender clearActions() {
11050 mActions.clear();
11051 return this;
11052 }
11053
11054 /**
11055 * Get the wearable actions present on this notification.
11056 */
11057 public List<Action> getActions() {
11058 return mActions;
11059 }
11060
11061 /**
11062 * Set an intent to launch inside of an activity view when displaying
11063 * this notification. The {@link PendingIntent} provided should be for an activity.
11064 *
11065 * <pre class="prettyprint">
11066 * Intent displayIntent = new Intent(context, MyDisplayActivity.class);
11067 * PendingIntent displayPendingIntent = PendingIntent.getActivity(context,
11068 * 0, displayIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE_UNAUDITED);
11069 * Notification notif = new Notification.Builder(context)
11070 * .extend(new Notification.WearableExtender()
11071 * .setDisplayIntent(displayPendingIntent)
11072 * .setCustomSizePreset(Notification.WearableExtender.SIZE_MEDIUM))
11073 * .build();</pre>
11074 *
11075 * <p>The activity to launch needs to allow embedding, must be exported, and
11076 * should have an empty task affinity. It is also recommended to use the device
11077 * default light theme.
11078 *
11079 * <p>Example AndroidManifest.xml entry:
11080 * <pre class="prettyprint">
11081 * &lt;activity android:name=&quot;com.example.MyDisplayActivity&quot;
11082 * android:exported=&quot;true&quot;
11083 * android:allowEmbedded=&quot;true&quot;
11084 * android:taskAffinity=&quot;&quot;
11085 * android:theme=&quot;@android:style/Theme.DeviceDefault.Light&quot; /&gt;</pre>
11086 *
11087 * @param intent the {@link PendingIntent} for an activity
11088 * @return this object for method chaining
11089 * @see android.app.Notification.WearableExtender#getDisplayIntent
11090 * @deprecated Display intents are no longer supported.
11091 */
11092 @Deprecated
11093 public WearableExtender setDisplayIntent(PendingIntent intent) {
11094 mDisplayIntent = intent;
11095 return this;
11096 }
11097
11098 /**
11099 * Get the intent to launch inside of an activity view when displaying this
11100 * notification. This {@code PendingIntent} should be for an activity.
11101 *
11102 * @deprecated Display intents are no longer supported.
11103 */
11104 @Deprecated
11105 public PendingIntent getDisplayIntent() {
11106 return mDisplayIntent;
11107 }
11108
11109 /**
11110 * Add an additional page of content to display with this notification. The current
11111 * notification forms the first page, and pages added using this function form
11112 * subsequent pages. This field can be used to separate a notification into multiple
11113 * sections.
11114 *
11115 * @param page the notification to add as another page
11116 * @return this object for method chaining
11117 * @see android.app.Notification.WearableExtender#getPages
11118 * @deprecated Multiple content pages are no longer supported.
11119 */
11120 @Deprecated
11121 public WearableExtender addPage(Notification page) {
11122 mPages.add(page);
11123 return this;
11124 }
11125
11126 /**
11127 * Add additional pages of content to display with this notification. The current
11128 * notification forms the first page, and pages added using this function form
11129 * subsequent pages. This field can be used to separate a notification into multiple
11130 * sections.
11131 *
11132 * @param pages a list of notifications
11133 * @return this object for method chaining
11134 * @see android.app.Notification.WearableExtender#getPages
11135 * @deprecated Multiple content pages are no longer supported.
11136 */
11137 @Deprecated
11138 public WearableExtender addPages(List<Notification> pages) {
11139 mPages.addAll(pages);
11140 return this;
11141 }
11142
11143 /**
11144 * Clear all additional pages present on this builder.
11145 * @return this object for method chaining.
11146 * @see #addPage
11147 * @deprecated Multiple content pages are no longer supported.
11148 */
11149 @Deprecated
11150 public WearableExtender clearPages() {
11151 mPages.clear();
11152 return this;
11153 }
11154
11155 /**
11156 * Get the array of additional pages of content for displaying this notification. The
11157 * current notification forms the first page, and elements within this array form
11158 * subsequent pages. This field can be used to separate a notification into multiple
11159 * sections.
11160 * @return the pages for this notification
11161 * @deprecated Multiple content pages are no longer supported.
11162 */
11163 @Deprecated
11164 public List<Notification> getPages() {
11165 return mPages;
11166 }
11167
11168 /**
11169 * Set a background image to be displayed behind the notification content.
11170 * Contrary to the {@link android.app.Notification.BigPictureStyle}, this background
11171 * will work with any notification style.
11172 *
11173 * @param background the background bitmap
11174 * @return this object for method chaining
11175 * @see android.app.Notification.WearableExtender#getBackground
11176 * @deprecated Background images are no longer supported.
11177 */
11178 @Deprecated
11179 public WearableExtender setBackground(Bitmap background) {
11180 mBackground = background;
11181 return this;
11182 }
11183
11184 /**
11185 * Get a background image to be displayed behind the notification content.
11186 * Contrary to the {@link android.app.Notification.BigPictureStyle}, this background
11187 * will work with any notification style.
11188 *
11189 * @return the background image
11190 * @see android.app.Notification.WearableExtender#setBackground
11191 * @deprecated Background images are no longer supported.
11192 */
11193 @Deprecated
11194 public Bitmap getBackground() {
11195 return mBackground;
11196 }
11197
11198 /**
11199 * Set an icon that goes with the content of this notification.
11200 */
11201 @Deprecated
11202 public WearableExtender setContentIcon(int icon) {
11203 mContentIcon = icon;
11204 return this;
11205 }
11206
11207 /**
11208 * Get an icon that goes with the content of this notification.
11209 */
11210 @Deprecated
11211 public int getContentIcon() {
11212 return mContentIcon;
11213 }
11214
11215 /**
11216 * Set the gravity that the content icon should have within the notification display.
11217 * Supported values include {@link android.view.Gravity#START} and
11218 * {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}.
11219 * @see #setContentIcon
11220 */
11221 @Deprecated
11222 public WearableExtender setContentIconGravity(int contentIconGravity) {
11223 mContentIconGravity = contentIconGravity;
11224 return this;
11225 }
11226
11227 /**
11228 * Get the gravity that the content icon should have within the notification display.
11229 * Supported values include {@link android.view.Gravity#START} and
11230 * {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}.
11231 * @see #getContentIcon
11232 */
11233 @Deprecated
11234 public int getContentIconGravity() {
11235 return mContentIconGravity;
11236 }
11237
11238 /**
11239 * Set an action from this notification's actions as the primary action. If the action has a
11240 * {@link RemoteInput} associated with it, shortcuts to the options for that input are shown
11241 * directly on the notification.
11242 *
11243 * @param actionIndex The index of the primary action.
11244 * If wearable actions were added to the main notification, this index
11245 * will apply to that list, otherwise it will apply to the regular
11246 * actions list.
11247 */
11248 public WearableExtender setContentAction(int actionIndex) {
11249 mContentActionIndex = actionIndex;
11250 return this;
11251 }
11252
11253 /**
11254 * Get the index of the notification action, if any, that was specified as the primary
11255 * action.
11256 *
11257 * <p>If wearable specific actions were added to the main notification, this index will
11258 * apply to that list, otherwise it will apply to the regular actions list.
11259 *
11260 * @return the action index or {@link #UNSET_ACTION_INDEX} if no action was selected.
11261 */
11262 public int getContentAction() {
11263 return mContentActionIndex;
11264 }
11265
11266 /**
11267 * Set the gravity that this notification should have within the available viewport space.
11268 * Supported values include {@link android.view.Gravity#TOP},
11269 * {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}.
11270 * The default value is {@link android.view.Gravity#BOTTOM}.
11271 */
11272 @Deprecated
11273 public WearableExtender setGravity(int gravity) {
11274 mGravity = gravity;
11275 return this;
11276 }
11277
11278 /**
11279 * Get the gravity that this notification should have within the available viewport space.
11280 * Supported values include {@link android.view.Gravity#TOP},
11281 * {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}.
11282 * The default value is {@link android.view.Gravity#BOTTOM}.
11283 */
11284 @Deprecated
11285 public int getGravity() {
11286 return mGravity;
11287 }
11288
11289 /**
11290 * Set the custom size preset for the display of this notification out of the available
11291 * presets found in {@link android.app.Notification.WearableExtender}, e.g.
11292 * {@link #SIZE_LARGE}.
11293 * <p>Some custom size presets are only applicable for custom display notifications created
11294 * using {@link android.app.Notification.WearableExtender#setDisplayIntent}. Check the
11295 * documentation for the preset in question. See also
11296 * {@link #setCustomContentHeight} and {@link #getCustomSizePreset}.
11297 */
11298 @Deprecated
11299 public WearableExtender setCustomSizePreset(int sizePreset) {
11300 mCustomSizePreset = sizePreset;
11301 return this;
11302 }
11303
11304 /**
11305 * Get the custom size preset for the display of this notification out of the available
11306 * presets found in {@link android.app.Notification.WearableExtender}, e.g.
11307 * {@link #SIZE_LARGE}.
11308 * <p>Some custom size presets are only applicable for custom display notifications created
11309 * using {@link #setDisplayIntent}. Check the documentation for the preset in question.
11310 * See also {@link #setCustomContentHeight} and {@link #setCustomSizePreset}.
11311 */
11312 @Deprecated
11313 public int getCustomSizePreset() {
11314 return mCustomSizePreset;
11315 }
11316
11317 /**
11318 * Set the custom height in pixels for the display of this notification's content.
11319 * <p>This option is only available for custom display notifications created
11320 * using {@link android.app.Notification.WearableExtender#setDisplayIntent}. See also
11321 * {@link android.app.Notification.WearableExtender#setCustomSizePreset} and
11322 * {@link #getCustomContentHeight}.
11323 */
11324 @Deprecated
11325 public WearableExtender setCustomContentHeight(int height) {
11326 mCustomContentHeight = height;
11327 return this;
11328 }
11329
11330 /**
11331 * Get the custom height in pixels for the display of this notification's content.
11332 * <p>This option is only available for custom display notifications created
11333 * using {@link #setDisplayIntent}. See also {@link #setCustomSizePreset} and
11334 * {@link #setCustomContentHeight}.
11335 */
11336 @Deprecated
11337 public int getCustomContentHeight() {
11338 return mCustomContentHeight;
11339 }
11340
11341 /**
11342 * Set whether the scrolling position for the contents of this notification should start
11343 * at the bottom of the contents instead of the top when the contents are too long to
11344 * display within the screen. Default is false (start scroll at the top).
11345 */
11346 public WearableExtender setStartScrollBottom(boolean startScrollBottom) {
11347 setFlag(FLAG_START_SCROLL_BOTTOM, startScrollBottom);
11348 return this;
11349 }
11350
11351 /**
11352 * Get whether the scrolling position for the contents of this notification should start
11353 * at the bottom of the contents instead of the top when the contents are too long to
11354 * display within the screen. Default is false (start scroll at the top).
11355 */
11356 public boolean getStartScrollBottom() {
11357 return (mFlags & FLAG_START_SCROLL_BOTTOM) != 0;
11358 }
11359
11360 /**
11361 * Set whether the content intent is available when the wearable device is not connected
11362 * to a companion device. The user can still trigger this intent when the wearable device
11363 * is offline, but a visual hint will indicate that the content intent may not be available.
11364 * Defaults to true.
11365 */
11366 public WearableExtender setContentIntentAvailableOffline(
11367 boolean contentIntentAvailableOffline) {
11368 setFlag(FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE, contentIntentAvailableOffline);
11369 return this;
11370 }
11371
11372 /**
11373 * Get whether the content intent is available when the wearable device is not connected
11374 * to a companion device. The user can still trigger this intent when the wearable device
11375 * is offline, but a visual hint will indicate that the content intent may not be available.
11376 * Defaults to true.
11377 */
11378 public boolean getContentIntentAvailableOffline() {
11379 return (mFlags & FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE) != 0;
11380 }
11381
11382 /**
11383 * Set a hint that this notification's icon should not be displayed.
11384 * @param hintHideIcon {@code true} to hide the icon, {@code false} otherwise.
11385 * @return this object for method chaining
11386 */
11387 @Deprecated
11388 public WearableExtender setHintHideIcon(boolean hintHideIcon) {
11389 setFlag(FLAG_HINT_HIDE_ICON, hintHideIcon);
11390 return this;
11391 }
11392
11393 /**
11394 * Get a hint that this notification's icon should not be displayed.
11395 * @return {@code true} if this icon should not be displayed, false otherwise.
11396 * The default value is {@code false} if this was never set.
11397 */
11398 @Deprecated
11399 public boolean getHintHideIcon() {
11400 return (mFlags & FLAG_HINT_HIDE_ICON) != 0;
11401 }
11402
11403 /**
11404 * Set a visual hint that only the background image of this notification should be
11405 * displayed, and other semantic content should be hidden. This hint is only applicable
11406 * to sub-pages added using {@link #addPage}.
11407 */
11408 @Deprecated
11409 public WearableExtender setHintShowBackgroundOnly(boolean hintShowBackgroundOnly) {
11410 setFlag(FLAG_HINT_SHOW_BACKGROUND_ONLY, hintShowBackgroundOnly);
11411 return this;
11412 }
11413
11414 /**
11415 * Get a visual hint that only the background image of this notification should be
11416 * displayed, and other semantic content should be hidden. This hint is only applicable
11417 * to sub-pages added using {@link android.app.Notification.WearableExtender#addPage}.
11418 */
11419 @Deprecated
11420 public boolean getHintShowBackgroundOnly() {
11421 return (mFlags & FLAG_HINT_SHOW_BACKGROUND_ONLY) != 0;
11422 }
11423
11424 /**
11425 * Set a hint that this notification's background should not be clipped if possible,
11426 * and should instead be resized to fully display on the screen, retaining the aspect
11427 * ratio of the image. This can be useful for images like barcodes or qr codes.
11428 * @param hintAvoidBackgroundClipping {@code true} to avoid clipping if possible.
11429 * @return this object for method chaining
11430 */
11431 @Deprecated
11432 public WearableExtender setHintAvoidBackgroundClipping(
11433 boolean hintAvoidBackgroundClipping) {
11434 setFlag(FLAG_HINT_AVOID_BACKGROUND_CLIPPING, hintAvoidBackgroundClipping);
11435 return this;
11436 }
11437
11438 /**
11439 * Get a hint that this notification's background should not be clipped if possible,
11440 * and should instead be resized to fully display on the screen, retaining the aspect
11441 * ratio of the image. This can be useful for images like barcodes or qr codes.
11442 * @return {@code true} if it's ok if the background is clipped on the screen, false
11443 * otherwise. The default value is {@code false} if this was never set.
11444 */
11445 @Deprecated
11446 public boolean getHintAvoidBackgroundClipping() {
11447 return (mFlags & FLAG_HINT_AVOID_BACKGROUND_CLIPPING) != 0;
11448 }
11449
11450 /**
11451 * Set a hint that the screen should remain on for at least this duration when
11452 * this notification is displayed on the screen.
11453 * @param timeout The requested screen timeout in milliseconds. Can also be either
11454 * {@link #SCREEN_TIMEOUT_SHORT} or {@link #SCREEN_TIMEOUT_LONG}.
11455 * @return this object for method chaining
11456 */
11457 @Deprecated
11458 public WearableExtender setHintScreenTimeout(int timeout) {
11459 mHintScreenTimeout = timeout;
11460 return this;
11461 }
11462
11463 /**
11464 * Get the duration, in milliseconds, that the screen should remain on for
11465 * when this notification is displayed.
11466 * @return the duration in milliseconds if > 0, or either one of the sentinel values
11467 * {@link #SCREEN_TIMEOUT_SHORT} or {@link #SCREEN_TIMEOUT_LONG}.
11468 */
11469 @Deprecated
11470 public int getHintScreenTimeout() {
11471 return mHintScreenTimeout;
11472 }
11473
11474 /**
11475 * Set a hint that this notification's {@link BigPictureStyle} (if present) should be
11476 * converted to low-bit and displayed in ambient mode, especially useful for barcodes and
11477 * qr codes, as well as other simple black-and-white tickets.
11478 * @param hintAmbientBigPicture {@code true} to enable converstion and ambient.
11479 * @return this object for method chaining
11480 * @deprecated This feature is no longer supported.
11481 */
11482 @Deprecated
11483 public WearableExtender setHintAmbientBigPicture(boolean hintAmbientBigPicture) {
11484 setFlag(FLAG_BIG_PICTURE_AMBIENT, hintAmbientBigPicture);
11485 return this;
11486 }
11487
11488 /**
11489 * Get a hint that this notification's {@link BigPictureStyle} (if present) should be
11490 * converted to low-bit and displayed in ambient mode, especially useful for barcodes and
11491 * qr codes, as well as other simple black-and-white tickets.
11492 * @return {@code true} if it should be displayed in ambient, false otherwise
11493 * otherwise. The default value is {@code false} if this was never set.
11494 * @deprecated This feature is no longer supported.
11495 */
11496 @Deprecated
11497 public boolean getHintAmbientBigPicture() {
11498 return (mFlags & FLAG_BIG_PICTURE_AMBIENT) != 0;
11499 }
11500
11501 /**
11502 * Set a hint that this notification's content intent will launch an {@link Activity}
11503 * directly, telling the platform that it can generate the appropriate transitions.
11504 * @param hintContentIntentLaunchesActivity {@code true} if the content intent will launch
11505 * an activity and transitions should be generated, false otherwise.
11506 * @return this object for method chaining
11507 */
11508 public WearableExtender setHintContentIntentLaunchesActivity(
11509 boolean hintContentIntentLaunchesActivity) {
11510 setFlag(FLAG_HINT_CONTENT_INTENT_LAUNCHES_ACTIVITY, hintContentIntentLaunchesActivity);
11511 return this;
11512 }
11513
11514 /**
11515 * Get a hint that this notification's content intent will launch an {@link Activity}
11516 * directly, telling the platform that it can generate the appropriate transitions
11517 * @return {@code true} if the content intent will launch an activity and transitions should
11518 * be generated, false otherwise. The default value is {@code false} if this was never set.
11519 */
11520 public boolean getHintContentIntentLaunchesActivity() {
11521 return (mFlags & FLAG_HINT_CONTENT_INTENT_LAUNCHES_ACTIVITY) != 0;
11522 }
11523
11524 /**
11525 * Sets the dismissal id for this notification. If a notification is posted with a
11526 * dismissal id, then when that notification is canceled, notifications on other wearables
11527 * and the paired Android phone having that same dismissal id will also be canceled. See
11528 * <a href="{@docRoot}wear/notifications/index.html">Adding Wearable Features to
11529 * Notifications</a> for more information.
11530 * @param dismissalId the dismissal id of the notification.
11531 * @return this object for method chaining
11532 */
11533 public WearableExtender setDismissalId(String dismissalId) {
11534 mDismissalId = dismissalId;
11535 return this;
11536 }
11537
11538 /**
11539 * Returns the dismissal id of the notification.
11540 * @return the dismissal id of the notification or null if it has not been set.
11541 */
11542 public String getDismissalId() {
11543 return mDismissalId;
11544 }
11545
11546 /**
11547 * Sets a bridge tag for this notification. A bridge tag can be set for notifications
11548 * posted from a phone to provide finer-grained control on what notifications are bridged
11549 * to wearables. See <a href="{@docRoot}wear/notifications/index.html">Adding Wearable
11550 * Features to Notifications</a> for more information.
11551 * @param bridgeTag the bridge tag of the notification.
11552 * @return this object for method chaining
11553 */
11554 public WearableExtender setBridgeTag(String bridgeTag) {
11555 mBridgeTag = bridgeTag;
11556 return this;
11557 }
11558
11559 /**
11560 * Returns the bridge tag of the notification.
11561 * @return the bridge tag or null if not present.
11562 */
11563 public String getBridgeTag() {
11564 return mBridgeTag;
11565 }
11566
11567 private void setFlag(int mask, boolean value) {
11568 if (value) {
11569 mFlags |= mask;
11570 } else {
11571 mFlags &= ~mask;
11572 }
11573 }
11574 }
11575
11576 /**
11577 * <p>Helper class to add Android Auto extensions to notifications. To create a notification
11578 * with car extensions:
11579 *
11580 * <ol>
11581 * <li>Create an {@link Notification.Builder}, setting any desired
11582 * properties.
11583 * <li>Create a {@link CarExtender}.
11584 * <li>Set car-specific properties using the {@code add} and {@code set} methods of
11585 * {@link CarExtender}.
11586 * <li>Call {@link Notification.Builder#extend(Notification.Extender)}
11587 * to apply the extensions to a notification.
11588 * </ol>
11589 *
11590 * <pre class="prettyprint">
11591 * Notification notification = new Notification.Builder(context)
11592 * ...
11593 * .extend(new CarExtender()
11594 * .set*(...))
11595 * .build();
11596 * </pre>
11597 *
11598 * <p>Car extensions can be accessed on an existing notification by using the
11599 * {@code CarExtender(Notification)} constructor, and then using the {@code get} methods
11600 * to access values.
11601 */
11602 public static final class CarExtender implements Extender {
11603 private static final String TAG = "CarExtender";
11604
11605 private static final String EXTRA_CAR_EXTENDER = "android.car.EXTENSIONS";
11606 private static final String EXTRA_LARGE_ICON = "large_icon";
11607 private static final String EXTRA_CONVERSATION = "car_conversation";
11608 private static final String EXTRA_COLOR = "app_color";
11609
11610 private Bitmap mLargeIcon;
11611 private UnreadConversation mUnreadConversation;
11612 private int mColor = Notification.COLOR_DEFAULT;
11613
11614 /**
11615 * Create a {@link CarExtender} with default options.
11616 */
11617 public CarExtender() {
11618 }
11619
11620 /**
11621 * Create a {@link CarExtender} from the CarExtender options of an existing Notification.
11622 *
11623 * @param notif The notification from which to copy options.
11624 */
11625 public CarExtender(Notification notif) {
11626 Bundle carBundle = notif.extras == null ?
11627 null : notif.extras.getBundle(EXTRA_CAR_EXTENDER);
11628 if (carBundle != null) {
11629 mLargeIcon = carBundle.getParcelable(EXTRA_LARGE_ICON, Bitmap.class);
11630 mColor = carBundle.getInt(EXTRA_COLOR, Notification.COLOR_DEFAULT);
11631
11632 Bundle b = carBundle.getBundle(EXTRA_CONVERSATION);
11633 mUnreadConversation = UnreadConversation.getUnreadConversationFromBundle(b);
11634 }
11635 }
11636
11637 /**
11638 * Apply car extensions to a notification that is being built. This is typically called by
11639 * the {@link Notification.Builder#extend(Notification.Extender)}
11640 * method of {@link Notification.Builder}.
11641 */
11642 @Override
11643 public Notification.Builder extend(Notification.Builder builder) {
11644 Bundle carExtensions = new Bundle();
11645
11646 if (mLargeIcon != null) {
11647 carExtensions.putParcelable(EXTRA_LARGE_ICON, mLargeIcon);
11648 }
11649 if (mColor != Notification.COLOR_DEFAULT) {
11650 carExtensions.putInt(EXTRA_COLOR, mColor);
11651 }
11652
11653 if (mUnreadConversation != null) {
11654 Bundle b = mUnreadConversation.getBundleForUnreadConversation();
11655 carExtensions.putBundle(EXTRA_CONVERSATION, b);
11656 }
11657
11658 builder.getExtras().putBundle(EXTRA_CAR_EXTENDER, carExtensions);
11659 return builder;
11660 }
11661
11662 /**
11663 * Sets the accent color to use when Android Auto presents the notification.
11664 *
11665 * Android Auto uses the color set with {@link Notification.Builder#setColor(int)}
11666 * to accent the displayed notification. However, not all colors are acceptable in an
11667 * automotive setting. This method can be used to override the color provided in the
11668 * notification in such a situation.
11669 */
11670 public CarExtender setColor(@ColorInt int color) {
11671 mColor = color;
11672 return this;
11673 }
11674
11675 /**
11676 * Gets the accent color.
11677 *
11678 * @see #setColor
11679 */
11680 @ColorInt
11681 public int getColor() {
11682 return mColor;
11683 }
11684
11685 /**
11686 * Sets the large icon of the car notification.
11687 *
11688 * If no large icon is set in the extender, Android Auto will display the icon
11689 * specified by {@link Notification.Builder#setLargeIcon(android.graphics.Bitmap)}
11690 *
11691 * @param largeIcon The large icon to use in the car notification.
11692 * @return This object for method chaining.
11693 */
11694 public CarExtender setLargeIcon(Bitmap largeIcon) {
11695 mLargeIcon = largeIcon;
11696 return this;
11697 }
11698
11699 /**
11700 * Gets the large icon used in this car notification, or null if no icon has been set.
11701 *
11702 * @return The large icon for the car notification.
11703 * @see CarExtender#setLargeIcon
11704 */
11705 public Bitmap getLargeIcon() {
11706 return mLargeIcon;
11707 }
11708
11709 /**
11710 * Sets the unread conversation in a message notification.
11711 *
11712 * @param unreadConversation The unread part of the conversation this notification conveys.
11713 * @return This object for method chaining.
11714 */
11715 public CarExtender setUnreadConversation(UnreadConversation unreadConversation) {
11716 mUnreadConversation = unreadConversation;
11717 return this;
11718 }
11719
11720 /**
11721 * Returns the unread conversation conveyed by this notification.
11722 * @see #setUnreadConversation(UnreadConversation)
11723 */
11724 public UnreadConversation getUnreadConversation() {
11725 return mUnreadConversation;
11726 }
11727
11728 /**
11729 * A class which holds the unread messages from a conversation.
11730 */
11731 public static class UnreadConversation {
11732 private static final String KEY_AUTHOR = "author";
11733 private static final String KEY_TEXT = "text";
11734 private static final String KEY_MESSAGES = "messages";
11735 static final String KEY_REMOTE_INPUT = "remote_input";
11736 static final String KEY_ON_REPLY = "on_reply";
11737 static final String KEY_ON_READ = "on_read";
11738 private static final String KEY_PARTICIPANTS = "participants";
11739 private static final String KEY_TIMESTAMP = "timestamp";
11740
11741 private final String[] mMessages;
11742 private final RemoteInput mRemoteInput;
11743 private final PendingIntent mReplyPendingIntent;
11744 private final PendingIntent mReadPendingIntent;
11745 private final String[] mParticipants;
11746 private final long mLatestTimestamp;
11747
11748 UnreadConversation(String[] messages, RemoteInput remoteInput,
11749 PendingIntent replyPendingIntent, PendingIntent readPendingIntent,
11750 String[] participants, long latestTimestamp) {
11751 mMessages = messages;
11752 mRemoteInput = remoteInput;
11753 mReadPendingIntent = readPendingIntent;
11754 mReplyPendingIntent = replyPendingIntent;
11755 mParticipants = participants;
11756 mLatestTimestamp = latestTimestamp;
11757 }
11758
11759 /**
11760 * Gets the list of messages conveyed by this notification.
11761 */
11762 public String[] getMessages() {
11763 return mMessages;
11764 }
11765
11766 /**
11767 * Gets the remote input that will be used to convey the response to a message list, or
11768 * null if no such remote input exists.
11769 */
11770 public RemoteInput getRemoteInput() {
11771 return mRemoteInput;
11772 }
11773
11774 /**
11775 * Gets the pending intent that will be triggered when the user replies to this
11776 * notification.
11777 */
11778 public PendingIntent getReplyPendingIntent() {
11779 return mReplyPendingIntent;
11780 }
11781
11782 /**
11783 * Gets the pending intent that Android Auto will send after it reads aloud all messages
11784 * in this object's message list.
11785 */
11786 public PendingIntent getReadPendingIntent() {
11787 return mReadPendingIntent;
11788 }
11789
11790 /**
11791 * Gets the participants in the conversation.
11792 */
11793 public String[] getParticipants() {
11794 return mParticipants;
11795 }
11796
11797 /**
11798 * Gets the firs participant in the conversation.
11799 */
11800 public String getParticipant() {
11801 return mParticipants.length > 0 ? mParticipants[0] : null;
11802 }
11803
11804 /**
11805 * Gets the timestamp of the conversation.
11806 */
11807 public long getLatestTimestamp() {
11808 return mLatestTimestamp;
11809 }
11810
11811 Bundle getBundleForUnreadConversation() {
11812 Bundle b = new Bundle();
11813 String author = null;
11814 if (mParticipants != null && mParticipants.length > 1) {
11815 author = mParticipants[0];
11816 }
11817 Parcelable[] messages = new Parcelable[mMessages.length];
11818 for (int i = 0; i < messages.length; i++) {
11819 Bundle m = new Bundle();
11820 m.putString(KEY_TEXT, mMessages[i]);
11821 m.putString(KEY_AUTHOR, author);
11822 messages[i] = m;
11823 }
11824 b.putParcelableArray(KEY_MESSAGES, messages);
11825 if (mRemoteInput != null) {
11826 b.putParcelable(KEY_REMOTE_INPUT, mRemoteInput);
11827 }
11828 b.putParcelable(KEY_ON_REPLY, mReplyPendingIntent);
11829 b.putParcelable(KEY_ON_READ, mReadPendingIntent);
11830 b.putStringArray(KEY_PARTICIPANTS, mParticipants);
11831 b.putLong(KEY_TIMESTAMP, mLatestTimestamp);
11832 return b;
11833 }
11834
11835 static UnreadConversation getUnreadConversationFromBundle(Bundle b) {
11836 if (b == null) {
11837 return null;
11838 }
11839 Parcelable[] parcelableMessages = b.getParcelableArray(KEY_MESSAGES);
11840 String[] messages = null;
11841 if (parcelableMessages != null) {
11842 String[] tmp = new String[parcelableMessages.length];
11843 boolean success = true;
11844 for (int i = 0; i < tmp.length; i++) {
11845 if (!(parcelableMessages[i] instanceof Bundle)) {
11846 success = false;
11847 break;
11848 }
11849 tmp[i] = ((Bundle) parcelableMessages[i]).getString(KEY_TEXT);
11850 if (tmp[i] == null) {
11851 success = false;
11852 break;
11853 }
11854 }
11855 if (success) {
11856 messages = tmp;
11857 } else {
11858 return null;
11859 }
11860 }
11861
11862 PendingIntent onRead = b.getParcelable(KEY_ON_READ, PendingIntent.class);
11863 PendingIntent onReply = b.getParcelable(KEY_ON_REPLY, PendingIntent.class);
11864
11865 RemoteInput remoteInput = b.getParcelable(KEY_REMOTE_INPUT, RemoteInput.class);
11866
11867 String[] participants = b.getStringArray(KEY_PARTICIPANTS);
11868 if (participants == null || participants.length != 1) {
11869 return null;
11870 }
11871
11872 return new UnreadConversation(messages,
11873 remoteInput,
11874 onReply,
11875 onRead,
11876 participants, b.getLong(KEY_TIMESTAMP));
11877 }
11878 };
11879
11880 /**
11881 * Builder class for {@link CarExtender.UnreadConversation} objects.
11882 */
11883 public static class Builder {
11884 private final List<String> mMessages = new ArrayList<String>();
11885 private final String mParticipant;
11886 private RemoteInput mRemoteInput;
11887 private PendingIntent mReadPendingIntent;
11888 private PendingIntent mReplyPendingIntent;
11889 private long mLatestTimestamp;
11890
11891 /**
11892 * Constructs a new builder for {@link CarExtender.UnreadConversation}.
11893 *
11894 * @param name The name of the other participant in the conversation.
11895 */
11896 public Builder(String name) {
11897 mParticipant = name;
11898 }
11899
11900 /**
11901 * Appends a new unread message to the list of messages for this conversation.
11902 *
11903 * The messages should be added from oldest to newest.
11904 *
11905 * @param message The text of the new unread message.
11906 * @return This object for method chaining.
11907 */
11908 public Builder addMessage(String message) {
11909 mMessages.add(message);
11910 return this;
11911 }
11912
11913 /**
11914 * Sets the pending intent and remote input which will convey the reply to this
11915 * notification.
11916 *
11917 * @param pendingIntent The pending intent which will be triggered on a reply.
11918 * @param remoteInput The remote input parcelable which will carry the reply.
11919 * @return This object for method chaining.
11920 *
11921 * @see CarExtender.UnreadConversation#getRemoteInput
11922 * @see CarExtender.UnreadConversation#getReplyPendingIntent
11923 */
11924 public Builder setReplyAction(
11925 PendingIntent pendingIntent, RemoteInput remoteInput) {
11926 mRemoteInput = remoteInput;
11927 mReplyPendingIntent = pendingIntent;
11928
11929 return this;
11930 }
11931
11932 /**
11933 * Sets the pending intent that will be sent once the messages in this notification
11934 * are read.
11935 *
11936 * @param pendingIntent The pending intent to use.
11937 * @return This object for method chaining.
11938 */
11939 public Builder setReadPendingIntent(PendingIntent pendingIntent) {
11940 mReadPendingIntent = pendingIntent;
11941 return this;
11942 }
11943
11944 /**
11945 * Sets the timestamp of the most recent message in an unread conversation.
11946 *
11947 * If a messaging notification has been posted by your application and has not
11948 * yet been cancelled, posting a later notification with the same id and tag
11949 * but without a newer timestamp may result in Android Auto not displaying a
11950 * heads up notification for the later notification.
11951 *
11952 * @param timestamp The timestamp of the most recent message in the conversation.
11953 * @return This object for method chaining.
11954 */
11955 public Builder setLatestTimestamp(long timestamp) {
11956 mLatestTimestamp = timestamp;
11957 return this;
11958 }
11959
11960 /**
11961 * Builds a new unread conversation object.
11962 *
11963 * @return The new unread conversation object.
11964 */
11965 public UnreadConversation build() {
11966 String[] messages = mMessages.toArray(new String[mMessages.size()]);
11967 String[] participants = { mParticipant };
11968 return new UnreadConversation(messages, mRemoteInput, mReplyPendingIntent,
11969 mReadPendingIntent, participants, mLatestTimestamp);
11970 }
11971 }
11972 }
11973
11974 /**
11975 * <p>Helper class to add Android TV extensions to notifications. To create a notification
11976 * with a TV extension:
11977 *
11978 * <ol>
11979 * <li>Create an {@link Notification.Builder}, setting any desired properties.
11980 * <li>Create a {@link TvExtender}.
11981 * <li>Set TV-specific properties using the {@code set} methods of
11982 * {@link TvExtender}.
11983 * <li>Call {@link Notification.Builder#extend(Notification.Extender)}
11984 * to apply the extension to a notification.
11985 * </ol>
11986 *
11987 * <pre class="prettyprint">
11988 * Notification notification = new Notification.Builder(context)
11989 * ...
11990 * .extend(new TvExtender()
11991 * .set*(...))
11992 * .build();
11993 * </pre>
11994 *
11995 * <p>TV extensions can be accessed on an existing notification by using the
11996 * {@code TvExtender(Notification)} constructor, and then using the {@code get} methods
11997 * to access values.
11998 *
11999 * @hide
12000 */
12001 @SystemApi
12002 public static final class TvExtender implements Extender {
12003 private static final String TAG = "TvExtender";
12004
12005 private static final String EXTRA_TV_EXTENDER = "android.tv.EXTENSIONS";
12006 private static final String EXTRA_FLAGS = "flags";
12007 static final String EXTRA_CONTENT_INTENT = "content_intent";
12008 static final String EXTRA_DELETE_INTENT = "delete_intent";
12009 private static final String EXTRA_CHANNEL_ID = "channel_id";
12010 private static final String EXTRA_SUPPRESS_SHOW_OVER_APPS = "suppressShowOverApps";
12011
12012 // Flags bitwise-ored to mFlags
12013 private static final int FLAG_AVAILABLE_ON_TV = 0x1;
12014
12015 private int mFlags;
12016 private String mChannelId;
12017 private PendingIntent mContentIntent;
12018 private PendingIntent mDeleteIntent;
12019 private boolean mSuppressShowOverApps;
12020
12021 /**
12022 * Create a {@link TvExtender} with default options.
12023 */
12024 public TvExtender() {
12025 mFlags = FLAG_AVAILABLE_ON_TV;
12026 }
12027
12028 /**
12029 * Create a {@link TvExtender} from the TvExtender options of an existing Notification.
12030 *
12031 * @param notif The notification from which to copy options.
12032 */
12033 public TvExtender(Notification notif) {
12034 Bundle bundle = notif.extras == null ?
12035 null : notif.extras.getBundle(EXTRA_TV_EXTENDER);
12036 if (bundle != null) {
12037 mFlags = bundle.getInt(EXTRA_FLAGS);
12038 mChannelId = bundle.getString(EXTRA_CHANNEL_ID);
12039 mSuppressShowOverApps = bundle.getBoolean(EXTRA_SUPPRESS_SHOW_OVER_APPS);
12040 mContentIntent = bundle.getParcelable(EXTRA_CONTENT_INTENT, PendingIntent.class);
12041 mDeleteIntent = bundle.getParcelable(EXTRA_DELETE_INTENT, PendingIntent.class);
12042 }
12043 }
12044
12045 /**
12046 * Apply a TV extension to a notification that is being built. This is typically called by
12047 * the {@link Notification.Builder#extend(Notification.Extender)}
12048 * method of {@link Notification.Builder}.
12049 */
12050 @Override
12051 public Notification.Builder extend(Notification.Builder builder) {
12052 Bundle bundle = new Bundle();
12053
12054 bundle.putInt(EXTRA_FLAGS, mFlags);
12055 bundle.putString(EXTRA_CHANNEL_ID, mChannelId);
12056 bundle.putBoolean(EXTRA_SUPPRESS_SHOW_OVER_APPS, mSuppressShowOverApps);
12057 if (mContentIntent != null) {
12058 bundle.putParcelable(EXTRA_CONTENT_INTENT, mContentIntent);
12059 }
12060
12061 if (mDeleteIntent != null) {
12062 bundle.putParcelable(EXTRA_DELETE_INTENT, mDeleteIntent);
12063 }
12064
12065 builder.getExtras().putBundle(EXTRA_TV_EXTENDER, bundle);
12066 return builder;
12067 }
12068
12069 /**
12070 * Returns true if this notification should be shown on TV. This method return true
12071 * if the notification was extended with a TvExtender.
12072 */
12073 public boolean isAvailableOnTv() {
12074 return (mFlags & FLAG_AVAILABLE_ON_TV) != 0;
12075 }
12076
12077 /**
12078 * Specifies the channel the notification should be delivered on when shown on TV.
12079 * It can be different from the channel that the notification is delivered to when
12080 * posting on a non-TV device.
12081 */
12082 public TvExtender setChannel(String channelId) {
12083 mChannelId = channelId;
12084 return this;
12085 }
12086
12087 /**
12088 * Specifies the channel the notification should be delivered on when shown on TV.
12089 * It can be different from the channel that the notification is delivered to when
12090 * posting on a non-TV device.
12091 */
12092 public TvExtender setChannelId(String channelId) {
12093 mChannelId = channelId;
12094 return this;
12095 }
12096
12097 /** @removed */
12098 @Deprecated
12099 public String getChannel() {
12100 return mChannelId;
12101 }
12102
12103 /**
12104 * Returns the id of the channel this notification posts to on TV.
12105 */
12106 public String getChannelId() {
12107 return mChannelId;
12108 }
12109
12110 /**
12111 * Supplies a {@link PendingIntent} to be sent when the notification is selected on TV.
12112 * If provided, it is used instead of the content intent specified
12113 * at the level of Notification.
12114 */
12115 public TvExtender setContentIntent(PendingIntent intent) {
12116 mContentIntent = intent;
12117 return this;
12118 }
12119
12120 /**
12121 * Returns the TV-specific content intent. If this method returns null, the
12122 * main content intent on the notification should be used.
12123 *
12124 * @see {@link Notification#contentIntent}
12125 */
12126 public PendingIntent getContentIntent() {
12127 return mContentIntent;
12128 }
12129
12130 /**
12131 * Supplies a {@link PendingIntent} to send when the notification is cleared explicitly
12132 * by the user on TV. If provided, it is used instead of the delete intent specified
12133 * at the level of Notification.
12134 */
12135 public TvExtender setDeleteIntent(PendingIntent intent) {
12136 mDeleteIntent = intent;
12137 return this;
12138 }
12139
12140 /**
12141 * Returns the TV-specific delete intent. If this method returns null, the
12142 * main delete intent on the notification should be used.
12143 *
12144 * @see {@link Notification#deleteIntent}
12145 */
12146 public PendingIntent getDeleteIntent() {
12147 return mDeleteIntent;
12148 }
12149
12150 /**
12151 * Specifies whether this notification should suppress showing a message over top of apps
12152 * outside of the launcher.
12153 */
12154 public TvExtender setSuppressShowOverApps(boolean suppress) {
12155 mSuppressShowOverApps = suppress;
12156 return this;
12157 }
12158
12159 /**
12160 * Returns true if this notification should not show messages over top of apps
12161 * outside of the launcher.
12162 */
12163 public boolean getSuppressShowOverApps() {
12164 return mSuppressShowOverApps;
12165 }
12166 }
12167
12168 /**
12169 * Get an array of Parcelable objects from a parcelable array bundle field.
12170 * Update the bundle to have a typed array so fetches in the future don't need
12171 * to do an array copy.
12172 */
12173 @Nullable
12174 private static <T extends Parcelable> T[] getParcelableArrayFromBundle(
12175 Bundle bundle, String key, Class<T> itemClass) {
12176 final Parcelable[] array = bundle.getParcelableArray(key);
12177 final Class<?> arrayClass = Array.newInstance(itemClass, 0).getClass();
12178 if (arrayClass.isInstance(array) || array == null) {
12179 return (T[]) array;
12180 }
12181 final T[] typedArray = (T[]) Array.newInstance(itemClass, array.length);
12182 for (int i = 0; i < array.length; i++) {
12183 typedArray[i] = (T) array[i];
12184 }
12185 bundle.putParcelableArray(key, typedArray);
12186 return typedArray;
12187 }
12188
12189 private static class BuilderRemoteViews extends RemoteViews {
12190 public BuilderRemoteViews(Parcel parcel) {
12191 super(parcel);
12192 }
12193
12194 public BuilderRemoteViews(ApplicationInfo appInfo, int layoutId) {
12195 super(appInfo, layoutId);
12196 }
12197
12198 @Override
12199 public BuilderRemoteViews clone() {
12200 Parcel p = Parcel.obtain();
12201 writeToParcel(p, 0);
12202 p.setDataPosition(0);
12203 BuilderRemoteViews brv = new BuilderRemoteViews(p);
12204 p.recycle();
12205 return brv;
12206 }
12207
12208 /**
12209 * Override and return true, since {@link RemoteViews#onLoadClass(Class)} is not overridden.
12210 *
12211 * @see RemoteViews#shouldUseStaticFilter()
12212 */
12213 @Override
12214 protected boolean shouldUseStaticFilter() {
12215 return true;
12216 }
12217 }
12218
12219 /**
12220 * A result object where information about the template that was created is saved.
12221 */
12222 private static class TemplateBindResult {
12223 boolean mRightIconVisible;
12224 float mRightIconWidthDp;
12225 float mRightIconHeightDp;
12226
12227 /**
12228 * The margin end that needs to be added to the heading so that it won't overlap
12229 * with the large icon. This value includes the space required to accommodate the large
12230 * icon, but should be added to the space needed to accommodate the expander. This does
12231 * not include the 16dp content margin that all notification views must have.
12232 */
12233 public final MarginSet mHeadingExtraMarginSet = new MarginSet();
12234
12235 /**
12236 * The margin end that needs to be added to the heading so that it won't overlap
12237 * with the large icon. This value includes the space required to accommodate the large
12238 * icon as well as the expander. This does not include the 16dp content margin that all
12239 * notification views must have.
12240 */
12241 public final MarginSet mHeadingFullMarginSet = new MarginSet();
12242
12243 /**
12244 * The margin end that needs to be added to the title text of the big state
12245 * so that it won't overlap with the large icon, but assuming the text can run under
12246 * the expander when that icon is not visible.
12247 */
12248 public final MarginSet mTitleMarginSet = new MarginSet();
12249
12250 public void setRightIconState(boolean visible, float widthDp, float heightDp,
12251 float marginEndDpIfVisible, float expanderSizeDp) {
12252 mRightIconVisible = visible;
12253 mRightIconWidthDp = widthDp;
12254 mRightIconHeightDp = heightDp;
12255 mHeadingExtraMarginSet.setValues(0, marginEndDpIfVisible);
12256 mHeadingFullMarginSet.setValues(expanderSizeDp, marginEndDpIfVisible + expanderSizeDp);
12257 mTitleMarginSet.setValues(0, marginEndDpIfVisible + expanderSizeDp);
12258 }
12259
12260 /**
12261 * This contains the end margins for a view when the right icon is visible or not. These
12262 * values are both needed so that NotificationGroupingUtil can 'move' the right_icon to the
12263 * left_icon and adjust the margins, and to undo that change as well.
12264 */
12265 private class MarginSet {
12266 private float mValueIfGone;
12267 private float mValueIfVisible;
12268
12269 public void setValues(float valueIfGone, float valueIfVisible) {
12270 mValueIfGone = valueIfGone;
12271 mValueIfVisible = valueIfVisible;
12272 }
12273
12274 public void applyToView(@NonNull RemoteViews views, @IdRes int viewId) {
12275 applyToView(views, viewId, 0);
12276 }
12277
12278 public void applyToView(@NonNull RemoteViews views, @IdRes int viewId,
12279 float extraMarginDp) {
12280 final float marginEndDp = getDpValue() + extraMarginDp;
12281 if (viewId == R.id.notification_header) {
12282 views.setFloat(R.id.notification_header,
12283 "setTopLineExtraMarginEndDp", marginEndDp);
12284 } else if (viewId == R.id.text || viewId == R.id.big_text) {
12285 if (mValueIfGone != 0) {
12286 throw new RuntimeException("Programming error: `text` and `big_text` use "
12287 + "ImageFloatingTextView which can either show a margin or not; "
12288 + "thus mValueIfGone must be 0, but it was " + mValueIfGone);
12289 }
12290 // Note that the caller must set "setNumIndentLines" to a positive int in order
12291 // for this margin to do anything at all.
12292 views.setFloat(viewId, "setImageEndMarginDp", mValueIfVisible);
12293 views.setBoolean(viewId, "setHasImage", mRightIconVisible);
12294 // Apply just the *extra* margin as the view layout margin; this will be
12295 // unchanged depending on the visibility of the image, but it means that the
12296 // extra margin applies to *every* line of text instead of just indented lines.
12297 views.setViewLayoutMargin(viewId, RemoteViews.MARGIN_END,
12298 extraMarginDp, TypedValue.COMPLEX_UNIT_DIP);
12299 } else {
12300 views.setViewLayoutMargin(viewId, RemoteViews.MARGIN_END,
12301 marginEndDp, TypedValue.COMPLEX_UNIT_DIP);
12302 }
12303 if (mRightIconVisible) {
12304 views.setIntTag(viewId, R.id.tag_margin_end_when_icon_visible,
12305 TypedValue.createComplexDimension(
12306 mValueIfVisible + extraMarginDp, TypedValue.COMPLEX_UNIT_DIP));
12307 views.setIntTag(viewId, R.id.tag_margin_end_when_icon_gone,
12308 TypedValue.createComplexDimension(
12309 mValueIfGone + extraMarginDp, TypedValue.COMPLEX_UNIT_DIP));
12310 }
12311 }
12312
12313 public float getDpValue() {
12314 return mRightIconVisible ? mValueIfVisible : mValueIfGone;
12315 }
12316 }
12317 }
12318
12319 private static class StandardTemplateParams {
12320 /**
12321 * Notifications will be minimally decorated with ONLY an icon and expander:
12322 * <li>A large icon is never shown.
12323 * <li>A progress bar is never shown.
12324 * <li>The expanded and heads up states do not show actions, even if provided.
12325 */
12326 public static final int DECORATION_MINIMAL = 1;
12327
12328 /**
12329 * Notifications will be partially decorated with AT LEAST an icon and expander:
12330 * <li>A large icon is shown if provided.
12331 * <li>A progress bar is shown if provided and enough space remains below the content.
12332 * <li>Actions are shown in the expanded and heads up states.
12333 */
12334 public static final int DECORATION_PARTIAL = 2;
12335
12336 public static int VIEW_TYPE_UNSPECIFIED = 0;
12337 public static int VIEW_TYPE_NORMAL = 1;
12338 public static int VIEW_TYPE_BIG = 2;
12339 public static int VIEW_TYPE_HEADS_UP = 3;
12340 public static int VIEW_TYPE_MINIMIZED = 4; // header only for minimized state
12341 public static int VIEW_TYPE_PUBLIC = 5; // header only for automatic public version
12342 public static int VIEW_TYPE_GROUP_HEADER = 6; // header only for top of group
12343
12344 int mViewType = VIEW_TYPE_UNSPECIFIED;
12345 boolean mHeaderless;
12346 boolean mHideAppName;
12347 boolean mHideTitle;
12348 boolean mHideSubText;
12349 boolean mHideTime;
12350 boolean mHideActions;
12351 boolean mHideProgress;
12352 boolean mHideSnoozeButton;
12353 boolean mHideLeftIcon;
12354 boolean mHideRightIcon;
12355 Icon mPromotedPicture;
12356 boolean mCallStyleActions;
12357 boolean mAllowTextWithProgress;
12358 int mTitleViewId;
12359 int mTextViewId;
12360 CharSequence title;
12361 CharSequence text;
12362 CharSequence headerTextSecondary;
12363 CharSequence summaryText;
12364 int maxRemoteInputHistory = Style.MAX_REMOTE_INPUT_HISTORY_LINES;
12365 boolean allowColorization = true;
12366 boolean mHighlightExpander = false;
12367
12368 final StandardTemplateParams reset() {
12369 mViewType = VIEW_TYPE_UNSPECIFIED;
12370 mHeaderless = false;
12371 mHideAppName = false;
12372 mHideTitle = false;
12373 mHideSubText = false;
12374 mHideTime = false;
12375 mHideActions = false;
12376 mHideProgress = false;
12377 mHideSnoozeButton = false;
12378 mHideLeftIcon = false;
12379 mHideRightIcon = false;
12380 mPromotedPicture = null;
12381 mCallStyleActions = false;
12382 mAllowTextWithProgress = false;
12383 mTitleViewId = R.id.title;
12384 mTextViewId = R.id.text;
12385 title = null;
12386 text = null;
12387 summaryText = null;
12388 headerTextSecondary = null;
12389 maxRemoteInputHistory = Style.MAX_REMOTE_INPUT_HISTORY_LINES;
12390 allowColorization = true;
12391 mHighlightExpander = false;
12392 return this;
12393 }
12394
12395 final boolean hasTitle() {
12396 return !TextUtils.isEmpty(title) && !mHideTitle;
12397 }
12398
12399 final StandardTemplateParams viewType(int viewType) {
12400 mViewType = viewType;
12401 return this;
12402 }
12403
12404 public StandardTemplateParams headerless(boolean headerless) {
12405 mHeaderless = headerless;
12406 return this;
12407 }
12408
12409 public StandardTemplateParams hideAppName(boolean hideAppName) {
12410 mHideAppName = hideAppName;
12411 return this;
12412 }
12413
12414 public StandardTemplateParams hideSubText(boolean hideSubText) {
12415 mHideSubText = hideSubText;
12416 return this;
12417 }
12418
12419 public StandardTemplateParams hideTime(boolean hideTime) {
12420 mHideTime = hideTime;
12421 return this;
12422 }
12423
12424 final StandardTemplateParams hideActions(boolean hideActions) {
12425 this.mHideActions = hideActions;
12426 return this;
12427 }
12428
12429 final StandardTemplateParams hideProgress(boolean hideProgress) {
12430 this.mHideProgress = hideProgress;
12431 return this;
12432 }
12433
12434 final StandardTemplateParams hideTitle(boolean hideTitle) {
12435 this.mHideTitle = hideTitle;
12436 return this;
12437 }
12438
12439 final StandardTemplateParams callStyleActions(boolean callStyleActions) {
12440 this.mCallStyleActions = callStyleActions;
12441 return this;
12442 }
12443
12444 final StandardTemplateParams allowTextWithProgress(boolean allowTextWithProgress) {
12445 this.mAllowTextWithProgress = allowTextWithProgress;
12446 return this;
12447 }
12448
12449 final StandardTemplateParams hideSnoozeButton(boolean hideSnoozeButton) {
12450 this.mHideSnoozeButton = hideSnoozeButton;
12451 return this;
12452 }
12453
12454 final StandardTemplateParams promotedPicture(Icon promotedPicture) {
12455 this.mPromotedPicture = promotedPicture;
12456 return this;
12457 }
12458
12459 public StandardTemplateParams titleViewId(int titleViewId) {
12460 mTitleViewId = titleViewId;
12461 return this;
12462 }
12463
12464 public StandardTemplateParams textViewId(int textViewId) {
12465 mTextViewId = textViewId;
12466 return this;
12467 }
12468
12469 final StandardTemplateParams title(CharSequence title) {
12470 this.title = title;
12471 return this;
12472 }
12473
12474 final StandardTemplateParams text(CharSequence text) {
12475 this.text = text;
12476 return this;
12477 }
12478
12479 final StandardTemplateParams summaryText(CharSequence text) {
12480 this.summaryText = text;
12481 return this;
12482 }
12483
12484 final StandardTemplateParams headerTextSecondary(CharSequence text) {
12485 this.headerTextSecondary = text;
12486 return this;
12487 }
12488
12489
12490 final StandardTemplateParams hideLeftIcon(boolean hideLeftIcon) {
12491 this.mHideLeftIcon = hideLeftIcon;
12492 return this;
12493 }
12494
12495 final StandardTemplateParams hideRightIcon(boolean hideRightIcon) {
12496 this.mHideRightIcon = hideRightIcon;
12497 return this;
12498 }
12499
12500 final StandardTemplateParams disallowColorization() {
12501 this.allowColorization = false;
12502 return this;
12503 }
12504
12505 final StandardTemplateParams highlightExpander(boolean highlight) {
12506 this.mHighlightExpander = highlight;
12507 return this;
12508 }
12509
12510 final StandardTemplateParams fillTextsFrom(Builder b) {
12511 Bundle extras = b.mN.extras;
12512 this.title = b.processLegacyText(extras.getCharSequence(EXTRA_TITLE));
12513 this.text = b.processLegacyText(extras.getCharSequence(EXTRA_TEXT));
12514 this.summaryText = extras.getCharSequence(EXTRA_SUB_TEXT);
12515 return this;
12516 }
12517
12518 /**
12519 * Set the maximum lines of remote input history lines allowed.
12520 * @param maxRemoteInputHistory The number of lines.
12521 * @return The builder for method chaining.
12522 */
12523 public StandardTemplateParams setMaxRemoteInputHistory(int maxRemoteInputHistory) {
12524 this.maxRemoteInputHistory = maxRemoteInputHistory;
12525 return this;
12526 }
12527
12528 public StandardTemplateParams decorationType(int decorationType) {
12529 hideTitle(true);
12530 // Minimally decorated custom views do not show certain pieces of chrome that have
12531 // always been shown when using DecoratedCustomViewStyle.
12532 boolean hideOtherFields = decorationType <= DECORATION_MINIMAL;
12533 hideLeftIcon(false); // The left icon decoration is better than showing nothing.
12534 hideRightIcon(hideOtherFields);
12535 hideProgress(hideOtherFields);
12536 hideActions(hideOtherFields);
12537 return this;
12538 }
12539 }
12540
12541 /**
12542 * A utility which stores and calculates the palette of colors used to color notifications.
12543 * @hide
12544 */
12545 @VisibleForTesting
12546 public static class Colors {
12547 private int mPaletteIsForRawColor = COLOR_INVALID;
12548 private boolean mPaletteIsForColorized = false;
12549 private boolean mPaletteIsForNightMode = false;
12550 // The following colors are the palette
12551 private int mBackgroundColor = COLOR_INVALID;
12552 private int mProtectionColor = COLOR_INVALID;
12553 private int mPrimaryTextColor = COLOR_INVALID;
12554 private int mSecondaryTextColor = COLOR_INVALID;
12555 private int mPrimaryAccentColor = COLOR_INVALID;
12556 private int mSecondaryAccentColor = COLOR_INVALID;
12557 private int mTertiaryAccentColor = COLOR_INVALID;
12558 private int mOnAccentTextColor = COLOR_INVALID;
12559 private int mErrorColor = COLOR_INVALID;
12560 private int mContrastColor = COLOR_INVALID;
12561 private int mRippleAlpha = 0x33;
12562
12563 /**
12564 * A utility for obtaining a TypedArray of the given DayNight-styled attributes, which
12565 * returns null when the context is a mock with no theme.
12566 *
12567 * NOTE: Calling this method is expensive, as creating a new ContextThemeWrapper
12568 * instances can allocate as much as 5MB of memory, so its important to call this method
12569 * only when necessary, getting as many attributes as possible from each call.
12570 *
12571 * @see Resources.Theme#obtainStyledAttributes(int[])
12572 */
12573 @Nullable
12574 private static TypedArray obtainDayNightAttributes(@NonNull Context ctx,
12575 @NonNull @StyleableRes int[] attrs) {
12576 // when testing, the mock context may have no theme
12577 if (ctx.getTheme() == null) {
12578 return null;
12579 }
12580 Resources.Theme theme = new ContextThemeWrapper(ctx,
12581 R.style.Theme_DeviceDefault_DayNight).getTheme();
12582 return theme.obtainStyledAttributes(attrs);
12583 }
12584
12585 /** A null-safe wrapper of TypedArray.getColor because mocks return null */
12586 private static @ColorInt int getColor(@Nullable TypedArray ta, int index,
12587 @ColorInt int defValue) {
12588 return ta == null ? defValue : ta.getColor(index, defValue);
12589 }
12590
12591 /**
12592 * Resolve the palette. If the inputs have not changed, this will be a no-op.
12593 * This does not handle invalidating the resolved colors when the context itself changes,
12594 * because that case does not happen in the current notification inflation pipeline; we will
12595 * recreate a new builder (and thus a new palette) when reinflating notifications for a new
12596 * theme (admittedly, we do the same for night mode, but that's easy to check).
12597 *
12598 * @param ctx the builder context.
12599 * @param rawColor the notification's color; may be COLOR_DEFAULT, but may never have alpha.
12600 * @param isColorized whether the notification is colorized.
12601 * @param nightMode whether the UI is in night mode.
12602 */
12603 public void resolvePalette(Context ctx, int rawColor,
12604 boolean isColorized, boolean nightMode) {
12605 if (mPaletteIsForRawColor == rawColor
12606 && mPaletteIsForColorized == isColorized
12607 && mPaletteIsForNightMode == nightMode) {
12608 return;
12609 }
12610 mPaletteIsForRawColor = rawColor;
12611 mPaletteIsForColorized = isColorized;
12612 mPaletteIsForNightMode = nightMode;
12613
12614 if (isColorized) {
12615 if (rawColor == COLOR_DEFAULT) {
12616 int[] attrs = {R.attr.colorAccentSecondary};
12617 try (TypedArray ta = obtainDayNightAttributes(ctx, attrs)) {
12618 mBackgroundColor = getColor(ta, 0, Color.WHITE);
12619 }
12620 } else {
12621 mBackgroundColor = rawColor;
12622 }
12623 mProtectionColor = COLOR_INVALID; // filled in at the end
12624 mPrimaryTextColor = ContrastColorUtil.findAlphaToMeetContrast(
12625 ContrastColorUtil.resolvePrimaryColor(ctx, mBackgroundColor, nightMode),
12626 mBackgroundColor, 4.5);
12627 mSecondaryTextColor = ContrastColorUtil.findAlphaToMeetContrast(
12628 ContrastColorUtil.resolveSecondaryColor(ctx, mBackgroundColor, nightMode),
12629 mBackgroundColor, 4.5);
12630 mContrastColor = mPrimaryTextColor;
12631 mPrimaryAccentColor = mPrimaryTextColor;
12632 mSecondaryAccentColor = mSecondaryTextColor;
12633 mTertiaryAccentColor = flattenAlpha(mPrimaryTextColor, mBackgroundColor);
12634 mOnAccentTextColor = mBackgroundColor;
12635 mErrorColor = mPrimaryTextColor;
12636 mRippleAlpha = 0x33;
12637 } else {
12638 int[] attrs = {
12639 R.attr.colorSurface,
12640 R.attr.colorBackgroundFloating,
12641 R.attr.textColorPrimary,
12642 R.attr.textColorSecondary,
12643 R.attr.colorAccent,
12644 R.attr.colorAccentSecondary,
12645 R.attr.colorAccentTertiary,
12646 R.attr.textColorOnAccent,
12647 R.attr.colorError,
12648 R.attr.colorControlHighlight
12649 };
12650 try (TypedArray ta = obtainDayNightAttributes(ctx, attrs)) {
12651 mBackgroundColor = getColor(ta, 0, nightMode ? Color.BLACK : Color.WHITE);
12652 mProtectionColor = getColor(ta, 1, COLOR_INVALID);
12653 mPrimaryTextColor = getColor(ta, 2, COLOR_INVALID);
12654 mSecondaryTextColor = getColor(ta, 3, COLOR_INVALID);
12655 mPrimaryAccentColor = getColor(ta, 4, COLOR_INVALID);
12656 mSecondaryAccentColor = getColor(ta, 5, COLOR_INVALID);
12657 mTertiaryAccentColor = getColor(ta, 6, COLOR_INVALID);
12658 mOnAccentTextColor = getColor(ta, 7, COLOR_INVALID);
12659 mErrorColor = getColor(ta, 8, COLOR_INVALID);
12660 mRippleAlpha = Color.alpha(getColor(ta, 9, 0x33ffffff));
12661 }
12662 mContrastColor = calculateContrastColor(ctx, rawColor, mPrimaryAccentColor,
12663 mBackgroundColor, nightMode);
12664
12665 // make sure every color has a valid value
12666 if (mPrimaryTextColor == COLOR_INVALID) {
12667 mPrimaryTextColor = ContrastColorUtil.resolvePrimaryColor(
12668 ctx, mBackgroundColor, nightMode);
12669 }
12670 if (mSecondaryTextColor == COLOR_INVALID) {
12671 mSecondaryTextColor = ContrastColorUtil.resolveSecondaryColor(
12672 ctx, mBackgroundColor, nightMode);
12673 }
12674 if (mPrimaryAccentColor == COLOR_INVALID) {
12675 mPrimaryAccentColor = mContrastColor;
12676 }
12677 if (mSecondaryAccentColor == COLOR_INVALID) {
12678 mSecondaryAccentColor = mContrastColor;
12679 }
12680 if (mTertiaryAccentColor == COLOR_INVALID) {
12681 mTertiaryAccentColor = mContrastColor;
12682 }
12683 if (mOnAccentTextColor == COLOR_INVALID) {
12684 mOnAccentTextColor = ColorUtils.setAlphaComponent(
12685 ContrastColorUtil.resolvePrimaryColor(
12686 ctx, mTertiaryAccentColor, nightMode), 0xFF);
12687 }
12688 if (mErrorColor == COLOR_INVALID) {
12689 mErrorColor = mPrimaryTextColor;
12690 }
12691 }
12692 // make sure every color has a valid value
12693 if (mProtectionColor == COLOR_INVALID) {
12694 mProtectionColor = ColorUtils.blendARGB(mPrimaryTextColor, mBackgroundColor, 0.8f);
12695 }
12696 }
12697
12698 /** calculates the contrast color for the non-colorized notifications */
12699 private static @ColorInt int calculateContrastColor(Context ctx, @ColorInt int rawColor,
12700 @ColorInt int accentColor, @ColorInt int backgroundColor, boolean nightMode) {
12701 int color;
12702 if (rawColor == COLOR_DEFAULT) {
12703 color = accentColor;
12704 if (color == COLOR_INVALID) {
12705 color = ContrastColorUtil.resolveDefaultColor(ctx, backgroundColor, nightMode);
12706 }
12707 } else {
12708 color = ContrastColorUtil.resolveContrastColor(ctx, rawColor, backgroundColor,
12709 nightMode);
12710 }
12711 return flattenAlpha(color, backgroundColor);
12712 }
12713
12714 /** remove any alpha by manually blending it with the given background. */
12715 private static @ColorInt int flattenAlpha(@ColorInt int color, @ColorInt int background) {
12716 return Color.alpha(color) == 0xff ? color
12717 : ContrastColorUtil.compositeColors(color, background);
12718 }
12719
12720 /** @return the notification's background color */
12721 public @ColorInt int getBackgroundColor() {
12722 return mBackgroundColor;
12723 }
12724
12725 /**
12726 * @return the "surface protection" color from the theme,
12727 * or a variant of the normal background color when colorized.
12728 */
12729 public @ColorInt int getProtectionColor() {
12730 return mProtectionColor;
12731 }
12732
12733 /** @return the color for the most prominent text */
12734 public @ColorInt int getPrimaryTextColor() {
12735 return mPrimaryTextColor;
12736 }
12737
12738 /** @return the color for less prominent text */
12739 public @ColorInt int getSecondaryTextColor() {
12740 return mSecondaryTextColor;
12741 }
12742
12743 /** @return the theme's accent color for colored UI elements. */
12744 public @ColorInt int getPrimaryAccentColor() {
12745 return mPrimaryAccentColor;
12746 }
12747
12748 /** @return the theme's secondary accent color for colored UI elements. */
12749 public @ColorInt int getSecondaryAccentColor() {
12750 return mSecondaryAccentColor;
12751 }
12752
12753 /** @return the theme's tertiary accent color for colored UI elements. */
12754 public @ColorInt int getTertiaryAccentColor() {
12755 return mTertiaryAccentColor;
12756 }
12757
12758 /** @return the theme's text color to be used on the tertiary accent color. */
12759 public @ColorInt int getOnAccentTextColor() {
12760 return mOnAccentTextColor;
12761 }
12762
12763 /**
12764 * @return the contrast-adjusted version of the color provided by the app, or the
12765 * primary text color when colorized.
12766 */
12767 public @ColorInt int getContrastColor() {
12768 return mContrastColor;
12769 }
12770
12771 /** @return the theme's error color, or the primary text color when colorized. */
12772 public @ColorInt int getErrorColor() {
12773 return mErrorColor;
12774 }
12775
12776 /** @return the alpha component of the current theme's control highlight color. */
12777 public int getRippleAlpha() {
12778 return mRippleAlpha;
12779 }
12780 }
12781 }