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