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