Notification.java revision bee4e074bbb791f7696233ce43bcf28a75dd1d99
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                    && p.maxRemoteInputHistory > 0) {
4907                boolean showSpinner = mN.extras.getBoolean(EXTRA_SHOW_REMOTE_INPUT_SPINNER);
4908                big.setViewVisibility(R.id.notification_material_reply_container, View.VISIBLE);
4909                big.setViewVisibility(R.id.notification_material_reply_text_1_container,
4910                        View.VISIBLE);
4911                big.setTextViewText(R.id.notification_material_reply_text_1,
4912                        processTextSpans(replyText[0]));
4913                setTextViewColorSecondary(big, R.id.notification_material_reply_text_1);
4914                big.setViewVisibility(R.id.notification_material_reply_progress,
4915                        showSpinner ? View.VISIBLE : View.GONE);
4916                big.setProgressIndeterminateTintList(
4917                        R.id.notification_material_reply_progress,
4918                        ColorStateList.valueOf(
4919                                isColorized() ? getPrimaryTextColor() : resolveContrastColor()));
4920
4921                if (replyText.length > 1 && !TextUtils.isEmpty(replyText[1])
4922                        && p.maxRemoteInputHistory > 1) {
4923                    big.setViewVisibility(R.id.notification_material_reply_text_2, View.VISIBLE);
4924                    big.setTextViewText(R.id.notification_material_reply_text_2,
4925                            processTextSpans(replyText[1]));
4926                    setTextViewColorSecondary(big, R.id.notification_material_reply_text_2);
4927
4928                    if (replyText.length > 2 && !TextUtils.isEmpty(replyText[2])
4929                            && p.maxRemoteInputHistory > 2) {
4930                        big.setViewVisibility(
4931                                R.id.notification_material_reply_text_3, View.VISIBLE);
4932                        big.setTextViewText(R.id.notification_material_reply_text_3,
4933                                processTextSpans(replyText[2]));
4934                        setTextViewColorSecondary(big, R.id.notification_material_reply_text_3);
4935                    }
4936                }
4937            }
4938
4939            return big;
4940        }
4941
4942        private boolean hasValidRemoteInput(Action action) {
4943            if (TextUtils.isEmpty(action.title) || action.actionIntent == null) {
4944                // Weird actions
4945                return false;
4946            }
4947
4948            RemoteInput[] remoteInputs = action.getRemoteInputs();
4949            if (remoteInputs == null) {
4950                return false;
4951            }
4952
4953            for (RemoteInput r : remoteInputs) {
4954                CharSequence[] choices = r.getChoices();
4955                if (r.getAllowFreeFormInput() || (choices != null && choices.length != 0)) {
4956                    return true;
4957                }
4958            }
4959            return false;
4960        }
4961
4962        /**
4963         * Construct a RemoteViews for the final 1U notification layout. In order:
4964         *   1. Custom contentView from the caller
4965         *   2. Style's proposed content view
4966         *   3. Standard template view
4967         */
4968        public RemoteViews createContentView() {
4969            return createContentView(false /* increasedheight */ );
4970        }
4971
4972        /**
4973         * Construct a RemoteViews for the smaller content view.
4974         *
4975         *   @param increasedHeight true if this layout be created with an increased height. Some
4976         *   styles may support showing more then just that basic 1U size
4977         *   and the system may decide to render important notifications
4978         *   slightly bigger even when collapsed.
4979         *
4980         *   @hide
4981         */
4982        public RemoteViews createContentView(boolean increasedHeight) {
4983            if (mN.contentView != null && useExistingRemoteView()) {
4984                return mN.contentView;
4985            } else if (mStyle != null) {
4986                final RemoteViews styleView = mStyle.makeContentView(increasedHeight);
4987                if (styleView != null) {
4988                    return styleView;
4989                }
4990            }
4991            return applyStandardTemplate(getBaseLayoutResource(), null /* result */);
4992        }
4993
4994        private boolean useExistingRemoteView() {
4995            return mStyle == null || (!mStyle.displayCustomViewInline()
4996                    && !mRebuildStyledRemoteViews);
4997        }
4998
4999        /**
5000         * Construct a RemoteViews for the final big notification layout.
5001         */
5002        public RemoteViews createBigContentView() {
5003            RemoteViews result = null;
5004            if (mN.bigContentView != null && useExistingRemoteView()) {
5005                return mN.bigContentView;
5006            } else if (mStyle != null) {
5007                result = mStyle.makeBigContentView();
5008                hideLine1Text(result);
5009            } else if (mActions.size() != 0) {
5010                result = applyStandardTemplateWithActions(getBigBaseLayoutResource(),
5011                        null /* result */);
5012            }
5013            makeHeaderExpanded(result);
5014            return result;
5015        }
5016
5017        /**
5018         * Construct a RemoteViews for the final notification header only. This will not be
5019         * colorized.
5020         *
5021         * @param ambient if true, generate the header for the ambient display layout.
5022         * @hide
5023         */
5024        public RemoteViews makeNotificationHeader(boolean ambient) {
5025            Boolean colorized = (Boolean) mN.extras.get(EXTRA_COLORIZED);
5026            mN.extras.putBoolean(EXTRA_COLORIZED, false);
5027            RemoteViews header = new BuilderRemoteViews(mContext.getApplicationInfo(),
5028                    ambient ? R.layout.notification_template_ambient_header
5029                            : R.layout.notification_template_header);
5030            resetNotificationHeader(header);
5031            bindNotificationHeader(header, ambient, null);
5032            if (colorized != null) {
5033                mN.extras.putBoolean(EXTRA_COLORIZED, colorized);
5034            } else {
5035                mN.extras.remove(EXTRA_COLORIZED);
5036            }
5037            return header;
5038        }
5039
5040        /**
5041         * Construct a RemoteViews for the ambient version of the notification.
5042         *
5043         * @hide
5044         */
5045        public RemoteViews makeAmbientNotification() {
5046            RemoteViews ambient = applyStandardTemplateWithActions(
5047                    R.layout.notification_template_material_ambient,
5048                    mParams.reset().ambient(true).fillTextsFrom(this).hasProgress(false),
5049                    null /* result */);
5050            return ambient;
5051        }
5052
5053        private void hideLine1Text(RemoteViews result) {
5054            if (result != null) {
5055                result.setViewVisibility(R.id.text_line_1, View.GONE);
5056            }
5057        }
5058
5059        /**
5060         * Adapt the Notification header if this view is used as an expanded view.
5061         *
5062         * @hide
5063         */
5064        public static void makeHeaderExpanded(RemoteViews result) {
5065            if (result != null) {
5066                result.setBoolean(R.id.notification_header, "setExpanded", true);
5067            }
5068        }
5069
5070        /**
5071         * Construct a RemoteViews for the final heads-up notification layout.
5072         *
5073         * @param increasedHeight true if this layout be created with an increased height. Some
5074         * styles may support showing more then just that basic 1U size
5075         * and the system may decide to render important notifications
5076         * slightly bigger even when collapsed.
5077         *
5078         * @hide
5079         */
5080        public RemoteViews createHeadsUpContentView(boolean increasedHeight) {
5081            if (mN.headsUpContentView != null && useExistingRemoteView()) {
5082                return mN.headsUpContentView;
5083            } else if (mStyle != null) {
5084                final RemoteViews styleView = mStyle.makeHeadsUpContentView(increasedHeight);
5085                if (styleView != null) {
5086                    return styleView;
5087                }
5088            } else if (mActions.size() == 0) {
5089                return null;
5090            }
5091
5092            // We only want at most a single remote input history to be shown here, otherwise
5093            // the content would become squished.
5094            StandardTemplateParams p = mParams.reset().fillTextsFrom(this)
5095                    .setMaxRemoteInputHistory(1);
5096            return applyStandardTemplateWithActions(getBigBaseLayoutResource(),
5097                    p,
5098                    null /* result */);
5099        }
5100
5101        /**
5102         * Construct a RemoteViews for the final heads-up notification layout.
5103         */
5104        public RemoteViews createHeadsUpContentView() {
5105            return createHeadsUpContentView(false /* useIncreasedHeight */);
5106        }
5107
5108        /**
5109         * Construct a RemoteViews for the display in public contexts like on the lockscreen.
5110         *
5111         * @hide
5112         */
5113        public RemoteViews makePublicContentView() {
5114            return makePublicView(false /* ambient */);
5115        }
5116
5117        /**
5118         * Construct a RemoteViews for the display in public contexts like on the lockscreen.
5119         *
5120         * @hide
5121         */
5122        public RemoteViews makePublicAmbientNotification() {
5123            return makePublicView(true /* ambient */);
5124        }
5125
5126        private RemoteViews makePublicView(boolean ambient) {
5127            if (mN.publicVersion != null) {
5128                final Builder builder = recoverBuilder(mContext, mN.publicVersion);
5129                return ambient ? builder.makeAmbientNotification() : builder.createContentView();
5130            }
5131            Bundle savedBundle = mN.extras;
5132            Style style = mStyle;
5133            mStyle = null;
5134            Icon largeIcon = mN.mLargeIcon;
5135            mN.mLargeIcon = null;
5136            Bitmap largeIconLegacy = mN.largeIcon;
5137            mN.largeIcon = null;
5138            ArrayList<Action> actions = mActions;
5139            mActions = new ArrayList<>();
5140            Bundle publicExtras = new Bundle();
5141            publicExtras.putBoolean(EXTRA_SHOW_WHEN,
5142                    savedBundle.getBoolean(EXTRA_SHOW_WHEN));
5143            publicExtras.putBoolean(EXTRA_SHOW_CHRONOMETER,
5144                    savedBundle.getBoolean(EXTRA_SHOW_CHRONOMETER));
5145            publicExtras.putBoolean(EXTRA_CHRONOMETER_COUNT_DOWN,
5146                    savedBundle.getBoolean(EXTRA_CHRONOMETER_COUNT_DOWN));
5147            String appName = savedBundle.getString(EXTRA_SUBSTITUTE_APP_NAME);
5148            if (appName != null) {
5149                publicExtras.putString(EXTRA_SUBSTITUTE_APP_NAME, appName);
5150            }
5151            mN.extras = publicExtras;
5152            RemoteViews view;
5153            if (ambient) {
5154                publicExtras.putCharSequence(EXTRA_TITLE,
5155                        mContext.getString(com.android.internal.R.string.notification_hidden_text));
5156                view = makeAmbientNotification();
5157            } else{
5158                view = makeNotificationHeader(false /* ambient */);
5159                view.setBoolean(R.id.notification_header, "setExpandOnlyOnButton", true);
5160            }
5161            mN.extras = savedBundle;
5162            mN.mLargeIcon = largeIcon;
5163            mN.largeIcon = largeIconLegacy;
5164            mActions = actions;
5165            mStyle = style;
5166            return view;
5167        }
5168
5169        /**
5170         * Construct a content view for the display when low - priority
5171         *
5172         * @param useRegularSubtext uses the normal subtext set if there is one available. Otherwise
5173         *                          a new subtext is created consisting of the content of the
5174         *                          notification.
5175         * @hide
5176         */
5177        public RemoteViews makeLowPriorityContentView(boolean useRegularSubtext) {
5178            int color = mN.color;
5179            mN.color = COLOR_DEFAULT;
5180            CharSequence summary = mN.extras.getCharSequence(EXTRA_SUB_TEXT);
5181            if (!useRegularSubtext || TextUtils.isEmpty(summary)) {
5182                CharSequence newSummary = createSummaryText();
5183                if (!TextUtils.isEmpty(newSummary)) {
5184                    mN.extras.putCharSequence(EXTRA_SUB_TEXT, newSummary);
5185                }
5186            }
5187
5188            RemoteViews header = makeNotificationHeader(false /* ambient */);
5189            header.setBoolean(R.id.notification_header, "setAcceptAllTouches", true);
5190            if (summary != null) {
5191                mN.extras.putCharSequence(EXTRA_SUB_TEXT, summary);
5192            } else {
5193                mN.extras.remove(EXTRA_SUB_TEXT);
5194            }
5195            mN.color = color;
5196            return header;
5197        }
5198
5199        private CharSequence createSummaryText() {
5200            CharSequence titleText = mN.extras.getCharSequence(Notification.EXTRA_TITLE);
5201            if (USE_ONLY_TITLE_IN_LOW_PRIORITY_SUMMARY) {
5202                return titleText;
5203            }
5204            SpannableStringBuilder summary = new SpannableStringBuilder();
5205            if (titleText == null) {
5206                titleText = mN.extras.getCharSequence(Notification.EXTRA_TITLE_BIG);
5207            }
5208            BidiFormatter bidi = BidiFormatter.getInstance();
5209            if (titleText != null) {
5210                summary.append(bidi.unicodeWrap(titleText));
5211            }
5212            CharSequence contentText = mN.extras.getCharSequence(Notification.EXTRA_TEXT);
5213            if (titleText != null && contentText != null) {
5214                summary.append(bidi.unicodeWrap(mContext.getText(
5215                        R.string.notification_header_divider_symbol_with_spaces)));
5216            }
5217            if (contentText != null) {
5218                summary.append(bidi.unicodeWrap(contentText));
5219            }
5220            return summary;
5221        }
5222
5223        private RemoteViews generateActionButton(Action action, boolean emphazisedMode,
5224                boolean ambient) {
5225            final boolean tombstone = (action.actionIntent == null);
5226            RemoteViews button = new BuilderRemoteViews(mContext.getApplicationInfo(),
5227                    emphazisedMode ? getEmphasizedActionLayoutResource()
5228                            : tombstone ? getActionTombstoneLayoutResource()
5229                                    : getActionLayoutResource());
5230            if (!tombstone) {
5231                button.setOnClickPendingIntent(R.id.action0, action.actionIntent);
5232            }
5233            button.setContentDescription(R.id.action0, action.title);
5234            if (action.mRemoteInputs != null) {
5235                button.setRemoteInputs(R.id.action0, action.mRemoteInputs);
5236            }
5237            if (emphazisedMode) {
5238                // change the background bgColor
5239                CharSequence title = action.title;
5240                ColorStateList[] outResultColor = null;
5241                int background = resolveBackgroundColor();
5242                if (isLegacy()) {
5243                    title = NotificationColorUtil.clearColorSpans(title);
5244                } else {
5245                    outResultColor = new ColorStateList[1];
5246                    title = ensureColorSpanContrast(title, background, outResultColor);
5247                }
5248                button.setTextViewText(R.id.action0, processTextSpans(title));
5249                setTextViewColorPrimary(button, R.id.action0);
5250                int rippleColor;
5251                boolean hasColorOverride = outResultColor != null && outResultColor[0] != null;
5252                if (hasColorOverride) {
5253                    // There's a span spanning the full text, let's take it and use it as the
5254                    // background color
5255                    background = outResultColor[0].getDefaultColor();
5256                    int textColor = NotificationColorUtil.resolvePrimaryColor(mContext,
5257                            background);
5258                    button.setTextColor(R.id.action0, textColor);
5259                    rippleColor = textColor;
5260                } else if (mN.color != COLOR_DEFAULT && !isColorized() && mTintActionButtons) {
5261                    rippleColor = resolveContrastColor();
5262                    button.setTextColor(R.id.action0, rippleColor);
5263                } else {
5264                    rippleColor = getPrimaryTextColor();
5265                }
5266                // We only want about 20% alpha for the ripple
5267                rippleColor = (rippleColor & 0x00ffffff) | 0x33000000;
5268                button.setColorStateList(R.id.action0, "setRippleColor",
5269                        ColorStateList.valueOf(rippleColor));
5270                button.setColorStateList(R.id.action0, "setButtonBackground",
5271                        ColorStateList.valueOf(background));
5272                button.setBoolean(R.id.action0, "setHasStroke", !hasColorOverride);
5273            } else {
5274                button.setTextViewText(R.id.action0, processTextSpans(
5275                        processLegacyText(action.title)));
5276                if (isColorized() && !ambient) {
5277                    setTextViewColorPrimary(button, R.id.action0);
5278                } else if (mN.color != COLOR_DEFAULT && mTintActionButtons) {
5279                    button.setTextColor(R.id.action0,
5280                            ambient ? resolveAmbientColor() : resolveContrastColor());
5281                }
5282            }
5283            return button;
5284        }
5285
5286        /**
5287         * Ensures contrast on color spans against a background color. also returns the color of the
5288         * text if a span was found that spans over the whole text.
5289         *
5290         * @param charSequence the charSequence on which the spans are
5291         * @param background the background color to ensure the contrast against
5292         * @param outResultColor an array in which a color will be returned as the first element if
5293         *                    there exists a full length color span.
5294         * @return the contrasted charSequence
5295         */
5296        private CharSequence ensureColorSpanContrast(CharSequence charSequence, int background,
5297                ColorStateList[] outResultColor) {
5298            if (charSequence instanceof Spanned) {
5299                Spanned ss = (Spanned) charSequence;
5300                Object[] spans = ss.getSpans(0, ss.length(), Object.class);
5301                SpannableStringBuilder builder = new SpannableStringBuilder(ss.toString());
5302                for (Object span : spans) {
5303                    Object resultSpan = span;
5304                    int spanStart = ss.getSpanStart(span);
5305                    int spanEnd = ss.getSpanEnd(span);
5306                    boolean fullLength = (spanEnd - spanStart) == charSequence.length();
5307                    if (resultSpan instanceof CharacterStyle) {
5308                        resultSpan = ((CharacterStyle) span).getUnderlying();
5309                    }
5310                    if (resultSpan instanceof TextAppearanceSpan) {
5311                        TextAppearanceSpan originalSpan = (TextAppearanceSpan) resultSpan;
5312                        ColorStateList textColor = originalSpan.getTextColor();
5313                        if (textColor != null) {
5314                            int[] colors = textColor.getColors();
5315                            int[] newColors = new int[colors.length];
5316                            for (int i = 0; i < newColors.length; i++) {
5317                                newColors[i] = NotificationColorUtil.ensureLargeTextContrast(
5318                                        colors[i], background, mInNightMode);
5319                            }
5320                            textColor = new ColorStateList(textColor.getStates().clone(),
5321                                    newColors);
5322                            if (fullLength) {
5323                                outResultColor[0] = textColor;
5324                                // Let's drop the color from the span
5325                                textColor = null;
5326                            }
5327                            resultSpan = new TextAppearanceSpan(
5328                                    originalSpan.getFamily(),
5329                                    originalSpan.getTextStyle(),
5330                                    originalSpan.getTextSize(),
5331                                    textColor,
5332                                    originalSpan.getLinkTextColor());
5333                        }
5334                    } else if (resultSpan instanceof ForegroundColorSpan) {
5335                        ForegroundColorSpan originalSpan = (ForegroundColorSpan) resultSpan;
5336                        int foregroundColor = originalSpan.getForegroundColor();
5337                        foregroundColor = NotificationColorUtil.ensureLargeTextContrast(
5338                                foregroundColor, background, mInNightMode);
5339                        if (fullLength) {
5340                            outResultColor[0] = ColorStateList.valueOf(foregroundColor);
5341                            resultSpan = null;
5342                        } else {
5343                            resultSpan = new ForegroundColorSpan(foregroundColor);
5344                        }
5345                    } else {
5346                        resultSpan = span;
5347                    }
5348                    if (resultSpan != null) {
5349                        builder.setSpan(resultSpan, spanStart, spanEnd, ss.getSpanFlags(span));
5350                    }
5351                }
5352                return builder;
5353            }
5354            return charSequence;
5355        }
5356
5357        /**
5358         * @return Whether we are currently building a notification from a legacy (an app that
5359         *         doesn't create material notifications by itself) app.
5360         */
5361        private boolean isLegacy() {
5362            if (!mIsLegacyInitialized) {
5363                mIsLegacy = mContext.getApplicationInfo().targetSdkVersion
5364                        < Build.VERSION_CODES.LOLLIPOP;
5365                mIsLegacyInitialized = true;
5366            }
5367            return mIsLegacy;
5368        }
5369
5370        private CharSequence processLegacyText(CharSequence charSequence) {
5371            return processLegacyText(charSequence, false /* ambient */);
5372        }
5373
5374        private CharSequence processLegacyText(CharSequence charSequence, boolean ambient) {
5375            boolean isAlreadyLightText = isLegacy() || textColorsNeedInversion();
5376            boolean wantLightText = ambient;
5377            if (isAlreadyLightText != wantLightText) {
5378                return getColorUtil().invertCharSequenceColors(charSequence);
5379            } else {
5380                return charSequence;
5381            }
5382        }
5383
5384        /**
5385         * Apply any necessariy colors to the small icon
5386         */
5387        private void processSmallIconColor(Icon smallIcon, RemoteViews contentView,
5388                boolean ambient) {
5389            boolean colorable = !isLegacy() || getColorUtil().isGrayscaleIcon(mContext, smallIcon);
5390            int color;
5391            if (ambient) {
5392                color = resolveAmbientColor();
5393            } else if (isColorized()) {
5394                color = getPrimaryTextColor();
5395            } else {
5396                color = resolveContrastColor();
5397            }
5398            if (colorable) {
5399                contentView.setDrawableTint(R.id.icon, false, color,
5400                        PorterDuff.Mode.SRC_ATOP);
5401
5402            }
5403            contentView.setInt(R.id.notification_header, "setOriginalIconColor",
5404                    colorable ? color : NotificationHeaderView.NO_COLOR);
5405        }
5406
5407        /**
5408         * Make the largeIcon dark if it's a fake smallIcon (that is,
5409         * if it's grayscale).
5410         */
5411        // TODO: also check bounds, transparency, that sort of thing.
5412        private void processLargeLegacyIcon(Icon largeIcon, RemoteViews contentView) {
5413            if (largeIcon != null && isLegacy()
5414                    && getColorUtil().isGrayscaleIcon(mContext, largeIcon)) {
5415                // resolve color will fall back to the default when legacy
5416                contentView.setDrawableTint(R.id.icon, false, resolveContrastColor(),
5417                        PorterDuff.Mode.SRC_ATOP);
5418            }
5419        }
5420
5421        private void sanitizeColor() {
5422            if (mN.color != COLOR_DEFAULT) {
5423                mN.color |= 0xFF000000; // no alpha for custom colors
5424            }
5425        }
5426
5427        int resolveContrastColor() {
5428            if (mCachedContrastColorIsFor == mN.color && mCachedContrastColor != COLOR_INVALID) {
5429                return mCachedContrastColor;
5430            }
5431
5432            int color;
5433            int background = mContext.getColor(
5434                    com.android.internal.R.color.notification_material_background_color);
5435            if (mN.color == COLOR_DEFAULT) {
5436                ensureColors();
5437                color = NotificationColorUtil.resolveDefaultColor(mContext, background);
5438            } else {
5439                color = NotificationColorUtil.resolveContrastColor(mContext, mN.color,
5440                        background, mInNightMode);
5441            }
5442            if (Color.alpha(color) < 255) {
5443                // alpha doesn't go well for color filters, so let's blend it manually
5444                color = NotificationColorUtil.compositeColors(color, background);
5445            }
5446            mCachedContrastColorIsFor = mN.color;
5447            return mCachedContrastColor = color;
5448        }
5449
5450        int resolveNeutralColor() {
5451            if (mNeutralColor != COLOR_INVALID) {
5452                return mNeutralColor;
5453            }
5454            int background = mContext.getColor(
5455                    com.android.internal.R.color.notification_material_background_color);
5456            mNeutralColor = NotificationColorUtil.resolveDefaultColor(mContext, background);
5457            if (Color.alpha(mNeutralColor) < 255) {
5458                // alpha doesn't go well for color filters, so let's blend it manually
5459                mNeutralColor = NotificationColorUtil.compositeColors(mNeutralColor, background);
5460            }
5461            return mNeutralColor;
5462        }
5463
5464        int resolveAmbientColor() {
5465            if (mCachedAmbientColorIsFor == mN.color && mCachedAmbientColorIsFor != COLOR_INVALID) {
5466                return mCachedAmbientColor;
5467            }
5468            final int contrasted = NotificationColorUtil.resolveAmbientColor(mContext, mN.color);
5469
5470            mCachedAmbientColorIsFor = mN.color;
5471            return mCachedAmbientColor = contrasted;
5472        }
5473
5474        /**
5475         * Apply the unstyled operations and return a new {@link Notification} object.
5476         * @hide
5477         */
5478        public Notification buildUnstyled() {
5479            if (mActions.size() > 0) {
5480                mN.actions = new Action[mActions.size()];
5481                mActions.toArray(mN.actions);
5482            }
5483            if (!mPersonList.isEmpty()) {
5484                mN.extras.putParcelableArrayList(EXTRA_PEOPLE_LIST, mPersonList);
5485            }
5486            if (mN.bigContentView != null || mN.contentView != null
5487                    || mN.headsUpContentView != null) {
5488                mN.extras.putBoolean(EXTRA_CONTAINS_CUSTOM_VIEW, true);
5489            }
5490            return mN;
5491        }
5492
5493        /**
5494         * Creates a Builder from an existing notification so further changes can be made.
5495         * @param context The context for your application / activity.
5496         * @param n The notification to create a Builder from.
5497         */
5498        public static Notification.Builder recoverBuilder(Context context, Notification n) {
5499            // Re-create notification context so we can access app resources.
5500            ApplicationInfo applicationInfo = n.extras.getParcelable(
5501                    EXTRA_BUILDER_APPLICATION_INFO);
5502            Context builderContext;
5503            if (applicationInfo != null) {
5504                try {
5505                    builderContext = context.createApplicationContext(applicationInfo,
5506                            Context.CONTEXT_RESTRICTED);
5507                } catch (NameNotFoundException e) {
5508                    Log.e(TAG, "ApplicationInfo " + applicationInfo + " not found");
5509                    builderContext = context;  // try with our context
5510                }
5511            } else {
5512                builderContext = context; // try with given context
5513            }
5514
5515            return new Builder(builderContext, n);
5516        }
5517
5518        /**
5519         * @deprecated Use {@link #build()} instead.
5520         */
5521        @Deprecated
5522        public Notification getNotification() {
5523            return build();
5524        }
5525
5526        /**
5527         * Combine all of the options that have been set and return a new {@link Notification}
5528         * object.
5529         */
5530        public Notification build() {
5531            // first, add any extras from the calling code
5532            if (mUserExtras != null) {
5533                mN.extras = getAllExtras();
5534            }
5535
5536            mN.creationTime = System.currentTimeMillis();
5537
5538            // lazy stuff from mContext; see comment in Builder(Context, Notification)
5539            Notification.addFieldsFromContext(mContext, mN);
5540
5541            buildUnstyled();
5542
5543            if (mStyle != null) {
5544                mStyle.reduceImageSizes(mContext);
5545                mStyle.purgeResources();
5546                mStyle.validate(mContext);
5547                mStyle.buildStyled(mN);
5548            }
5549            mN.reduceImageSizes(mContext);
5550
5551            if (mContext.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N
5552                    && (useExistingRemoteView())) {
5553                if (mN.contentView == null) {
5554                    mN.contentView = createContentView();
5555                    mN.extras.putInt(EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT,
5556                            mN.contentView.getSequenceNumber());
5557                }
5558                if (mN.bigContentView == null) {
5559                    mN.bigContentView = createBigContentView();
5560                    if (mN.bigContentView != null) {
5561                        mN.extras.putInt(EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT,
5562                                mN.bigContentView.getSequenceNumber());
5563                    }
5564                }
5565                if (mN.headsUpContentView == null) {
5566                    mN.headsUpContentView = createHeadsUpContentView();
5567                    if (mN.headsUpContentView != null) {
5568                        mN.extras.putInt(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT,
5569                                mN.headsUpContentView.getSequenceNumber());
5570                    }
5571                }
5572            }
5573
5574            if ((mN.defaults & DEFAULT_LIGHTS) != 0) {
5575                mN.flags |= FLAG_SHOW_LIGHTS;
5576            }
5577
5578            mN.allPendingIntents = null;
5579
5580            return mN;
5581        }
5582
5583        /**
5584         * Apply this Builder to an existing {@link Notification} object.
5585         *
5586         * @hide
5587         */
5588        public Notification buildInto(Notification n) {
5589            build().cloneInto(n, true);
5590            return n;
5591        }
5592
5593        /**
5594         * Removes RemoteViews that were created for compatibility from {@param n}, if they did not
5595         * change. Also removes extenders on low ram devices, as
5596         * {@link android.service.notification.NotificationListenerService} services are disabled.
5597         *
5598         * @return {@param n}, if no stripping is needed, otherwise a stripped clone of {@param n}.
5599         *
5600         * @hide
5601         */
5602        public static Notification maybeCloneStrippedForDelivery(Notification n, boolean isLowRam,
5603                Context context) {
5604            String templateClass = n.extras.getString(EXTRA_TEMPLATE);
5605
5606            // Only strip views for known Styles because we won't know how to
5607            // re-create them otherwise.
5608            if (!isLowRam
5609                    && !TextUtils.isEmpty(templateClass)
5610                    && getNotificationStyleClass(templateClass) == null) {
5611                return n;
5612            }
5613
5614            // Only strip unmodified BuilderRemoteViews.
5615            boolean stripContentView = n.contentView instanceof BuilderRemoteViews &&
5616                    n.extras.getInt(EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT, -1) ==
5617                            n.contentView.getSequenceNumber();
5618            boolean stripBigContentView = n.bigContentView instanceof BuilderRemoteViews &&
5619                    n.extras.getInt(EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT, -1) ==
5620                            n.bigContentView.getSequenceNumber();
5621            boolean stripHeadsUpContentView = n.headsUpContentView instanceof BuilderRemoteViews &&
5622                    n.extras.getInt(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT, -1) ==
5623                            n.headsUpContentView.getSequenceNumber();
5624
5625            // Nothing to do here, no need to clone.
5626            if (!isLowRam
5627                    && !stripContentView && !stripBigContentView && !stripHeadsUpContentView) {
5628                return n;
5629            }
5630
5631            Notification clone = n.clone();
5632            if (stripContentView) {
5633                clone.contentView = null;
5634                clone.extras.remove(EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT);
5635            }
5636            if (stripBigContentView) {
5637                clone.bigContentView = null;
5638                clone.extras.remove(EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT);
5639            }
5640            if (stripHeadsUpContentView) {
5641                clone.headsUpContentView = null;
5642                clone.extras.remove(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT);
5643            }
5644            if (isLowRam) {
5645                String[] allowedServices = context.getResources().getStringArray(
5646                        R.array.config_allowedManagedServicesOnLowRamDevices);
5647                if (allowedServices.length == 0) {
5648                    clone.extras.remove(Notification.TvExtender.EXTRA_TV_EXTENDER);
5649                    clone.extras.remove(WearableExtender.EXTRA_WEARABLE_EXTENSIONS);
5650                    clone.extras.remove(CarExtender.EXTRA_CAR_EXTENDER);
5651                }
5652            }
5653            return clone;
5654        }
5655
5656        private int getBaseLayoutResource() {
5657            return R.layout.notification_template_material_base;
5658        }
5659
5660        private int getBigBaseLayoutResource() {
5661            return R.layout.notification_template_material_big_base;
5662        }
5663
5664        private int getBigPictureLayoutResource() {
5665            return R.layout.notification_template_material_big_picture;
5666        }
5667
5668        private int getBigTextLayoutResource() {
5669            return R.layout.notification_template_material_big_text;
5670        }
5671
5672        private int getInboxLayoutResource() {
5673            return R.layout.notification_template_material_inbox;
5674        }
5675
5676        private int getMessagingLayoutResource() {
5677            return R.layout.notification_template_material_messaging;
5678        }
5679
5680        private int getActionLayoutResource() {
5681            return R.layout.notification_material_action;
5682        }
5683
5684        private int getEmphasizedActionLayoutResource() {
5685            return R.layout.notification_material_action_emphasized;
5686        }
5687
5688        private int getActionTombstoneLayoutResource() {
5689            return R.layout.notification_material_action_tombstone;
5690        }
5691
5692        private int getBackgroundColor() {
5693            if (isColorized()) {
5694                return mBackgroundColor != COLOR_INVALID ? mBackgroundColor : mN.color;
5695            } else {
5696                return COLOR_DEFAULT;
5697            }
5698        }
5699
5700        /**
5701         * Gets a neutral color that can be used for icons or similar that should not stand out.
5702         */
5703        private int getNeutralColor() {
5704            if (isColorized()) {
5705                return getSecondaryTextColor();
5706            } else {
5707                return resolveNeutralColor();
5708            }
5709        }
5710
5711        /**
5712         * Same as getBackgroundColor but also resolved the default color to the background.
5713         */
5714        private int resolveBackgroundColor() {
5715            int backgroundColor = getBackgroundColor();
5716            if (backgroundColor == COLOR_DEFAULT) {
5717                backgroundColor = mContext.getColor(
5718                        com.android.internal.R.color.notification_material_background_color);
5719            }
5720            return backgroundColor;
5721        }
5722
5723        private boolean isColorized() {
5724            return mN.isColorized();
5725        }
5726
5727        private boolean shouldTintActionButtons() {
5728            return mTintActionButtons;
5729        }
5730
5731        private boolean textColorsNeedInversion() {
5732            if (mStyle == null || !MediaStyle.class.equals(mStyle.getClass())) {
5733                return false;
5734            }
5735            int targetSdkVersion = mContext.getApplicationInfo().targetSdkVersion;
5736            return targetSdkVersion > Build.VERSION_CODES.M
5737                    && targetSdkVersion < Build.VERSION_CODES.O;
5738        }
5739
5740        /**
5741         * Set a color palette to be used as the background and textColors
5742         *
5743         * @param backgroundColor the color to be used as the background
5744         * @param foregroundColor the color to be used as the foreground
5745         *
5746         * @hide
5747         */
5748        public void setColorPalette(int backgroundColor, int foregroundColor) {
5749            mBackgroundColor = backgroundColor;
5750            mForegroundColor = foregroundColor;
5751            mTextColorsAreForBackground = COLOR_INVALID;
5752            ensureColors();
5753        }
5754
5755        /**
5756         * Forces all styled remoteViews to be built from scratch and not use any cached
5757         * RemoteViews.
5758         * This is needed for legacy apps that are baking in their remoteviews into the
5759         * notification.
5760         *
5761         * @hide
5762         */
5763        public void setRebuildStyledRemoteViews(boolean rebuild) {
5764            mRebuildStyledRemoteViews = rebuild;
5765        }
5766
5767        /**
5768         * Get the text that should be displayed in the statusBar when heads upped. This is
5769         * usually just the app name, but may be different depending on the style.
5770         *
5771         * @param publicMode If true, return a text that is safe to display in public.
5772         *
5773         * @hide
5774         */
5775        public CharSequence getHeadsUpStatusBarText(boolean publicMode) {
5776            if (mStyle != null && !publicMode) {
5777                CharSequence text = mStyle.getHeadsUpStatusBarText();
5778                if (!TextUtils.isEmpty(text)) {
5779                    return text;
5780                }
5781            }
5782            return loadHeaderAppName();
5783        }
5784    }
5785
5786    /**
5787     * Reduces the image sizes to conform to a maximum allowed size. This also processes all custom
5788     * remote views.
5789     *
5790     * @hide
5791     */
5792    void reduceImageSizes(Context context) {
5793        if (extras.getBoolean(EXTRA_REDUCED_IMAGES)) {
5794            return;
5795        }
5796        boolean isLowRam = ActivityManager.isLowRamDeviceStatic();
5797        if (mLargeIcon != null || largeIcon != null) {
5798            Resources resources = context.getResources();
5799            Class<? extends Style> style = getNotificationStyle();
5800            int maxWidth = resources.getDimensionPixelSize(isLowRam
5801                    ? R.dimen.notification_right_icon_size_low_ram
5802                    : R.dimen.notification_right_icon_size);
5803            int maxHeight = maxWidth;
5804            if (MediaStyle.class.equals(style)
5805                    || DecoratedMediaCustomViewStyle.class.equals(style)) {
5806                maxHeight = resources.getDimensionPixelSize(isLowRam
5807                        ? R.dimen.notification_media_image_max_height_low_ram
5808                        : R.dimen.notification_media_image_max_height);
5809                maxWidth = resources.getDimensionPixelSize(isLowRam
5810                        ? R.dimen.notification_media_image_max_width_low_ram
5811                        : R.dimen.notification_media_image_max_width);
5812            }
5813            if (mLargeIcon != null) {
5814                mLargeIcon.scaleDownIfNecessary(maxWidth, maxHeight);
5815            }
5816            if (largeIcon != null) {
5817                largeIcon = Icon.scaleDownIfNecessary(largeIcon, maxWidth, maxHeight);
5818            }
5819        }
5820        reduceImageSizesForRemoteView(contentView, context, isLowRam);
5821        reduceImageSizesForRemoteView(headsUpContentView, context, isLowRam);
5822        reduceImageSizesForRemoteView(bigContentView, context, isLowRam);
5823        extras.putBoolean(EXTRA_REDUCED_IMAGES, true);
5824    }
5825
5826    private void reduceImageSizesForRemoteView(RemoteViews remoteView, Context context,
5827            boolean isLowRam) {
5828        if (remoteView != null) {
5829            Resources resources = context.getResources();
5830            int maxWidth = resources.getDimensionPixelSize(isLowRam
5831                    ? R.dimen.notification_custom_view_max_image_width_low_ram
5832                    : R.dimen.notification_custom_view_max_image_width);
5833            int maxHeight = resources.getDimensionPixelSize(isLowRam
5834                    ? R.dimen.notification_custom_view_max_image_height_low_ram
5835                    : R.dimen.notification_custom_view_max_image_height);
5836            remoteView.reduceImageSizes(maxWidth, maxHeight);
5837        }
5838    }
5839
5840    /**
5841     * @return whether this notification is a foreground service notification
5842     */
5843    private boolean isForegroundService() {
5844        return (flags & Notification.FLAG_FOREGROUND_SERVICE) != 0;
5845    }
5846
5847    /**
5848     * @return whether this notification has a media session attached
5849     * @hide
5850     */
5851    public boolean hasMediaSession() {
5852        return extras.getParcelable(Notification.EXTRA_MEDIA_SESSION) != null;
5853    }
5854
5855    /**
5856     * @return the style class of this notification
5857     * @hide
5858     */
5859    public Class<? extends Notification.Style> getNotificationStyle() {
5860        String templateClass = extras.getString(Notification.EXTRA_TEMPLATE);
5861
5862        if (!TextUtils.isEmpty(templateClass)) {
5863            return Notification.getNotificationStyleClass(templateClass);
5864        }
5865        return null;
5866    }
5867
5868    /**
5869     * @return true if this notification is colorized.
5870     *
5871     * @hide
5872     */
5873    public boolean isColorized() {
5874        if (isColorizedMedia()) {
5875            return true;
5876        }
5877        return extras.getBoolean(EXTRA_COLORIZED)
5878                && (hasColorizedPermission() || isForegroundService());
5879    }
5880
5881    /**
5882     * Returns whether an app can colorize due to the android.permission.USE_COLORIZED_NOTIFICATIONS
5883     * permission. The permission is checked when a notification is enqueued.
5884     */
5885    private boolean hasColorizedPermission() {
5886        return (flags & Notification.FLAG_CAN_COLORIZE) != 0;
5887    }
5888
5889    /**
5890     * @return true if this notification is colorized and it is a media notification
5891     *
5892     * @hide
5893     */
5894    public boolean isColorizedMedia() {
5895        Class<? extends Style> style = getNotificationStyle();
5896        if (MediaStyle.class.equals(style)) {
5897            Boolean colorized = (Boolean) extras.get(EXTRA_COLORIZED);
5898            if ((colorized == null || colorized) && hasMediaSession()) {
5899                return true;
5900            }
5901        } else if (DecoratedMediaCustomViewStyle.class.equals(style)) {
5902            if (extras.getBoolean(EXTRA_COLORIZED) && hasMediaSession()) {
5903                return true;
5904            }
5905        }
5906        return false;
5907    }
5908
5909
5910    /**
5911     * @return true if this is a media notification
5912     *
5913     * @hide
5914     */
5915    public boolean isMediaNotification() {
5916        Class<? extends Style> style = getNotificationStyle();
5917        if (MediaStyle.class.equals(style)) {
5918            return true;
5919        } else if (DecoratedMediaCustomViewStyle.class.equals(style)) {
5920            return true;
5921        }
5922        return false;
5923    }
5924
5925    private boolean hasLargeIcon() {
5926        return mLargeIcon != null || largeIcon != null;
5927    }
5928
5929    /**
5930     * @return true if the notification will show the time; false otherwise
5931     * @hide
5932     */
5933    public boolean showsTime() {
5934        return when != 0 && extras.getBoolean(EXTRA_SHOW_WHEN);
5935    }
5936
5937    /**
5938     * @return true if the notification will show a chronometer; false otherwise
5939     * @hide
5940     */
5941    public boolean showsChronometer() {
5942        return when != 0 && extras.getBoolean(EXTRA_SHOW_CHRONOMETER);
5943    }
5944
5945    /**
5946     * @removed
5947     */
5948    @SystemApi
5949    public static Class<? extends Style> getNotificationStyleClass(String templateClass) {
5950        Class<? extends Style>[] classes = new Class[] {
5951                BigTextStyle.class, BigPictureStyle.class, InboxStyle.class, MediaStyle.class,
5952                DecoratedCustomViewStyle.class, DecoratedMediaCustomViewStyle.class,
5953                MessagingStyle.class };
5954        for (Class<? extends Style> innerClass : classes) {
5955            if (templateClass.equals(innerClass.getName())) {
5956                return innerClass;
5957            }
5958        }
5959        return null;
5960    }
5961
5962    /**
5963     * An object that can apply a rich notification style to a {@link Notification.Builder}
5964     * object.
5965     */
5966    public static abstract class Style {
5967
5968        /**
5969         * The number of items allowed simulatanously in the remote input history.
5970         * @hide
5971         */
5972        static final int MAX_REMOTE_INPUT_HISTORY_LINES = 3;
5973        private CharSequence mBigContentTitle;
5974
5975        /**
5976         * @hide
5977         */
5978        protected CharSequence mSummaryText = null;
5979
5980        /**
5981         * @hide
5982         */
5983        protected boolean mSummaryTextSet = false;
5984
5985        protected Builder mBuilder;
5986
5987        /**
5988         * Overrides ContentTitle in the big form of the template.
5989         * This defaults to the value passed to setContentTitle().
5990         */
5991        protected void internalSetBigContentTitle(CharSequence title) {
5992            mBigContentTitle = title;
5993        }
5994
5995        /**
5996         * Set the first line of text after the detail section in the big form of the template.
5997         */
5998        protected void internalSetSummaryText(CharSequence cs) {
5999            mSummaryText = cs;
6000            mSummaryTextSet = true;
6001        }
6002
6003        public void setBuilder(Builder builder) {
6004            if (mBuilder != builder) {
6005                mBuilder = builder;
6006                if (mBuilder != null) {
6007                    mBuilder.setStyle(this);
6008                }
6009            }
6010        }
6011
6012        protected void checkBuilder() {
6013            if (mBuilder == null) {
6014                throw new IllegalArgumentException("Style requires a valid Builder object");
6015            }
6016        }
6017
6018        protected RemoteViews getStandardView(int layoutId) {
6019            return getStandardView(layoutId, null);
6020        }
6021
6022        /**
6023         * Get the standard view for this style.
6024         *
6025         * @param layoutId The layout id to use
6026         * @param result The result where template bind information is saved.
6027         * @return A remoteView for this style.
6028         * @hide
6029         */
6030        protected RemoteViews getStandardView(int layoutId, TemplateBindResult result) {
6031            checkBuilder();
6032
6033            // Nasty.
6034            CharSequence oldBuilderContentTitle =
6035                    mBuilder.getAllExtras().getCharSequence(EXTRA_TITLE);
6036            if (mBigContentTitle != null) {
6037                mBuilder.setContentTitle(mBigContentTitle);
6038            }
6039
6040            RemoteViews contentView = mBuilder.applyStandardTemplateWithActions(layoutId, result);
6041
6042            mBuilder.getAllExtras().putCharSequence(EXTRA_TITLE, oldBuilderContentTitle);
6043
6044            if (mBigContentTitle != null && mBigContentTitle.equals("")) {
6045                contentView.setViewVisibility(R.id.line1, View.GONE);
6046            } else {
6047                contentView.setViewVisibility(R.id.line1, View.VISIBLE);
6048            }
6049
6050            return contentView;
6051        }
6052
6053        /**
6054         * Construct a Style-specific RemoteViews for the collapsed notification layout.
6055         * The default implementation has nothing additional to add.
6056         *
6057         * @param increasedHeight true if this layout be created with an increased height.
6058         * @hide
6059         */
6060        public RemoteViews makeContentView(boolean increasedHeight) {
6061            return null;
6062        }
6063
6064        /**
6065         * Construct a Style-specific RemoteViews for the final big notification layout.
6066         * @hide
6067         */
6068        public RemoteViews makeBigContentView() {
6069            return null;
6070        }
6071
6072        /**
6073         * Construct a Style-specific RemoteViews for the final HUN layout.
6074         *
6075         * @param increasedHeight true if this layout be created with an increased height.
6076         * @hide
6077         */
6078        public RemoteViews makeHeadsUpContentView(boolean increasedHeight) {
6079            return null;
6080        }
6081
6082        /**
6083         * Apply any style-specific extras to this notification before shipping it out.
6084         * @hide
6085         */
6086        public void addExtras(Bundle extras) {
6087            if (mSummaryTextSet) {
6088                extras.putCharSequence(EXTRA_SUMMARY_TEXT, mSummaryText);
6089            }
6090            if (mBigContentTitle != null) {
6091                extras.putCharSequence(EXTRA_TITLE_BIG, mBigContentTitle);
6092            }
6093            extras.putString(EXTRA_TEMPLATE, this.getClass().getName());
6094        }
6095
6096        /**
6097         * Reconstruct the internal state of this Style object from extras.
6098         * @hide
6099         */
6100        protected void restoreFromExtras(Bundle extras) {
6101            if (extras.containsKey(EXTRA_SUMMARY_TEXT)) {
6102                mSummaryText = extras.getCharSequence(EXTRA_SUMMARY_TEXT);
6103                mSummaryTextSet = true;
6104            }
6105            if (extras.containsKey(EXTRA_TITLE_BIG)) {
6106                mBigContentTitle = extras.getCharSequence(EXTRA_TITLE_BIG);
6107            }
6108        }
6109
6110
6111        /**
6112         * @hide
6113         */
6114        public Notification buildStyled(Notification wip) {
6115            addExtras(wip.extras);
6116            return wip;
6117        }
6118
6119        /**
6120         * @hide
6121         */
6122        public void purgeResources() {}
6123
6124        /**
6125         * Calls {@link android.app.Notification.Builder#build()} on the Builder this Style is
6126         * attached to.
6127         *
6128         * @return the fully constructed Notification.
6129         */
6130        public Notification build() {
6131            checkBuilder();
6132            return mBuilder.build();
6133        }
6134
6135        /**
6136         * @hide
6137         * @return true if the style positions the progress bar on the second line; false if the
6138         *         style hides the progress bar
6139         */
6140        protected boolean hasProgress() {
6141            return true;
6142        }
6143
6144        /**
6145         * @hide
6146         * @return Whether we should put the summary be put into the notification header
6147         */
6148        public boolean hasSummaryInHeader() {
6149            return true;
6150        }
6151
6152        /**
6153         * @hide
6154         * @return Whether custom content views are displayed inline in the style
6155         */
6156        public boolean displayCustomViewInline() {
6157            return false;
6158        }
6159
6160        /**
6161         * Reduces the image sizes contained in this style.
6162         *
6163         * @hide
6164         */
6165        public void reduceImageSizes(Context context) {
6166        }
6167
6168        /**
6169         * Validate that this style was properly composed. This is called at build time.
6170         * @hide
6171         */
6172        public void validate(Context context) {
6173        }
6174
6175        /**
6176         * @hide
6177         */
6178        public abstract boolean areNotificationsVisiblyDifferent(Style other);
6179
6180        /**
6181         * @return the the text that should be displayed in the statusBar when heads-upped.
6182         * If {@code null} is returned, the default implementation will be used.
6183         *
6184         * @hide
6185         */
6186        public CharSequence getHeadsUpStatusBarText() {
6187            return null;
6188        }
6189    }
6190
6191    /**
6192     * Helper class for generating large-format notifications that include a large image attachment.
6193     *
6194     * Here's how you'd set the <code>BigPictureStyle</code> on a notification:
6195     * <pre class="prettyprint">
6196     * Notification notif = new Notification.Builder(mContext)
6197     *     .setContentTitle(&quot;New photo from &quot; + sender.toString())
6198     *     .setContentText(subject)
6199     *     .setSmallIcon(R.drawable.new_post)
6200     *     .setLargeIcon(aBitmap)
6201     *     .setStyle(new Notification.BigPictureStyle()
6202     *         .bigPicture(aBigBitmap))
6203     *     .build();
6204     * </pre>
6205     *
6206     * @see Notification#bigContentView
6207     */
6208    public static class BigPictureStyle extends Style {
6209        private Bitmap mPicture;
6210        private Icon mBigLargeIcon;
6211        private boolean mBigLargeIconSet = false;
6212
6213        public BigPictureStyle() {
6214        }
6215
6216        /**
6217         * @deprecated use {@code BigPictureStyle()}.
6218         */
6219        @Deprecated
6220        public BigPictureStyle(Builder builder) {
6221            setBuilder(builder);
6222        }
6223
6224        /**
6225         * Overrides ContentTitle in the big form of the template.
6226         * This defaults to the value passed to setContentTitle().
6227         */
6228        public BigPictureStyle setBigContentTitle(CharSequence title) {
6229            internalSetBigContentTitle(safeCharSequence(title));
6230            return this;
6231        }
6232
6233        /**
6234         * Set the first line of text after the detail section in the big form of the template.
6235         */
6236        public BigPictureStyle setSummaryText(CharSequence cs) {
6237            internalSetSummaryText(safeCharSequence(cs));
6238            return this;
6239        }
6240
6241        /**
6242         * @hide
6243         */
6244        public Bitmap getBigPicture() {
6245            return mPicture;
6246        }
6247
6248        /**
6249         * Provide the bitmap to be used as the payload for the BigPicture notification.
6250         */
6251        public BigPictureStyle bigPicture(Bitmap b) {
6252            mPicture = b;
6253            return this;
6254        }
6255
6256        /**
6257         * Override the large icon when the big notification is shown.
6258         */
6259        public BigPictureStyle bigLargeIcon(Bitmap b) {
6260            return bigLargeIcon(b != null ? Icon.createWithBitmap(b) : null);
6261        }
6262
6263        /**
6264         * Override the large icon when the big notification is shown.
6265         */
6266        public BigPictureStyle bigLargeIcon(Icon icon) {
6267            mBigLargeIconSet = true;
6268            mBigLargeIcon = icon;
6269            return this;
6270        }
6271
6272        /** @hide */
6273        public static final int MIN_ASHMEM_BITMAP_SIZE = 128 * (1 << 10);
6274
6275        /**
6276         * @hide
6277         */
6278        @Override
6279        public void purgeResources() {
6280            super.purgeResources();
6281            if (mPicture != null &&
6282                mPicture.isMutable() &&
6283                mPicture.getAllocationByteCount() >= MIN_ASHMEM_BITMAP_SIZE) {
6284                mPicture = mPicture.createAshmemBitmap();
6285            }
6286            if (mBigLargeIcon != null) {
6287                mBigLargeIcon.convertToAshmem();
6288            }
6289        }
6290
6291        /**
6292         * @hide
6293         */
6294        @Override
6295        public void reduceImageSizes(Context context) {
6296            super.reduceImageSizes(context);
6297            Resources resources = context.getResources();
6298            boolean isLowRam = ActivityManager.isLowRamDeviceStatic();
6299            if (mPicture != null) {
6300                int maxPictureWidth = resources.getDimensionPixelSize(isLowRam
6301                        ? R.dimen.notification_big_picture_max_height_low_ram
6302                        : R.dimen.notification_big_picture_max_height);
6303                int maxPictureHeight = resources.getDimensionPixelSize(isLowRam
6304                        ? R.dimen.notification_big_picture_max_width_low_ram
6305                        : R.dimen.notification_big_picture_max_width);
6306                mPicture = Icon.scaleDownIfNecessary(mPicture, maxPictureWidth, maxPictureHeight);
6307            }
6308            if (mBigLargeIcon != null) {
6309                int rightIconSize = resources.getDimensionPixelSize(isLowRam
6310                        ? R.dimen.notification_right_icon_size_low_ram
6311                        : R.dimen.notification_right_icon_size);
6312                mBigLargeIcon.scaleDownIfNecessary(rightIconSize, rightIconSize);
6313            }
6314        }
6315
6316        /**
6317         * @hide
6318         */
6319        public RemoteViews makeBigContentView() {
6320            // Replace mN.mLargeIcon with mBigLargeIcon if mBigLargeIconSet
6321            // This covers the following cases:
6322            //   1. mBigLargeIconSet -> mBigLargeIcon (null or non-null) applies, overrides
6323            //          mN.mLargeIcon
6324            //   2. !mBigLargeIconSet -> mN.mLargeIcon applies
6325            Icon oldLargeIcon = null;
6326            Bitmap largeIconLegacy = null;
6327            if (mBigLargeIconSet) {
6328                oldLargeIcon = mBuilder.mN.mLargeIcon;
6329                mBuilder.mN.mLargeIcon = mBigLargeIcon;
6330                // The legacy largeIcon might not allow us to clear the image, as it's taken in
6331                // replacement if the other one is null. Because we're restoring these legacy icons
6332                // for old listeners, this is in general non-null.
6333                largeIconLegacy = mBuilder.mN.largeIcon;
6334                mBuilder.mN.largeIcon = null;
6335            }
6336
6337            RemoteViews contentView = getStandardView(mBuilder.getBigPictureLayoutResource(),
6338                    null /* result */);
6339            if (mSummaryTextSet) {
6340                contentView.setTextViewText(R.id.text, mBuilder.processTextSpans(
6341                        mBuilder.processLegacyText(mSummaryText)));
6342                mBuilder.setTextViewColorSecondary(contentView, R.id.text);
6343                contentView.setViewVisibility(R.id.text, View.VISIBLE);
6344            }
6345            mBuilder.setContentMinHeight(contentView, mBuilder.mN.hasLargeIcon());
6346
6347            if (mBigLargeIconSet) {
6348                mBuilder.mN.mLargeIcon = oldLargeIcon;
6349                mBuilder.mN.largeIcon = largeIconLegacy;
6350            }
6351
6352            contentView.setImageViewBitmap(R.id.big_picture, mPicture);
6353            return contentView;
6354        }
6355
6356        /**
6357         * @hide
6358         */
6359        public void addExtras(Bundle extras) {
6360            super.addExtras(extras);
6361
6362            if (mBigLargeIconSet) {
6363                extras.putParcelable(EXTRA_LARGE_ICON_BIG, mBigLargeIcon);
6364            }
6365            extras.putParcelable(EXTRA_PICTURE, mPicture);
6366        }
6367
6368        /**
6369         * @hide
6370         */
6371        @Override
6372        protected void restoreFromExtras(Bundle extras) {
6373            super.restoreFromExtras(extras);
6374
6375            if (extras.containsKey(EXTRA_LARGE_ICON_BIG)) {
6376                mBigLargeIconSet = true;
6377                mBigLargeIcon = extras.getParcelable(EXTRA_LARGE_ICON_BIG);
6378            }
6379            mPicture = extras.getParcelable(EXTRA_PICTURE);
6380        }
6381
6382        /**
6383         * @hide
6384         */
6385        @Override
6386        public boolean hasSummaryInHeader() {
6387            return false;
6388        }
6389
6390        /**
6391         * @hide
6392         * Note that we aren't actually comparing the contents of the bitmaps here, so this
6393         * is only doing a cursory inspection. Bitmaps of equal size will appear the same.
6394         */
6395        @Override
6396        public boolean areNotificationsVisiblyDifferent(Style other) {
6397            if (other == null || getClass() != other.getClass()) {
6398                return true;
6399            }
6400            BigPictureStyle otherS = (BigPictureStyle) other;
6401            return areBitmapsObviouslyDifferent(getBigPicture(), otherS.getBigPicture());
6402        }
6403
6404        private static boolean areBitmapsObviouslyDifferent(Bitmap a, Bitmap b) {
6405            if (a == b) {
6406                return false;
6407            }
6408            if (a == null || b == null) {
6409                return true;
6410            }
6411            return a.getWidth() != b.getWidth()
6412                    || a.getHeight() != b.getHeight()
6413                    || a.getConfig() != b.getConfig()
6414                    || a.getGenerationId() != b.getGenerationId();
6415        }
6416    }
6417
6418    /**
6419     * Helper class for generating large-format notifications that include a lot of text.
6420     *
6421     * Here's how you'd set the <code>BigTextStyle</code> on a notification:
6422     * <pre class="prettyprint">
6423     * Notification notif = new Notification.Builder(mContext)
6424     *     .setContentTitle(&quot;New mail from &quot; + sender.toString())
6425     *     .setContentText(subject)
6426     *     .setSmallIcon(R.drawable.new_mail)
6427     *     .setLargeIcon(aBitmap)
6428     *     .setStyle(new Notification.BigTextStyle()
6429     *         .bigText(aVeryLongString))
6430     *     .build();
6431     * </pre>
6432     *
6433     * @see Notification#bigContentView
6434     */
6435    public static class BigTextStyle extends Style {
6436
6437        private CharSequence mBigText;
6438
6439        public BigTextStyle() {
6440        }
6441
6442        /**
6443         * @deprecated use {@code BigTextStyle()}.
6444         */
6445        @Deprecated
6446        public BigTextStyle(Builder builder) {
6447            setBuilder(builder);
6448        }
6449
6450        /**
6451         * Overrides ContentTitle in the big form of the template.
6452         * This defaults to the value passed to setContentTitle().
6453         */
6454        public BigTextStyle setBigContentTitle(CharSequence title) {
6455            internalSetBigContentTitle(safeCharSequence(title));
6456            return this;
6457        }
6458
6459        /**
6460         * Set the first line of text after the detail section in the big form of the template.
6461         */
6462        public BigTextStyle setSummaryText(CharSequence cs) {
6463            internalSetSummaryText(safeCharSequence(cs));
6464            return this;
6465        }
6466
6467        /**
6468         * Provide the longer text to be displayed in the big form of the
6469         * template in place of the content text.
6470         */
6471        public BigTextStyle bigText(CharSequence cs) {
6472            mBigText = safeCharSequence(cs);
6473            return this;
6474        }
6475
6476        /**
6477         * @hide
6478         */
6479        public CharSequence getBigText() {
6480            return mBigText;
6481        }
6482
6483        /**
6484         * @hide
6485         */
6486        public void addExtras(Bundle extras) {
6487            super.addExtras(extras);
6488
6489            extras.putCharSequence(EXTRA_BIG_TEXT, mBigText);
6490        }
6491
6492        /**
6493         * @hide
6494         */
6495        @Override
6496        protected void restoreFromExtras(Bundle extras) {
6497            super.restoreFromExtras(extras);
6498
6499            mBigText = extras.getCharSequence(EXTRA_BIG_TEXT);
6500        }
6501
6502        /**
6503         * @param increasedHeight true if this layout be created with an increased height.
6504         *
6505         * @hide
6506         */
6507        @Override
6508        public RemoteViews makeContentView(boolean increasedHeight) {
6509            if (increasedHeight) {
6510                mBuilder.mOriginalActions = mBuilder.mActions;
6511                mBuilder.mActions = new ArrayList<>();
6512                RemoteViews remoteViews = makeBigContentView();
6513                mBuilder.mActions = mBuilder.mOriginalActions;
6514                mBuilder.mOriginalActions = null;
6515                return remoteViews;
6516            }
6517            return super.makeContentView(increasedHeight);
6518        }
6519
6520        /**
6521         * @hide
6522         */
6523        @Override
6524        public RemoteViews makeHeadsUpContentView(boolean increasedHeight) {
6525            if (increasedHeight && mBuilder.mActions.size() > 0) {
6526                return makeBigContentView();
6527            }
6528            return super.makeHeadsUpContentView(increasedHeight);
6529        }
6530
6531        /**
6532         * @hide
6533         */
6534        public RemoteViews makeBigContentView() {
6535
6536            // Nasty
6537            CharSequence text = mBuilder.getAllExtras().getCharSequence(EXTRA_TEXT);
6538            mBuilder.getAllExtras().putCharSequence(EXTRA_TEXT, null);
6539
6540            TemplateBindResult result = new TemplateBindResult();
6541            RemoteViews contentView = getStandardView(mBuilder.getBigTextLayoutResource(), result);
6542            contentView.setInt(R.id.big_text, "setImageEndMargin", result.getIconMarginEnd());
6543
6544            mBuilder.getAllExtras().putCharSequence(EXTRA_TEXT, text);
6545
6546            CharSequence bigTextText = mBuilder.processLegacyText(mBigText);
6547            if (TextUtils.isEmpty(bigTextText)) {
6548                // In case the bigtext is null / empty fall back to the normal text to avoid a weird
6549                // experience
6550                bigTextText = mBuilder.processLegacyText(text);
6551            }
6552            applyBigTextContentView(mBuilder, contentView, bigTextText);
6553
6554            return contentView;
6555        }
6556
6557        /**
6558         * @hide
6559         * Spans are ignored when comparing text for visual difference.
6560         */
6561        @Override
6562        public boolean areNotificationsVisiblyDifferent(Style other) {
6563            if (other == null || getClass() != other.getClass()) {
6564                return true;
6565            }
6566            BigTextStyle newS = (BigTextStyle) other;
6567            return !Objects.equals(String.valueOf(getBigText()), String.valueOf(newS.getBigText()));
6568        }
6569
6570        static void applyBigTextContentView(Builder builder,
6571                RemoteViews contentView, CharSequence bigTextText) {
6572            contentView.setTextViewText(R.id.big_text, builder.processTextSpans(bigTextText));
6573            builder.setTextViewColorSecondary(contentView, R.id.big_text);
6574            contentView.setViewVisibility(R.id.big_text,
6575                    TextUtils.isEmpty(bigTextText) ? View.GONE : View.VISIBLE);
6576            contentView.setBoolean(R.id.big_text, "setHasImage", builder.mN.hasLargeIcon());
6577        }
6578    }
6579
6580    /**
6581     * Helper class for generating large-format notifications that include multiple back-and-forth
6582     * messages of varying types between any number of people.
6583     *
6584     * <br>
6585     * If the platform does not provide large-format notifications, this method has no effect. The
6586     * user will always see the normal notification view.
6587     * <br>
6588     * This class is a "rebuilder": It attaches to a Builder object and modifies its behavior, like
6589     * so:
6590     * <pre class="prettyprint">
6591     *
6592     * Notification noti = new Notification.Builder()
6593     *     .setContentTitle(&quot;2 new messages wtih &quot; + sender.toString())
6594     *     .setContentText(subject)
6595     *     .setSmallIcon(R.drawable.new_message)
6596     *     .setLargeIcon(aBitmap)
6597     *     .setStyle(new Notification.MessagingStyle(resources.getString(R.string.reply_name))
6598     *         .addMessage(messages[0].getText(), messages[0].getTime(), messages[0].getSender())
6599     *         .addMessage(messages[1].getText(), messages[1].getTime(), messages[1].getSender()))
6600     *     .build();
6601     * </pre>
6602     */
6603    public static class MessagingStyle extends Style {
6604
6605        /**
6606         * The maximum number of messages that will be retained in the Notification itself (the
6607         * number displayed is up to the platform).
6608         */
6609        public static final int MAXIMUM_RETAINED_MESSAGES = 25;
6610
6611        @NonNull Person mUser;
6612        @Nullable CharSequence mConversationTitle;
6613        List<Message> mMessages = new ArrayList<>();
6614        List<Message> mHistoricMessages = new ArrayList<>();
6615        boolean mIsGroupConversation;
6616
6617        MessagingStyle() {
6618        }
6619
6620        /**
6621         * @param userDisplayName Required - the name to be displayed for any replies sent by the
6622         * user before the posting app reposts the notification with those messages after they've
6623         * been actually sent and in previous messages sent by the user added in
6624         * {@link #addMessage(Notification.MessagingStyle.Message)}
6625         *
6626         * @deprecated use {@code MessagingStyle(Person)}
6627         */
6628        public MessagingStyle(@NonNull CharSequence userDisplayName) {
6629            this(new Person.Builder().setName(userDisplayName).build());
6630        }
6631
6632        /**
6633         * @param user Required - The person displayed for any messages that are sent by the
6634         * user. Any messages added with {@link #addMessage(Notification.MessagingStyle.Message)}
6635         * who don't have a Person associated with it will be displayed as if they were sent
6636         * by this user. The user also needs to have a valid name associated with it, which will
6637         * be enforced starting in Android P.
6638         */
6639        public MessagingStyle(@NonNull Person user) {
6640            mUser = user;
6641        }
6642
6643        /**
6644         * Validate that this style was properly composed. This is called at build time.
6645         * @hide
6646         */
6647        @Override
6648        public void validate(Context context) {
6649            super.validate(context);
6650            if (context.getApplicationInfo().targetSdkVersion
6651                    >= Build.VERSION_CODES.P && (mUser == null || mUser.getName() == null)) {
6652                throw new RuntimeException("User must be valid and have a name.");
6653            }
6654        }
6655
6656        /**
6657         * @return the the text that should be displayed in the statusBar when heads upped.
6658         * If {@code null} is returned, the default implementation will be used.
6659         *
6660         * @hide
6661         */
6662        @Override
6663        public CharSequence getHeadsUpStatusBarText() {
6664            CharSequence conversationTitle = !TextUtils.isEmpty(super.mBigContentTitle)
6665                    ? super.mBigContentTitle
6666                    : mConversationTitle;
6667            if (!TextUtils.isEmpty(conversationTitle) && !hasOnlyWhiteSpaceSenders()) {
6668                return conversationTitle;
6669            }
6670            return null;
6671        }
6672
6673        /**
6674         * @return the user to be displayed for any replies sent by the user
6675         */
6676        @NonNull
6677        public Person getUser() {
6678            return mUser;
6679        }
6680
6681        /**
6682         * Returns the name to be displayed for any replies sent by the user
6683         *
6684         * @deprecated use {@link #getUser()} instead
6685         */
6686        public CharSequence getUserDisplayName() {
6687            return mUser.getName();
6688        }
6689
6690        /**
6691         * Sets the title to be displayed on this conversation. May be set to {@code null}.
6692         *
6693         * <p>This API's behavior was changed in SDK version {@link Build.VERSION_CODES#P}. If your
6694         * application's target version is less than {@link Build.VERSION_CODES#P}, setting a
6695         * conversation title to a non-null value will make {@link #isGroupConversation()} return
6696         * {@code true} and passing {@code null} will make it return {@code false}. In
6697         * {@link Build.VERSION_CODES#P} and beyond, use {@link #setGroupConversation(boolean)}
6698         * to set group conversation status.
6699         *
6700         * @param conversationTitle Title displayed for this conversation
6701         * @return this object for method chaining
6702         */
6703        public MessagingStyle setConversationTitle(@Nullable CharSequence conversationTitle) {
6704            mConversationTitle = conversationTitle;
6705            return this;
6706        }
6707
6708        /**
6709         * Return the title to be displayed on this conversation. May return {@code null}.
6710         */
6711        @Nullable
6712        public CharSequence getConversationTitle() {
6713            return mConversationTitle;
6714        }
6715
6716        /**
6717         * Adds a message for display by this notification. Convenience call for a simple
6718         * {@link Message} in {@link #addMessage(Notification.MessagingStyle.Message)}.
6719         * @param text A {@link CharSequence} to be displayed as the message content
6720         * @param timestamp Time at which the message arrived
6721         * @param sender A {@link CharSequence} to be used for displaying the name of the
6722         * sender. Should be <code>null</code> for messages by the current user, in which case
6723         * the platform will insert {@link #getUserDisplayName()}.
6724         * Should be unique amongst all individuals in the conversation, and should be
6725         * consistent during re-posts of the notification.
6726         *
6727         * @see Message#Message(CharSequence, long, CharSequence)
6728         *
6729         * @return this object for method chaining
6730         *
6731         * @deprecated use {@link #addMessage(CharSequence, long, Person)}
6732         */
6733        public MessagingStyle addMessage(CharSequence text, long timestamp, CharSequence sender) {
6734            return addMessage(text, timestamp,
6735                    sender == null ? null : new Person.Builder().setName(sender).build());
6736        }
6737
6738        /**
6739         * Adds a message for display by this notification. Convenience call for a simple
6740         * {@link Message} in {@link #addMessage(Notification.MessagingStyle.Message)}.
6741         * @param text A {@link CharSequence} to be displayed as the message content
6742         * @param timestamp Time at which the message arrived
6743         * @param sender The {@link Person} who sent the message.
6744         * Should be <code>null</code> for messages by the current user, in which case
6745         * the platform will insert the user set in {@code MessagingStyle(Person)}.
6746         *
6747         * @see Message#Message(CharSequence, long, CharSequence)
6748         *
6749         * @return this object for method chaining
6750         */
6751        public MessagingStyle addMessage(@NonNull CharSequence text, long timestamp,
6752                @Nullable Person sender) {
6753            return addMessage(new Message(text, timestamp, sender));
6754        }
6755
6756        /**
6757         * Adds a {@link Message} for display in this notification.
6758         *
6759         * <p>The messages should be added in chronologic order, i.e. the oldest first,
6760         * the newest last.
6761         *
6762         * @param message The {@link Message} to be displayed
6763         * @return this object for method chaining
6764         */
6765        public MessagingStyle addMessage(Message message) {
6766            mMessages.add(message);
6767            if (mMessages.size() > MAXIMUM_RETAINED_MESSAGES) {
6768                mMessages.remove(0);
6769            }
6770            return this;
6771        }
6772
6773        /**
6774         * Adds a {@link Message} for historic context in this notification.
6775         *
6776         * <p>Messages should be added as historic if they are not the main subject of the
6777         * notification but may give context to a conversation. The system may choose to present
6778         * them only when relevant, e.g. when replying to a message through a {@link RemoteInput}.
6779         *
6780         * <p>The messages should be added in chronologic order, i.e. the oldest first,
6781         * the newest last.
6782         *
6783         * @param message The historic {@link Message} to be added
6784         * @return this object for method chaining
6785         */
6786        public MessagingStyle addHistoricMessage(Message message) {
6787            mHistoricMessages.add(message);
6788            if (mHistoricMessages.size() > MAXIMUM_RETAINED_MESSAGES) {
6789                mHistoricMessages.remove(0);
6790            }
6791            return this;
6792        }
6793
6794        /**
6795         * Gets the list of {@code Message} objects that represent the notification
6796         */
6797        public List<Message> getMessages() {
6798            return mMessages;
6799        }
6800
6801        /**
6802         * Gets the list of historic {@code Message}s in the notification.
6803         */
6804        public List<Message> getHistoricMessages() {
6805            return mHistoricMessages;
6806        }
6807
6808        /**
6809         * Sets whether this conversation notification represents a group.
6810         *
6811         * @param isGroupConversation {@code true} if the conversation represents a group,
6812         * {@code false} otherwise.
6813         * @return this object for method chaining
6814         */
6815        public MessagingStyle setGroupConversation(boolean isGroupConversation) {
6816            mIsGroupConversation = isGroupConversation;
6817            return this;
6818        }
6819
6820        /**
6821         * Returns {@code true} if this notification represents a group conversation, otherwise
6822         * {@code false}.
6823         *
6824         * <p> If the application that generated this {@link MessagingStyle} targets an SDK version
6825         * less than {@link Build.VERSION_CODES#P}, this method becomes dependent on whether or
6826         * not the conversation title is set; returning {@code true} if the conversation title is
6827         * a non-null value, or {@code false} otherwise. From {@link Build.VERSION_CODES#P} forward,
6828         * this method returns what's set by {@link #setGroupConversation(boolean)} allowing for
6829         * named, non-group conversations.
6830         *
6831         * @see #setConversationTitle(CharSequence)
6832         */
6833        public boolean isGroupConversation() {
6834            // When target SDK version is < P, a non-null conversation title dictates if this is
6835            // as group conversation.
6836            if (mBuilder != null
6837                    && mBuilder.mContext.getApplicationInfo().targetSdkVersion
6838                            < Build.VERSION_CODES.P) {
6839                return mConversationTitle != null;
6840            }
6841
6842            return mIsGroupConversation;
6843        }
6844
6845        /**
6846         * @hide
6847         */
6848        @Override
6849        public void addExtras(Bundle extras) {
6850            super.addExtras(extras);
6851            if (mUser != null) {
6852                // For legacy usages
6853                extras.putCharSequence(EXTRA_SELF_DISPLAY_NAME, mUser.getName());
6854                extras.putParcelable(EXTRA_MESSAGING_PERSON, mUser);
6855            }
6856            if (mConversationTitle != null) {
6857                extras.putCharSequence(EXTRA_CONVERSATION_TITLE, mConversationTitle);
6858            }
6859            if (!mMessages.isEmpty()) { extras.putParcelableArray(EXTRA_MESSAGES,
6860                    Message.getBundleArrayForMessages(mMessages));
6861            }
6862            if (!mHistoricMessages.isEmpty()) { extras.putParcelableArray(EXTRA_HISTORIC_MESSAGES,
6863                    Message.getBundleArrayForMessages(mHistoricMessages));
6864            }
6865
6866            fixTitleAndTextExtras(extras);
6867            extras.putBoolean(EXTRA_IS_GROUP_CONVERSATION, mIsGroupConversation);
6868        }
6869
6870        private void fixTitleAndTextExtras(Bundle extras) {
6871            Message m = findLatestIncomingMessage();
6872            CharSequence text = (m == null) ? null : m.mText;
6873            CharSequence sender = m == null ? null
6874                    : m.mSender == null || TextUtils.isEmpty(m.mSender.getName())
6875                            ? mUser.getName() : m.mSender.getName();
6876            CharSequence title;
6877            if (!TextUtils.isEmpty(mConversationTitle)) {
6878                if (!TextUtils.isEmpty(sender)) {
6879                    BidiFormatter bidi = BidiFormatter.getInstance();
6880                    title = mBuilder.mContext.getString(
6881                            com.android.internal.R.string.notification_messaging_title_template,
6882                            bidi.unicodeWrap(mConversationTitle), bidi.unicodeWrap(sender));
6883                } else {
6884                    title = mConversationTitle;
6885                }
6886            } else {
6887                title = sender;
6888            }
6889
6890            if (title != null) {
6891                extras.putCharSequence(EXTRA_TITLE, title);
6892            }
6893            if (text != null) {
6894                extras.putCharSequence(EXTRA_TEXT, text);
6895            }
6896        }
6897
6898        /**
6899         * @hide
6900         */
6901        @Override
6902        protected void restoreFromExtras(Bundle extras) {
6903            super.restoreFromExtras(extras);
6904
6905            mUser = extras.getParcelable(EXTRA_MESSAGING_PERSON);
6906            if (mUser == null) {
6907                CharSequence displayName = extras.getCharSequence(EXTRA_SELF_DISPLAY_NAME);
6908                mUser = new Person.Builder().setName(displayName).build();
6909            }
6910            mConversationTitle = extras.getCharSequence(EXTRA_CONVERSATION_TITLE);
6911            Parcelable[] messages = extras.getParcelableArray(EXTRA_MESSAGES);
6912            mMessages = Message.getMessagesFromBundleArray(messages);
6913            Parcelable[] histMessages = extras.getParcelableArray(EXTRA_HISTORIC_MESSAGES);
6914            mHistoricMessages = Message.getMessagesFromBundleArray(histMessages);
6915            mIsGroupConversation = extras.getBoolean(EXTRA_IS_GROUP_CONVERSATION);
6916        }
6917
6918        /**
6919         * @hide
6920         */
6921        @Override
6922        public RemoteViews makeContentView(boolean increasedHeight) {
6923            mBuilder.mOriginalActions = mBuilder.mActions;
6924            mBuilder.mActions = new ArrayList<>();
6925            RemoteViews remoteViews = makeMessagingView(true /* displayImagesAtEnd */,
6926                    false /* hideLargeIcon */);
6927            mBuilder.mActions = mBuilder.mOriginalActions;
6928            mBuilder.mOriginalActions = null;
6929            return remoteViews;
6930        }
6931
6932        /**
6933         * @hide
6934         * Spans are ignored when comparing text for visual difference.
6935         */
6936        @Override
6937        public boolean areNotificationsVisiblyDifferent(Style other) {
6938            if (other == null || getClass() != other.getClass()) {
6939                return true;
6940            }
6941            MessagingStyle newS = (MessagingStyle) other;
6942            List<MessagingStyle.Message> oldMs = getMessages();
6943            List<MessagingStyle.Message> newMs = newS.getMessages();
6944
6945            if (oldMs == null || newMs == null) {
6946                newMs = new ArrayList<>();
6947            }
6948
6949            int n = oldMs.size();
6950            if (n != newMs.size()) {
6951                return true;
6952            }
6953            for (int i = 0; i < n; i++) {
6954                MessagingStyle.Message oldM = oldMs.get(i);
6955                MessagingStyle.Message newM = newMs.get(i);
6956                if (!Objects.equals(
6957                        String.valueOf(oldM.getText()),
6958                        String.valueOf(newM.getText()))) {
6959                    return true;
6960                }
6961                if (!Objects.equals(oldM.getDataUri(), newM.getDataUri())) {
6962                    return true;
6963                }
6964                String oldSender = String.valueOf(oldM.getSenderPerson() == null
6965                        ? oldM.getSender()
6966                        : oldM.getSenderPerson().getName());
6967                String newSender = String.valueOf(newM.getSenderPerson() == null
6968                        ? newM.getSender()
6969                        : newM.getSenderPerson().getName());
6970                if (!Objects.equals(oldSender, newSender)) {
6971                    return true;
6972                }
6973
6974                String oldKey = oldM.getSenderPerson() == null
6975                        ? null : oldM.getSenderPerson().getKey();
6976                String newKey = newM.getSenderPerson() == null
6977                        ? null : newM.getSenderPerson().getKey();
6978                if (!Objects.equals(oldKey, newKey)) {
6979                    return true;
6980                }
6981                // Other fields (like timestamp) intentionally excluded
6982            }
6983            return false;
6984        }
6985
6986        private Message findLatestIncomingMessage() {
6987            return findLatestIncomingMessage(mMessages);
6988        }
6989
6990        /**
6991         * @hide
6992         */
6993        @Nullable
6994        public static Message findLatestIncomingMessage(
6995                List<Message> messages) {
6996            for (int i = messages.size() - 1; i >= 0; i--) {
6997                Message m = messages.get(i);
6998                // Incoming messages have a non-empty sender.
6999                if (m.mSender != null && !TextUtils.isEmpty(m.mSender.getName())) {
7000                    return m;
7001                }
7002            }
7003            if (!messages.isEmpty()) {
7004                // No incoming messages, fall back to outgoing message
7005                return messages.get(messages.size() - 1);
7006            }
7007            return null;
7008        }
7009
7010        /**
7011         * @hide
7012         */
7013        @Override
7014        public RemoteViews makeBigContentView() {
7015            return makeMessagingView(false /* displayImagesAtEnd */, true /* hideLargeIcon */);
7016        }
7017
7018        /**
7019         * Create a messaging layout.
7020         *
7021         * @param displayImagesAtEnd should images be displayed at the end of the content instead
7022         *                           of inline.
7023         * @param hideRightIcons Should the reply affordance be shown at the end of the notification
7024         * @return the created remoteView.
7025         */
7026        @NonNull
7027        private RemoteViews makeMessagingView(boolean displayImagesAtEnd, boolean hideRightIcons) {
7028            CharSequence conversationTitle = !TextUtils.isEmpty(super.mBigContentTitle)
7029                    ? super.mBigContentTitle
7030                    : mConversationTitle;
7031            boolean isOneToOne = TextUtils.isEmpty(conversationTitle);
7032            CharSequence nameReplacement = null;
7033            if (hasOnlyWhiteSpaceSenders()) {
7034                isOneToOne = true;
7035                nameReplacement = conversationTitle;
7036                conversationTitle = null;
7037            }
7038            TemplateBindResult bindResult = new TemplateBindResult();
7039            RemoteViews contentView = mBuilder.applyStandardTemplateWithActions(
7040                    mBuilder.getMessagingLayoutResource(),
7041                    mBuilder.mParams.reset().hasProgress(false).title(conversationTitle).text(null)
7042                            .hideLargeIcon(hideRightIcons || isOneToOne)
7043                            .hideReplyIcon(hideRightIcons)
7044                            .headerTextSecondary(conversationTitle),
7045                    bindResult);
7046            addExtras(mBuilder.mN.extras);
7047            // also update the end margin if there is an image
7048            contentView.setViewLayoutMarginEnd(R.id.notification_messaging,
7049                    bindResult.getIconMarginEnd());
7050            contentView.setInt(R.id.status_bar_latest_event_content, "setLayoutColor",
7051                    mBuilder.isColorized() ? mBuilder.getPrimaryTextColor()
7052                            : mBuilder.resolveContrastColor());
7053            contentView.setInt(R.id.status_bar_latest_event_content, "setSenderTextColor",
7054                    mBuilder.getPrimaryTextColor());
7055            contentView.setInt(R.id.status_bar_latest_event_content, "setMessageTextColor",
7056                    mBuilder.getSecondaryTextColor());
7057            contentView.setBoolean(R.id.status_bar_latest_event_content, "setDisplayImagesAtEnd",
7058                    displayImagesAtEnd);
7059            contentView.setIcon(R.id.status_bar_latest_event_content, "setLargeIcon",
7060                    mBuilder.mN.mLargeIcon);
7061            contentView.setCharSequence(R.id.status_bar_latest_event_content, "setNameReplacement",
7062                    nameReplacement);
7063            contentView.setBoolean(R.id.status_bar_latest_event_content, "setIsOneToOne",
7064                    isOneToOne);
7065            contentView.setBundle(R.id.status_bar_latest_event_content, "setData",
7066                    mBuilder.mN.extras);
7067            return contentView;
7068        }
7069
7070        private boolean hasOnlyWhiteSpaceSenders() {
7071            for (int i = 0; i < mMessages.size(); i++) {
7072                Message m = mMessages.get(i);
7073                Person sender = m.getSenderPerson();
7074                if (sender != null && !isWhiteSpace(sender.getName())) {
7075                    return false;
7076                }
7077            }
7078            return true;
7079        }
7080
7081        private boolean isWhiteSpace(CharSequence sender) {
7082            if (TextUtils.isEmpty(sender)) {
7083                return true;
7084            }
7085            if (sender.toString().matches("^\\s*$")) {
7086                return true;
7087            }
7088            // Let's check if we only have 0 whitespace chars. Some apps did this as a workaround
7089            // For the presentation that we had.
7090            for (int i = 0; i < sender.length(); i++) {
7091                char c = sender.charAt(i);
7092                if (c != '\u200B') {
7093                    return false;
7094                }
7095            }
7096            return true;
7097        }
7098
7099        private CharSequence createConversationTitleFromMessages() {
7100            ArraySet<CharSequence> names = new ArraySet<>();
7101            for (int i = 0; i < mMessages.size(); i++) {
7102                Message m = mMessages.get(i);
7103                Person sender = m.getSenderPerson();
7104                if (sender != null) {
7105                    names.add(sender.getName());
7106                }
7107            }
7108            SpannableStringBuilder title = new SpannableStringBuilder();
7109            int size = names.size();
7110            for (int i = 0; i < size; i++) {
7111                CharSequence name = names.valueAt(i);
7112                if (!TextUtils.isEmpty(title)) {
7113                    title.append(", ");
7114                }
7115                title.append(BidiFormatter.getInstance().unicodeWrap(name));
7116            }
7117            return title;
7118        }
7119
7120        /**
7121         * @hide
7122         */
7123        @Override
7124        public RemoteViews makeHeadsUpContentView(boolean increasedHeight) {
7125            RemoteViews remoteViews = makeMessagingView(true /* displayImagesAtEnd */,
7126                    true /* hideLargeIcon */);
7127            remoteViews.setInt(R.id.notification_messaging, "setMaxDisplayedLines", 1);
7128            return remoteViews;
7129        }
7130
7131        private static TextAppearanceSpan makeFontColorSpan(int color) {
7132            return new TextAppearanceSpan(null, 0, 0,
7133                    ColorStateList.valueOf(color), null);
7134        }
7135
7136        public static final class Message {
7137
7138            static final String KEY_TEXT = "text";
7139            static final String KEY_TIMESTAMP = "time";
7140            static final String KEY_SENDER = "sender";
7141            static final String KEY_SENDER_PERSON = "sender_person";
7142            static final String KEY_DATA_MIME_TYPE = "type";
7143            static final String KEY_DATA_URI= "uri";
7144            static final String KEY_EXTRAS_BUNDLE = "extras";
7145            static final String KEY_REMOTE_INPUT_HISTORY = "remote_input_history";
7146
7147            private final CharSequence mText;
7148            private final long mTimestamp;
7149            @Nullable
7150            private final Person mSender;
7151            /** True if this message was generated from the extra
7152             *  {@link Notification#EXTRA_REMOTE_INPUT_HISTORY}
7153             */
7154            private final boolean mRemoteInputHistory;
7155
7156            private Bundle mExtras = new Bundle();
7157            private String mDataMimeType;
7158            private Uri mDataUri;
7159
7160            /**
7161             * Constructor
7162             * @param text A {@link CharSequence} to be displayed as the message content
7163             * @param timestamp Time at which the message arrived
7164             * @param sender A {@link CharSequence} to be used for displaying the name of the
7165             * sender. Should be <code>null</code> for messages by the current user, in which case
7166             * the platform will insert {@link MessagingStyle#getUserDisplayName()}.
7167             * Should be unique amongst all individuals in the conversation, and should be
7168             * consistent during re-posts of the notification.
7169             *
7170             *  @deprecated use {@code Message(CharSequence, long, Person)}
7171             */
7172            public Message(CharSequence text, long timestamp, CharSequence sender){
7173                this(text, timestamp, sender == null ? null
7174                        : new Person.Builder().setName(sender).build());
7175            }
7176
7177            /**
7178             * Constructor
7179             * @param text A {@link CharSequence} to be displayed as the message content
7180             * @param timestamp Time at which the message arrived
7181             * @param sender The {@link Person} who sent the message.
7182             * Should be <code>null</code> for messages by the current user, in which case
7183             * the platform will insert the user set in {@code MessagingStyle(Person)}.
7184             * <p>
7185             * The person provided should contain an Icon, set with
7186             * {@link Person.Builder#setIcon(Icon)} and also have a name provided
7187             * with {@link Person.Builder#setName(CharSequence)}. If multiple users have the same
7188             * name, consider providing a key with {@link Person.Builder#setKey(String)} in order
7189             * to differentiate between the different users.
7190             * </p>
7191             */
7192            public Message(@NonNull CharSequence text, long timestamp, @Nullable Person sender) {
7193                this(text, timestamp, sender, false /* remoteHistory */);
7194            }
7195
7196            /**
7197             * Constructor
7198             * @param text A {@link CharSequence} to be displayed as the message content
7199             * @param timestamp Time at which the message arrived
7200             * @param sender The {@link Person} who sent the message.
7201             * Should be <code>null</code> for messages by the current user, in which case
7202             * the platform will insert the user set in {@code MessagingStyle(Person)}.
7203             * @param remoteInputHistory True if the messages was generated from the extra
7204             * {@link Notification#EXTRA_REMOTE_INPUT_HISTORY}.
7205             * <p>
7206             * The person provided should contain an Icon, set with
7207             * {@link Person.Builder#setIcon(Icon)} and also have a name provided
7208             * with {@link Person.Builder#setName(CharSequence)}. If multiple users have the same
7209             * name, consider providing a key with {@link Person.Builder#setKey(String)} in order
7210             * to differentiate between the different users.
7211             * </p>
7212             * @hide
7213             */
7214            public Message(@NonNull CharSequence text, long timestamp, @Nullable Person sender,
7215                    boolean remoteInputHistory) {
7216                mText = text;
7217                mTimestamp = timestamp;
7218                mSender = sender;
7219                mRemoteInputHistory = remoteInputHistory;
7220            }
7221
7222            /**
7223             * Sets a binary blob of data and an associated MIME type for a message. In the case
7224             * where the platform doesn't support the MIME type, the original text provided in the
7225             * constructor will be used.
7226             * @param dataMimeType The MIME type of the content. See
7227             * <a href="{@docRoot}notifications/messaging.html"> for the list of supported MIME
7228             * types on Android and Android Wear.
7229             * @param dataUri The uri containing the content whose type is given by the MIME type.
7230             * <p class="note">
7231             * <ol>
7232             *   <li>Notification Listeners including the System UI need permission to access the
7233             *       data the Uri points to. The recommended ways to do this are:</li>
7234             *   <li>Store the data in your own ContentProvider, making sure that other apps have
7235             *       the correct permission to access your provider. The preferred mechanism for
7236             *       providing access is to use per-URI permissions which are temporary and only
7237             *       grant access to the receiving application. An easy way to create a
7238             *       ContentProvider like this is to use the FileProvider helper class.</li>
7239             *   <li>Use the system MediaStore. The MediaStore is primarily aimed at video, audio
7240             *       and image MIME types, however beginning with Android 3.0 (API level 11) it can
7241             *       also store non-media types (see MediaStore.Files for more info). Files can be
7242             *       inserted into the MediaStore using scanFile() after which a content:// style
7243             *       Uri suitable for sharing is passed to the provided onScanCompleted() callback.
7244             *       Note that once added to the system MediaStore the content is accessible to any
7245             *       app on the device.</li>
7246             * </ol>
7247             * @return this object for method chaining
7248             */
7249            public Message setData(String dataMimeType, Uri dataUri) {
7250                mDataMimeType = dataMimeType;
7251                mDataUri = dataUri;
7252                return this;
7253            }
7254
7255            /**
7256             * Get the text to be used for this message, or the fallback text if a type and content
7257             * Uri have been set
7258             */
7259            public CharSequence getText() {
7260                return mText;
7261            }
7262
7263            /**
7264             * Get the time at which this message arrived
7265             */
7266            public long getTimestamp() {
7267                return mTimestamp;
7268            }
7269
7270            /**
7271             * Get the extras Bundle for this message.
7272             */
7273            public Bundle getExtras() {
7274                return mExtras;
7275            }
7276
7277            /**
7278             * Get the text used to display the contact's name in the messaging experience
7279             *
7280             * @deprecated use {@link #getSenderPerson()}
7281             */
7282            public CharSequence getSender() {
7283                return mSender == null ? null : mSender.getName();
7284            }
7285
7286            /**
7287             * Get the sender associated with this message.
7288             */
7289            @Nullable
7290            public Person getSenderPerson() {
7291                return mSender;
7292            }
7293
7294            /**
7295             * Get the MIME type of the data pointed to by the Uri
7296             */
7297            public String getDataMimeType() {
7298                return mDataMimeType;
7299            }
7300
7301            /**
7302             * Get the the Uri pointing to the content of the message. Can be null, in which case
7303             * {@see #getText()} is used.
7304             */
7305            public Uri getDataUri() {
7306                return mDataUri;
7307            }
7308
7309            /**
7310             * @return True if the message was generated from
7311             * {@link Notification#EXTRA_REMOTE_INPUT_HISTORY}.
7312             * @hide
7313             */
7314            public boolean isRemoteInputHistory() {
7315                return mRemoteInputHistory;
7316            }
7317
7318            private Bundle toBundle() {
7319                Bundle bundle = new Bundle();
7320                if (mText != null) {
7321                    bundle.putCharSequence(KEY_TEXT, mText);
7322                }
7323                bundle.putLong(KEY_TIMESTAMP, mTimestamp);
7324                if (mSender != null) {
7325                    // Legacy listeners need this
7326                    bundle.putCharSequence(KEY_SENDER, mSender.getName());
7327                    bundle.putParcelable(KEY_SENDER_PERSON, mSender);
7328                }
7329                if (mDataMimeType != null) {
7330                    bundle.putString(KEY_DATA_MIME_TYPE, mDataMimeType);
7331                }
7332                if (mDataUri != null) {
7333                    bundle.putParcelable(KEY_DATA_URI, mDataUri);
7334                }
7335                if (mExtras != null) {
7336                    bundle.putBundle(KEY_EXTRAS_BUNDLE, mExtras);
7337                }
7338                if (mRemoteInputHistory) {
7339                    bundle.putBoolean(KEY_REMOTE_INPUT_HISTORY, mRemoteInputHistory);
7340                }
7341                return bundle;
7342            }
7343
7344            static Bundle[] getBundleArrayForMessages(List<Message> messages) {
7345                Bundle[] bundles = new Bundle[messages.size()];
7346                final int N = messages.size();
7347                for (int i = 0; i < N; i++) {
7348                    bundles[i] = messages.get(i).toBundle();
7349                }
7350                return bundles;
7351            }
7352
7353            /**
7354             * @return A list of messages read from the bundles.
7355             *
7356             * @hide
7357             */
7358            public static List<Message> getMessagesFromBundleArray(Parcelable[] bundles) {
7359                if (bundles == null) {
7360                    return new ArrayList<>();
7361                }
7362                List<Message> messages = new ArrayList<>(bundles.length);
7363                for (int i = 0; i < bundles.length; i++) {
7364                    if (bundles[i] instanceof Bundle) {
7365                        Message message = getMessageFromBundle((Bundle)bundles[i]);
7366                        if (message != null) {
7367                            messages.add(message);
7368                        }
7369                    }
7370                }
7371                return messages;
7372            }
7373
7374            static Message getMessageFromBundle(Bundle bundle) {
7375                try {
7376                    if (!bundle.containsKey(KEY_TEXT) || !bundle.containsKey(KEY_TIMESTAMP)) {
7377                        return null;
7378                    } else {
7379
7380                        Person senderPerson = bundle.getParcelable(KEY_SENDER_PERSON);
7381                        if (senderPerson == null) {
7382                            // Legacy apps that use compat don't actually provide the sender objects
7383                            // We need to fix the compat version to provide people / use
7384                            // the native api instead
7385                            CharSequence senderName = bundle.getCharSequence(KEY_SENDER);
7386                            if (senderName != null) {
7387                                senderPerson = new Person.Builder().setName(senderName).build();
7388                            }
7389                        }
7390                        Message message = new Message(bundle.getCharSequence(KEY_TEXT),
7391                                bundle.getLong(KEY_TIMESTAMP),
7392                                senderPerson,
7393                                bundle.getBoolean(KEY_REMOTE_INPUT_HISTORY, false));
7394                        if (bundle.containsKey(KEY_DATA_MIME_TYPE) &&
7395                                bundle.containsKey(KEY_DATA_URI)) {
7396                            message.setData(bundle.getString(KEY_DATA_MIME_TYPE),
7397                                    (Uri) bundle.getParcelable(KEY_DATA_URI));
7398                        }
7399                        if (bundle.containsKey(KEY_EXTRAS_BUNDLE)) {
7400                            message.getExtras().putAll(bundle.getBundle(KEY_EXTRAS_BUNDLE));
7401                        }
7402                        return message;
7403                    }
7404                } catch (ClassCastException e) {
7405                    return null;
7406                }
7407            }
7408        }
7409    }
7410
7411    /**
7412     * Helper class for generating large-format notifications that include a list of (up to 5) strings.
7413     *
7414     * Here's how you'd set the <code>InboxStyle</code> on a notification:
7415     * <pre class="prettyprint">
7416     * Notification notif = new Notification.Builder(mContext)
7417     *     .setContentTitle(&quot;5 New mails from &quot; + sender.toString())
7418     *     .setContentText(subject)
7419     *     .setSmallIcon(R.drawable.new_mail)
7420     *     .setLargeIcon(aBitmap)
7421     *     .setStyle(new Notification.InboxStyle()
7422     *         .addLine(str1)
7423     *         .addLine(str2)
7424     *         .setContentTitle(&quot;&quot;)
7425     *         .setSummaryText(&quot;+3 more&quot;))
7426     *     .build();
7427     * </pre>
7428     *
7429     * @see Notification#bigContentView
7430     */
7431    public static class InboxStyle extends Style {
7432
7433        /**
7434         * The number of lines of remote input history allowed until we start reducing lines.
7435         */
7436        private static final int NUMBER_OF_HISTORY_ALLOWED_UNTIL_REDUCTION = 1;
7437        private ArrayList<CharSequence> mTexts = new ArrayList<CharSequence>(5);
7438
7439        public InboxStyle() {
7440        }
7441
7442        /**
7443         * @deprecated use {@code InboxStyle()}.
7444         */
7445        @Deprecated
7446        public InboxStyle(Builder builder) {
7447            setBuilder(builder);
7448        }
7449
7450        /**
7451         * Overrides ContentTitle in the big form of the template.
7452         * This defaults to the value passed to setContentTitle().
7453         */
7454        public InboxStyle setBigContentTitle(CharSequence title) {
7455            internalSetBigContentTitle(safeCharSequence(title));
7456            return this;
7457        }
7458
7459        /**
7460         * Set the first line of text after the detail section in the big form of the template.
7461         */
7462        public InboxStyle setSummaryText(CharSequence cs) {
7463            internalSetSummaryText(safeCharSequence(cs));
7464            return this;
7465        }
7466
7467        /**
7468         * Append a line to the digest section of the Inbox notification.
7469         */
7470        public InboxStyle addLine(CharSequence cs) {
7471            mTexts.add(safeCharSequence(cs));
7472            return this;
7473        }
7474
7475        /**
7476         * @hide
7477         */
7478        public ArrayList<CharSequence> getLines() {
7479            return mTexts;
7480        }
7481
7482        /**
7483         * @hide
7484         */
7485        public void addExtras(Bundle extras) {
7486            super.addExtras(extras);
7487
7488            CharSequence[] a = new CharSequence[mTexts.size()];
7489            extras.putCharSequenceArray(EXTRA_TEXT_LINES, mTexts.toArray(a));
7490        }
7491
7492        /**
7493         * @hide
7494         */
7495        @Override
7496        protected void restoreFromExtras(Bundle extras) {
7497            super.restoreFromExtras(extras);
7498
7499            mTexts.clear();
7500            if (extras.containsKey(EXTRA_TEXT_LINES)) {
7501                Collections.addAll(mTexts, extras.getCharSequenceArray(EXTRA_TEXT_LINES));
7502            }
7503        }
7504
7505        /**
7506         * @hide
7507         */
7508        public RemoteViews makeBigContentView() {
7509            // Remove the content text so it disappears unless you have a summary
7510            // Nasty
7511            CharSequence oldBuilderContentText = mBuilder.mN.extras.getCharSequence(EXTRA_TEXT);
7512            mBuilder.getAllExtras().putCharSequence(EXTRA_TEXT, null);
7513
7514            TemplateBindResult result = new TemplateBindResult();
7515            RemoteViews contentView = getStandardView(mBuilder.getInboxLayoutResource(), result);
7516
7517            mBuilder.getAllExtras().putCharSequence(EXTRA_TEXT, oldBuilderContentText);
7518
7519            int[] rowIds = {R.id.inbox_text0, R.id.inbox_text1, R.id.inbox_text2, R.id.inbox_text3,
7520                    R.id.inbox_text4, R.id.inbox_text5, R.id.inbox_text6};
7521
7522            // Make sure all rows are gone in case we reuse a view.
7523            for (int rowId : rowIds) {
7524                contentView.setViewVisibility(rowId, View.GONE);
7525            }
7526
7527            int i=0;
7528            int topPadding = mBuilder.mContext.getResources().getDimensionPixelSize(
7529                    R.dimen.notification_inbox_item_top_padding);
7530            boolean first = true;
7531            int onlyViewId = 0;
7532            int maxRows = rowIds.length;
7533            if (mBuilder.mActions.size() > 0) {
7534                maxRows--;
7535            }
7536            CharSequence[] remoteInputHistory = mBuilder.mN.extras.getCharSequenceArray(
7537                    EXTRA_REMOTE_INPUT_HISTORY);
7538            if (remoteInputHistory != null
7539                    && remoteInputHistory.length > NUMBER_OF_HISTORY_ALLOWED_UNTIL_REDUCTION) {
7540                // Let's remove some messages to make room for the remote input history.
7541                // 1 is always able to fit, but let's remove them if they are 2 or 3
7542                int numRemoteInputs = Math.min(remoteInputHistory.length,
7543                        MAX_REMOTE_INPUT_HISTORY_LINES);
7544                int totalNumRows = mTexts.size() + numRemoteInputs
7545                        - NUMBER_OF_HISTORY_ALLOWED_UNTIL_REDUCTION;
7546                if (totalNumRows > maxRows) {
7547                    int overflow = totalNumRows - maxRows;
7548                    if (mTexts.size() > maxRows) {
7549                        // Heuristic: if the Texts don't fit anyway, we'll rather drop the last
7550                        // few messages, even with the remote input
7551                        maxRows -= overflow;
7552                    } else  {
7553                        // otherwise we drop the first messages
7554                        i = overflow;
7555                    }
7556                }
7557            }
7558            while (i < mTexts.size() && i < maxRows) {
7559                CharSequence str = mTexts.get(i);
7560                if (!TextUtils.isEmpty(str)) {
7561                    contentView.setViewVisibility(rowIds[i], View.VISIBLE);
7562                    contentView.setTextViewText(rowIds[i],
7563                            mBuilder.processTextSpans(mBuilder.processLegacyText(str)));
7564                    mBuilder.setTextViewColorSecondary(contentView, rowIds[i]);
7565                    contentView.setViewPadding(rowIds[i], 0, topPadding, 0, 0);
7566                    handleInboxImageMargin(contentView, rowIds[i], first,
7567                            result.getIconMarginEnd());
7568                    if (first) {
7569                        onlyViewId = rowIds[i];
7570                    } else {
7571                        onlyViewId = 0;
7572                    }
7573                    first = false;
7574                }
7575                i++;
7576            }
7577            if (onlyViewId != 0) {
7578                // We only have 1 entry, lets make it look like the normal Text of a Bigtext
7579                topPadding = mBuilder.mContext.getResources().getDimensionPixelSize(
7580                        R.dimen.notification_text_margin_top);
7581                contentView.setViewPadding(onlyViewId, 0, topPadding, 0, 0);
7582            }
7583
7584            return contentView;
7585        }
7586
7587        /**
7588         * @hide
7589         */
7590        @Override
7591        public boolean areNotificationsVisiblyDifferent(Style other) {
7592            if (other == null || getClass() != other.getClass()) {
7593                return true;
7594            }
7595            InboxStyle newS = (InboxStyle) other;
7596
7597            final ArrayList<CharSequence> myLines = getLines();
7598            final ArrayList<CharSequence> newLines = newS.getLines();
7599            final int n = myLines.size();
7600            if (n != newLines.size()) {
7601                return true;
7602            }
7603
7604            for (int i = 0; i < n; i++) {
7605                if (!Objects.equals(
7606                        String.valueOf(myLines.get(i)),
7607                        String.valueOf(newLines.get(i)))) {
7608                    return true;
7609                }
7610            }
7611            return false;
7612        }
7613
7614        private void handleInboxImageMargin(RemoteViews contentView, int id, boolean first,
7615                int marginEndValue) {
7616            int endMargin = 0;
7617            if (first) {
7618                final int max = mBuilder.mN.extras.getInt(EXTRA_PROGRESS_MAX, 0);
7619                final boolean ind = mBuilder.mN.extras.getBoolean(EXTRA_PROGRESS_INDETERMINATE);
7620                boolean hasProgress = max != 0 || ind;
7621                if (!hasProgress) {
7622                    endMargin = marginEndValue;
7623                }
7624            }
7625            contentView.setViewLayoutMarginEnd(id, endMargin);
7626        }
7627    }
7628
7629    /**
7630     * Notification style for media playback notifications.
7631     *
7632     * In the expanded form, {@link Notification#bigContentView}, up to 5
7633     * {@link Notification.Action}s specified with
7634     * {@link Notification.Builder#addAction(Action) addAction} will be
7635     * shown as icon-only pushbuttons, suitable for transport controls. The Bitmap given to
7636     * {@link Notification.Builder#setLargeIcon(android.graphics.Bitmap) setLargeIcon()} will be
7637     * treated as album artwork.
7638     * <p>
7639     * Unlike the other styles provided here, MediaStyle can also modify the standard-size
7640     * {@link Notification#contentView}; by providing action indices to
7641     * {@link #setShowActionsInCompactView(int...)} you can promote up to 3 actions to be displayed
7642     * in the standard view alongside the usual content.
7643     * <p>
7644     * Notifications created with MediaStyle will have their category set to
7645     * {@link Notification#CATEGORY_TRANSPORT CATEGORY_TRANSPORT} unless you set a different
7646     * category using {@link Notification.Builder#setCategory(String) setCategory()}.
7647     * <p>
7648     * Finally, if you attach a {@link android.media.session.MediaSession.Token} using
7649     * {@link android.app.Notification.MediaStyle#setMediaSession(MediaSession.Token)},
7650     * the System UI can identify this as a notification representing an active media session
7651     * and respond accordingly (by showing album artwork in the lockscreen, for example).
7652     *
7653     * <p>
7654     * Starting at {@link android.os.Build.VERSION_CODES#O Android O} any notification that has a
7655     * media session attached with {@link #setMediaSession(MediaSession.Token)} will be colorized.
7656     * You can opt-out of this behavior by using {@link Notification.Builder#setColorized(boolean)}.
7657     * <p>
7658     *
7659     * To use this style with your Notification, feed it to
7660     * {@link Notification.Builder#setStyle(android.app.Notification.Style)} like so:
7661     * <pre class="prettyprint">
7662     * Notification noti = new Notification.Builder()
7663     *     .setSmallIcon(R.drawable.ic_stat_player)
7664     *     .setContentTitle(&quot;Track title&quot;)
7665     *     .setContentText(&quot;Artist - Album&quot;)
7666     *     .setLargeIcon(albumArtBitmap))
7667     *     .setStyle(<b>new Notification.MediaStyle()</b>
7668     *         .setMediaSession(mySession))
7669     *     .build();
7670     * </pre>
7671     *
7672     * @see Notification#bigContentView
7673     * @see Notification.Builder#setColorized(boolean)
7674     */
7675    public static class MediaStyle extends Style {
7676        static final int MAX_MEDIA_BUTTONS_IN_COMPACT = 3;
7677        static final int MAX_MEDIA_BUTTONS = 5;
7678
7679        private int[] mActionsToShowInCompact = null;
7680        private MediaSession.Token mToken;
7681
7682        public MediaStyle() {
7683        }
7684
7685        /**
7686         * @deprecated use {@code MediaStyle()}.
7687         */
7688        @Deprecated
7689        public MediaStyle(Builder builder) {
7690            setBuilder(builder);
7691        }
7692
7693        /**
7694         * Request up to 3 actions (by index in the order of addition) to be shown in the compact
7695         * notification view.
7696         *
7697         * @param actions the indices of the actions to show in the compact notification view
7698         */
7699        public MediaStyle setShowActionsInCompactView(int...actions) {
7700            mActionsToShowInCompact = actions;
7701            return this;
7702        }
7703
7704        /**
7705         * Attach a {@link android.media.session.MediaSession.Token} to this Notification
7706         * to provide additional playback information and control to the SystemUI.
7707         */
7708        public MediaStyle setMediaSession(MediaSession.Token token) {
7709            mToken = token;
7710            return this;
7711        }
7712
7713        /**
7714         * @hide
7715         */
7716        @Override
7717        public Notification buildStyled(Notification wip) {
7718            super.buildStyled(wip);
7719            if (wip.category == null) {
7720                wip.category = Notification.CATEGORY_TRANSPORT;
7721            }
7722            return wip;
7723        }
7724
7725        /**
7726         * @hide
7727         */
7728        @Override
7729        public RemoteViews makeContentView(boolean increasedHeight) {
7730            return makeMediaContentView();
7731        }
7732
7733        /**
7734         * @hide
7735         */
7736        @Override
7737        public RemoteViews makeBigContentView() {
7738            return makeMediaBigContentView();
7739        }
7740
7741        /**
7742         * @hide
7743         */
7744        @Override
7745        public RemoteViews makeHeadsUpContentView(boolean increasedHeight) {
7746            RemoteViews expanded = makeMediaBigContentView();
7747            return expanded != null ? expanded : makeMediaContentView();
7748        }
7749
7750        /** @hide */
7751        @Override
7752        public void addExtras(Bundle extras) {
7753            super.addExtras(extras);
7754
7755            if (mToken != null) {
7756                extras.putParcelable(EXTRA_MEDIA_SESSION, mToken);
7757            }
7758            if (mActionsToShowInCompact != null) {
7759                extras.putIntArray(EXTRA_COMPACT_ACTIONS, mActionsToShowInCompact);
7760            }
7761        }
7762
7763        /**
7764         * @hide
7765         */
7766        @Override
7767        protected void restoreFromExtras(Bundle extras) {
7768            super.restoreFromExtras(extras);
7769
7770            if (extras.containsKey(EXTRA_MEDIA_SESSION)) {
7771                mToken = extras.getParcelable(EXTRA_MEDIA_SESSION);
7772            }
7773            if (extras.containsKey(EXTRA_COMPACT_ACTIONS)) {
7774                mActionsToShowInCompact = extras.getIntArray(EXTRA_COMPACT_ACTIONS);
7775            }
7776        }
7777
7778        /**
7779         * @hide
7780         */
7781        @Override
7782        public boolean areNotificationsVisiblyDifferent(Style other) {
7783            if (other == null || getClass() != other.getClass()) {
7784                return true;
7785            }
7786            // All fields to compare are on the Notification object
7787            return false;
7788        }
7789
7790        private RemoteViews generateMediaActionButton(Action action, int color) {
7791            final boolean tombstone = (action.actionIntent == null);
7792            RemoteViews button = new BuilderRemoteViews(mBuilder.mContext.getApplicationInfo(),
7793                    R.layout.notification_material_media_action);
7794            button.setImageViewIcon(R.id.action0, action.getIcon());
7795
7796            // If the action buttons should not be tinted, then just use the default
7797            // notification color. Otherwise, just use the passed-in color.
7798            int tintColor = mBuilder.shouldTintActionButtons() || mBuilder.isColorized()
7799                    ? color
7800                    : NotificationColorUtil.resolveColor(mBuilder.mContext,
7801                            Notification.COLOR_DEFAULT);
7802
7803            button.setDrawableTint(R.id.action0, false, tintColor,
7804                    PorterDuff.Mode.SRC_ATOP);
7805            if (!tombstone) {
7806                button.setOnClickPendingIntent(R.id.action0, action.actionIntent);
7807            }
7808            button.setContentDescription(R.id.action0, action.title);
7809            return button;
7810        }
7811
7812        private RemoteViews makeMediaContentView() {
7813            RemoteViews view = mBuilder.applyStandardTemplate(
7814                    R.layout.notification_template_material_media, false, /* hasProgress */
7815                    null /* result */);
7816
7817            final int numActions = mBuilder.mActions.size();
7818            final int N = mActionsToShowInCompact == null
7819                    ? 0
7820                    : Math.min(mActionsToShowInCompact.length, MAX_MEDIA_BUTTONS_IN_COMPACT);
7821            if (N > 0) {
7822                view.removeAllViews(com.android.internal.R.id.media_actions);
7823                for (int i = 0; i < N; i++) {
7824                    if (i >= numActions) {
7825                        throw new IllegalArgumentException(String.format(
7826                                "setShowActionsInCompactView: action %d out of bounds (max %d)",
7827                                i, numActions - 1));
7828                    }
7829
7830                    final Action action = mBuilder.mActions.get(mActionsToShowInCompact[i]);
7831                    final RemoteViews button = generateMediaActionButton(action, getActionColor());
7832                    view.addView(com.android.internal.R.id.media_actions, button);
7833                }
7834            }
7835            handleImage(view);
7836            // handle the content margin
7837            int endMargin = R.dimen.notification_content_margin_end;
7838            if (mBuilder.mN.hasLargeIcon()) {
7839                endMargin = R.dimen.notification_media_image_margin_end;
7840            }
7841            view.setViewLayoutMarginEndDimen(R.id.notification_main_column, endMargin);
7842            return view;
7843        }
7844
7845        private int getActionColor() {
7846            return mBuilder.isColorized() ? mBuilder.getPrimaryTextColor()
7847                    : mBuilder.resolveContrastColor();
7848        }
7849
7850        private RemoteViews makeMediaBigContentView() {
7851            final int actionCount = Math.min(mBuilder.mActions.size(), MAX_MEDIA_BUTTONS);
7852            // Dont add an expanded view if there is no more content to be revealed
7853            int actionsInCompact = mActionsToShowInCompact == null
7854                    ? 0
7855                    : Math.min(mActionsToShowInCompact.length, MAX_MEDIA_BUTTONS_IN_COMPACT);
7856            if (!mBuilder.mN.hasLargeIcon() && actionCount <= actionsInCompact) {
7857                return null;
7858            }
7859            RemoteViews big = mBuilder.applyStandardTemplate(
7860                    R.layout.notification_template_material_big_media, false, null /* result */);
7861
7862            if (actionCount > 0) {
7863                big.removeAllViews(com.android.internal.R.id.media_actions);
7864                for (int i = 0; i < actionCount; i++) {
7865                    final RemoteViews button = generateMediaActionButton(mBuilder.mActions.get(i),
7866                            getActionColor());
7867                    big.addView(com.android.internal.R.id.media_actions, button);
7868                }
7869            }
7870            handleImage(big);
7871            return big;
7872        }
7873
7874        private void handleImage(RemoteViews contentView) {
7875            if (mBuilder.mN.hasLargeIcon()) {
7876                contentView.setViewLayoutMarginEndDimen(R.id.line1, 0);
7877                contentView.setViewLayoutMarginEndDimen(R.id.text, 0);
7878            }
7879        }
7880
7881        /**
7882         * @hide
7883         */
7884        @Override
7885        protected boolean hasProgress() {
7886            return false;
7887        }
7888    }
7889
7890    /**
7891     * Notification style for custom views that are decorated by the system
7892     *
7893     * <p>Instead of providing a notification that is completely custom, a developer can set this
7894     * style and still obtain system decorations like the notification header with the expand
7895     * affordance and actions.
7896     *
7897     * <p>Use {@link android.app.Notification.Builder#setCustomContentView(RemoteViews)},
7898     * {@link android.app.Notification.Builder#setCustomBigContentView(RemoteViews)} and
7899     * {@link android.app.Notification.Builder#setCustomHeadsUpContentView(RemoteViews)} to set the
7900     * corresponding custom views to display.
7901     *
7902     * To use this style with your Notification, feed it to
7903     * {@link Notification.Builder#setStyle(android.app.Notification.Style)} like so:
7904     * <pre class="prettyprint">
7905     * Notification noti = new Notification.Builder()
7906     *     .setSmallIcon(R.drawable.ic_stat_player)
7907     *     .setLargeIcon(albumArtBitmap))
7908     *     .setCustomContentView(contentView);
7909     *     .setStyle(<b>new Notification.DecoratedCustomViewStyle()</b>)
7910     *     .build();
7911     * </pre>
7912     */
7913    public static class DecoratedCustomViewStyle extends Style {
7914
7915        public DecoratedCustomViewStyle() {
7916        }
7917
7918        /**
7919         * @hide
7920         */
7921        public boolean displayCustomViewInline() {
7922            return true;
7923        }
7924
7925        /**
7926         * @hide
7927         */
7928        @Override
7929        public RemoteViews makeContentView(boolean increasedHeight) {
7930            return makeStandardTemplateWithCustomContent(mBuilder.mN.contentView);
7931        }
7932
7933        /**
7934         * @hide
7935         */
7936        @Override
7937        public RemoteViews makeBigContentView() {
7938            return makeDecoratedBigContentView();
7939        }
7940
7941        /**
7942         * @hide
7943         */
7944        @Override
7945        public RemoteViews makeHeadsUpContentView(boolean increasedHeight) {
7946            return makeDecoratedHeadsUpContentView();
7947        }
7948
7949        private RemoteViews makeDecoratedHeadsUpContentView() {
7950            RemoteViews headsUpContentView = mBuilder.mN.headsUpContentView == null
7951                    ? mBuilder.mN.contentView
7952                    : mBuilder.mN.headsUpContentView;
7953            if (mBuilder.mActions.size() == 0) {
7954               return makeStandardTemplateWithCustomContent(headsUpContentView);
7955            }
7956            TemplateBindResult result = new TemplateBindResult();
7957            RemoteViews remoteViews = mBuilder.applyStandardTemplateWithActions(
7958                        mBuilder.getBigBaseLayoutResource(), result);
7959            buildIntoRemoteViewContent(remoteViews, headsUpContentView, result);
7960            return remoteViews;
7961        }
7962
7963        private RemoteViews makeStandardTemplateWithCustomContent(RemoteViews customContent) {
7964            TemplateBindResult result = new TemplateBindResult();
7965            RemoteViews remoteViews = mBuilder.applyStandardTemplate(
7966                    mBuilder.getBaseLayoutResource(), result);
7967            buildIntoRemoteViewContent(remoteViews, customContent, result);
7968            return remoteViews;
7969        }
7970
7971        private RemoteViews makeDecoratedBigContentView() {
7972            RemoteViews bigContentView = mBuilder.mN.bigContentView == null
7973                    ? mBuilder.mN.contentView
7974                    : mBuilder.mN.bigContentView;
7975            if (mBuilder.mActions.size() == 0) {
7976                return makeStandardTemplateWithCustomContent(bigContentView);
7977            }
7978            TemplateBindResult result = new TemplateBindResult();
7979            RemoteViews remoteViews = mBuilder.applyStandardTemplateWithActions(
7980                    mBuilder.getBigBaseLayoutResource(), result);
7981            buildIntoRemoteViewContent(remoteViews, bigContentView, result);
7982            return remoteViews;
7983        }
7984
7985        private void buildIntoRemoteViewContent(RemoteViews remoteViews,
7986                RemoteViews customContent, TemplateBindResult result) {
7987            if (customContent != null) {
7988                // Need to clone customContent before adding, because otherwise it can no longer be
7989                // parceled independently of remoteViews.
7990                customContent = customContent.clone();
7991                remoteViews.removeAllViewsExceptId(R.id.notification_main_column, R.id.progress);
7992                remoteViews.addView(R.id.notification_main_column, customContent, 0 /* index */);
7993                remoteViews.setReapplyDisallowed();
7994            }
7995            // also update the end margin if there is an image
7996            Resources resources = mBuilder.mContext.getResources();
7997            int endMargin = resources.getDimensionPixelSize(
7998                    R.dimen.notification_content_margin_end) + result.getIconMarginEnd();
7999            remoteViews.setViewLayoutMarginEnd(R.id.notification_main_column, endMargin);
8000        }
8001
8002        /**
8003         * @hide
8004         */
8005        @Override
8006        public boolean areNotificationsVisiblyDifferent(Style other) {
8007            if (other == null || getClass() != other.getClass()) {
8008                return true;
8009            }
8010            // Comparison done for all custom RemoteViews, independent of style
8011            return false;
8012        }
8013    }
8014
8015    /**
8016     * Notification style for media custom views that are decorated by the system
8017     *
8018     * <p>Instead of providing a media notification that is completely custom, a developer can set
8019     * this style and still obtain system decorations like the notification header with the expand
8020     * affordance and actions.
8021     *
8022     * <p>Use {@link android.app.Notification.Builder#setCustomContentView(RemoteViews)},
8023     * {@link android.app.Notification.Builder#setCustomBigContentView(RemoteViews)} and
8024     * {@link android.app.Notification.Builder#setCustomHeadsUpContentView(RemoteViews)} to set the
8025     * corresponding custom views to display.
8026     * <p>
8027     * Contrary to {@link MediaStyle} a developer has to opt-in to the colorizing of the
8028     * notification by using {@link Notification.Builder#setColorized(boolean)}.
8029     * <p>
8030     * To use this style with your Notification, feed it to
8031     * {@link Notification.Builder#setStyle(android.app.Notification.Style)} like so:
8032     * <pre class="prettyprint">
8033     * Notification noti = new Notification.Builder()
8034     *     .setSmallIcon(R.drawable.ic_stat_player)
8035     *     .setLargeIcon(albumArtBitmap))
8036     *     .setCustomContentView(contentView);
8037     *     .setStyle(<b>new Notification.DecoratedMediaCustomViewStyle()</b>
8038     *          .setMediaSession(mySession))
8039     *     .build();
8040     * </pre>
8041     *
8042     * @see android.app.Notification.DecoratedCustomViewStyle
8043     * @see android.app.Notification.MediaStyle
8044     */
8045    public static class DecoratedMediaCustomViewStyle extends MediaStyle {
8046
8047        public DecoratedMediaCustomViewStyle() {
8048        }
8049
8050        /**
8051         * @hide
8052         */
8053        public boolean displayCustomViewInline() {
8054            return true;
8055        }
8056
8057        /**
8058         * @hide
8059         */
8060        @Override
8061        public RemoteViews makeContentView(boolean increasedHeight) {
8062            RemoteViews remoteViews = super.makeContentView(false /* increasedHeight */);
8063            return buildIntoRemoteView(remoteViews, R.id.notification_content_container,
8064                    mBuilder.mN.contentView);
8065        }
8066
8067        /**
8068         * @hide
8069         */
8070        @Override
8071        public RemoteViews makeBigContentView() {
8072            RemoteViews customRemoteView = mBuilder.mN.bigContentView != null
8073                    ? mBuilder.mN.bigContentView
8074                    : mBuilder.mN.contentView;
8075            return makeBigContentViewWithCustomContent(customRemoteView);
8076        }
8077
8078        private RemoteViews makeBigContentViewWithCustomContent(RemoteViews customRemoteView) {
8079            RemoteViews remoteViews = super.makeBigContentView();
8080            if (remoteViews != null) {
8081                return buildIntoRemoteView(remoteViews, R.id.notification_main_column,
8082                        customRemoteView);
8083            } else if (customRemoteView != mBuilder.mN.contentView){
8084                remoteViews = super.makeContentView(false /* increasedHeight */);
8085                return buildIntoRemoteView(remoteViews, R.id.notification_content_container,
8086                        customRemoteView);
8087            } else {
8088                return null;
8089            }
8090        }
8091
8092        /**
8093         * @hide
8094         */
8095        @Override
8096        public RemoteViews makeHeadsUpContentView(boolean increasedHeight) {
8097            RemoteViews customRemoteView = mBuilder.mN.headsUpContentView != null
8098                    ? mBuilder.mN.headsUpContentView
8099                    : mBuilder.mN.contentView;
8100            return makeBigContentViewWithCustomContent(customRemoteView);
8101        }
8102
8103        /**
8104         * @hide
8105         */
8106        @Override
8107        public boolean areNotificationsVisiblyDifferent(Style other) {
8108            if (other == null || getClass() != other.getClass()) {
8109                return true;
8110            }
8111            // Comparison done for all custom RemoteViews, independent of style
8112            return false;
8113        }
8114
8115        private RemoteViews buildIntoRemoteView(RemoteViews remoteViews, int id,
8116                RemoteViews customContent) {
8117            if (customContent != null) {
8118                // Need to clone customContent before adding, because otherwise it can no longer be
8119                // parceled independently of remoteViews.
8120                customContent = customContent.clone();
8121                customContent.overrideTextColors(mBuilder.getPrimaryTextColor());
8122                remoteViews.removeAllViews(id);
8123                remoteViews.addView(id, customContent);
8124                remoteViews.setReapplyDisallowed();
8125            }
8126            return remoteViews;
8127        }
8128    }
8129
8130    // When adding a new Style subclass here, don't forget to update
8131    // Builder.getNotificationStyleClass.
8132
8133    /**
8134     * Extender interface for use with {@link Builder#extend}. Extenders may be used to add
8135     * metadata or change options on a notification builder.
8136     */
8137    public interface Extender {
8138        /**
8139         * Apply this extender to a notification builder.
8140         * @param builder the builder to be modified.
8141         * @return the build object for chaining.
8142         */
8143        public Builder extend(Builder builder);
8144    }
8145
8146    /**
8147     * Helper class to add wearable extensions to notifications.
8148     * <p class="note"> See
8149     * <a href="{@docRoot}wear/notifications/creating.html">Creating Notifications
8150     * for Android Wear</a> for more information on how to use this class.
8151     * <p>
8152     * To create a notification with wearable extensions:
8153     * <ol>
8154     *   <li>Create a {@link android.app.Notification.Builder}, setting any desired
8155     *   properties.
8156     *   <li>Create a {@link android.app.Notification.WearableExtender}.
8157     *   <li>Set wearable-specific properties using the
8158     *   {@code add} and {@code set} methods of {@link android.app.Notification.WearableExtender}.
8159     *   <li>Call {@link android.app.Notification.Builder#extend} to apply the extensions to a
8160     *   notification.
8161     *   <li>Post the notification to the notification system with the
8162     *   {@code NotificationManager.notify(...)} methods.
8163     * </ol>
8164     *
8165     * <pre class="prettyprint">
8166     * Notification notif = new Notification.Builder(mContext)
8167     *         .setContentTitle(&quot;New mail from &quot; + sender.toString())
8168     *         .setContentText(subject)
8169     *         .setSmallIcon(R.drawable.new_mail)
8170     *         .extend(new Notification.WearableExtender()
8171     *                 .setContentIcon(R.drawable.new_mail))
8172     *         .build();
8173     * NotificationManager notificationManger =
8174     *         (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
8175     * notificationManger.notify(0, notif);</pre>
8176     *
8177     * <p>Wearable extensions can be accessed on an existing notification by using the
8178     * {@code WearableExtender(Notification)} constructor,
8179     * and then using the {@code get} methods to access values.
8180     *
8181     * <pre class="prettyprint">
8182     * Notification.WearableExtender wearableExtender = new Notification.WearableExtender(
8183     *         notification);
8184     * List&lt;Notification&gt; pages = wearableExtender.getPages();</pre>
8185     */
8186    public static final class WearableExtender implements Extender {
8187        /**
8188         * Sentinel value for an action index that is unset.
8189         */
8190        public static final int UNSET_ACTION_INDEX = -1;
8191
8192        /**
8193         * Size value for use with {@link #setCustomSizePreset} to show this notification with
8194         * default sizing.
8195         * <p>For custom display notifications created using {@link #setDisplayIntent},
8196         * the default is {@link #SIZE_MEDIUM}. All other notifications size automatically based
8197         * on their content.
8198         */
8199        public static final int SIZE_DEFAULT = 0;
8200
8201        /**
8202         * Size value for use with {@link #setCustomSizePreset} to show this notification
8203         * with an extra small size.
8204         * <p>This value is only applicable for custom display notifications created using
8205         * {@link #setDisplayIntent}.
8206         */
8207        public static final int SIZE_XSMALL = 1;
8208
8209        /**
8210         * Size value for use with {@link #setCustomSizePreset} to show this notification
8211         * with a small size.
8212         * <p>This value is only applicable for custom display notifications created using
8213         * {@link #setDisplayIntent}.
8214         */
8215        public static final int SIZE_SMALL = 2;
8216
8217        /**
8218         * Size value for use with {@link #setCustomSizePreset} to show this notification
8219         * with a medium size.
8220         * <p>This value is only applicable for custom display notifications created using
8221         * {@link #setDisplayIntent}.
8222         */
8223        public static final int SIZE_MEDIUM = 3;
8224
8225        /**
8226         * Size value for use with {@link #setCustomSizePreset} to show this notification
8227         * with a large size.
8228         * <p>This value is only applicable for custom display notifications created using
8229         * {@link #setDisplayIntent}.
8230         */
8231        public static final int SIZE_LARGE = 4;
8232
8233        /**
8234         * Size value for use with {@link #setCustomSizePreset} to show this notification
8235         * full screen.
8236         * <p>This value is only applicable for custom display notifications created using
8237         * {@link #setDisplayIntent}.
8238         */
8239        public static final int SIZE_FULL_SCREEN = 5;
8240
8241        /**
8242         * Sentinel value for use with {@link #setHintScreenTimeout} to keep the screen on for a
8243         * short amount of time when this notification is displayed on the screen. This
8244         * is the default value.
8245         */
8246        public static final int SCREEN_TIMEOUT_SHORT = 0;
8247
8248        /**
8249         * Sentinel value for use with {@link #setHintScreenTimeout} to keep the screen on
8250         * for a longer amount of time when this notification is displayed on the screen.
8251         */
8252        public static final int SCREEN_TIMEOUT_LONG = -1;
8253
8254        /** Notification extra which contains wearable extensions */
8255        private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS";
8256
8257        // Keys within EXTRA_WEARABLE_EXTENSIONS for wearable options.
8258        private static final String KEY_ACTIONS = "actions";
8259        private static final String KEY_FLAGS = "flags";
8260        private static final String KEY_DISPLAY_INTENT = "displayIntent";
8261        private static final String KEY_PAGES = "pages";
8262        private static final String KEY_BACKGROUND = "background";
8263        private static final String KEY_CONTENT_ICON = "contentIcon";
8264        private static final String KEY_CONTENT_ICON_GRAVITY = "contentIconGravity";
8265        private static final String KEY_CONTENT_ACTION_INDEX = "contentActionIndex";
8266        private static final String KEY_CUSTOM_SIZE_PRESET = "customSizePreset";
8267        private static final String KEY_CUSTOM_CONTENT_HEIGHT = "customContentHeight";
8268        private static final String KEY_GRAVITY = "gravity";
8269        private static final String KEY_HINT_SCREEN_TIMEOUT = "hintScreenTimeout";
8270        private static final String KEY_DISMISSAL_ID = "dismissalId";
8271        private static final String KEY_BRIDGE_TAG = "bridgeTag";
8272
8273        // Flags bitwise-ored to mFlags
8274        private static final int FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE = 0x1;
8275        private static final int FLAG_HINT_HIDE_ICON = 1 << 1;
8276        private static final int FLAG_HINT_SHOW_BACKGROUND_ONLY = 1 << 2;
8277        private static final int FLAG_START_SCROLL_BOTTOM = 1 << 3;
8278        private static final int FLAG_HINT_AVOID_BACKGROUND_CLIPPING = 1 << 4;
8279        private static final int FLAG_BIG_PICTURE_AMBIENT = 1 << 5;
8280        private static final int FLAG_HINT_CONTENT_INTENT_LAUNCHES_ACTIVITY = 1 << 6;
8281
8282        // Default value for flags integer
8283        private static final int DEFAULT_FLAGS = FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE;
8284
8285        private static final int DEFAULT_CONTENT_ICON_GRAVITY = Gravity.END;
8286        private static final int DEFAULT_GRAVITY = Gravity.BOTTOM;
8287
8288        private ArrayList<Action> mActions = new ArrayList<Action>();
8289        private int mFlags = DEFAULT_FLAGS;
8290        private PendingIntent mDisplayIntent;
8291        private ArrayList<Notification> mPages = new ArrayList<Notification>();
8292        private Bitmap mBackground;
8293        private int mContentIcon;
8294        private int mContentIconGravity = DEFAULT_CONTENT_ICON_GRAVITY;
8295        private int mContentActionIndex = UNSET_ACTION_INDEX;
8296        private int mCustomSizePreset = SIZE_DEFAULT;
8297        private int mCustomContentHeight;
8298        private int mGravity = DEFAULT_GRAVITY;
8299        private int mHintScreenTimeout;
8300        private String mDismissalId;
8301        private String mBridgeTag;
8302
8303        /**
8304         * Create a {@link android.app.Notification.WearableExtender} with default
8305         * options.
8306         */
8307        public WearableExtender() {
8308        }
8309
8310        public WearableExtender(Notification notif) {
8311            Bundle wearableBundle = notif.extras.getBundle(EXTRA_WEARABLE_EXTENSIONS);
8312            if (wearableBundle != null) {
8313                List<Action> actions = wearableBundle.getParcelableArrayList(KEY_ACTIONS);
8314                if (actions != null) {
8315                    mActions.addAll(actions);
8316                }
8317
8318                mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS);
8319                mDisplayIntent = wearableBundle.getParcelable(KEY_DISPLAY_INTENT);
8320
8321                Notification[] pages = getNotificationArrayFromBundle(
8322                        wearableBundle, KEY_PAGES);
8323                if (pages != null) {
8324                    Collections.addAll(mPages, pages);
8325                }
8326
8327                mBackground = wearableBundle.getParcelable(KEY_BACKGROUND);
8328                mContentIcon = wearableBundle.getInt(KEY_CONTENT_ICON);
8329                mContentIconGravity = wearableBundle.getInt(KEY_CONTENT_ICON_GRAVITY,
8330                        DEFAULT_CONTENT_ICON_GRAVITY);
8331                mContentActionIndex = wearableBundle.getInt(KEY_CONTENT_ACTION_INDEX,
8332                        UNSET_ACTION_INDEX);
8333                mCustomSizePreset = wearableBundle.getInt(KEY_CUSTOM_SIZE_PRESET,
8334                        SIZE_DEFAULT);
8335                mCustomContentHeight = wearableBundle.getInt(KEY_CUSTOM_CONTENT_HEIGHT);
8336                mGravity = wearableBundle.getInt(KEY_GRAVITY, DEFAULT_GRAVITY);
8337                mHintScreenTimeout = wearableBundle.getInt(KEY_HINT_SCREEN_TIMEOUT);
8338                mDismissalId = wearableBundle.getString(KEY_DISMISSAL_ID);
8339                mBridgeTag = wearableBundle.getString(KEY_BRIDGE_TAG);
8340            }
8341        }
8342
8343        /**
8344         * Apply wearable extensions to a notification that is being built. This is typically
8345         * called by the {@link android.app.Notification.Builder#extend} method of
8346         * {@link android.app.Notification.Builder}.
8347         */
8348        @Override
8349        public Notification.Builder extend(Notification.Builder builder) {
8350            Bundle wearableBundle = new Bundle();
8351
8352            if (!mActions.isEmpty()) {
8353                wearableBundle.putParcelableArrayList(KEY_ACTIONS, mActions);
8354            }
8355            if (mFlags != DEFAULT_FLAGS) {
8356                wearableBundle.putInt(KEY_FLAGS, mFlags);
8357            }
8358            if (mDisplayIntent != null) {
8359                wearableBundle.putParcelable(KEY_DISPLAY_INTENT, mDisplayIntent);
8360            }
8361            if (!mPages.isEmpty()) {
8362                wearableBundle.putParcelableArray(KEY_PAGES, mPages.toArray(
8363                        new Notification[mPages.size()]));
8364            }
8365            if (mBackground != null) {
8366                wearableBundle.putParcelable(KEY_BACKGROUND, mBackground);
8367            }
8368            if (mContentIcon != 0) {
8369                wearableBundle.putInt(KEY_CONTENT_ICON, mContentIcon);
8370            }
8371            if (mContentIconGravity != DEFAULT_CONTENT_ICON_GRAVITY) {
8372                wearableBundle.putInt(KEY_CONTENT_ICON_GRAVITY, mContentIconGravity);
8373            }
8374            if (mContentActionIndex != UNSET_ACTION_INDEX) {
8375                wearableBundle.putInt(KEY_CONTENT_ACTION_INDEX,
8376                        mContentActionIndex);
8377            }
8378            if (mCustomSizePreset != SIZE_DEFAULT) {
8379                wearableBundle.putInt(KEY_CUSTOM_SIZE_PRESET, mCustomSizePreset);
8380            }
8381            if (mCustomContentHeight != 0) {
8382                wearableBundle.putInt(KEY_CUSTOM_CONTENT_HEIGHT, mCustomContentHeight);
8383            }
8384            if (mGravity != DEFAULT_GRAVITY) {
8385                wearableBundle.putInt(KEY_GRAVITY, mGravity);
8386            }
8387            if (mHintScreenTimeout != 0) {
8388                wearableBundle.putInt(KEY_HINT_SCREEN_TIMEOUT, mHintScreenTimeout);
8389            }
8390            if (mDismissalId != null) {
8391                wearableBundle.putString(KEY_DISMISSAL_ID, mDismissalId);
8392            }
8393            if (mBridgeTag != null) {
8394                wearableBundle.putString(KEY_BRIDGE_TAG, mBridgeTag);
8395            }
8396
8397            builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle);
8398            return builder;
8399        }
8400
8401        @Override
8402        public WearableExtender clone() {
8403            WearableExtender that = new WearableExtender();
8404            that.mActions = new ArrayList<Action>(this.mActions);
8405            that.mFlags = this.mFlags;
8406            that.mDisplayIntent = this.mDisplayIntent;
8407            that.mPages = new ArrayList<Notification>(this.mPages);
8408            that.mBackground = this.mBackground;
8409            that.mContentIcon = this.mContentIcon;
8410            that.mContentIconGravity = this.mContentIconGravity;
8411            that.mContentActionIndex = this.mContentActionIndex;
8412            that.mCustomSizePreset = this.mCustomSizePreset;
8413            that.mCustomContentHeight = this.mCustomContentHeight;
8414            that.mGravity = this.mGravity;
8415            that.mHintScreenTimeout = this.mHintScreenTimeout;
8416            that.mDismissalId = this.mDismissalId;
8417            that.mBridgeTag = this.mBridgeTag;
8418            return that;
8419        }
8420
8421        /**
8422         * Add a wearable action to this notification.
8423         *
8424         * <p>When wearable actions are added using this method, the set of actions that
8425         * show on a wearable device splits from devices that only show actions added
8426         * using {@link android.app.Notification.Builder#addAction}. This allows for customization
8427         * of which actions display on different devices.
8428         *
8429         * @param action the action to add to this notification
8430         * @return this object for method chaining
8431         * @see android.app.Notification.Action
8432         */
8433        public WearableExtender addAction(Action action) {
8434            mActions.add(action);
8435            return this;
8436        }
8437
8438        /**
8439         * Adds wearable actions to this notification.
8440         *
8441         * <p>When wearable actions are added using this method, the set of actions that
8442         * show on a wearable device splits from devices that only show actions added
8443         * using {@link android.app.Notification.Builder#addAction}. This allows for customization
8444         * of which actions display on different devices.
8445         *
8446         * @param actions the actions to add to this notification
8447         * @return this object for method chaining
8448         * @see android.app.Notification.Action
8449         */
8450        public WearableExtender addActions(List<Action> actions) {
8451            mActions.addAll(actions);
8452            return this;
8453        }
8454
8455        /**
8456         * Clear all wearable actions present on this builder.
8457         * @return this object for method chaining.
8458         * @see #addAction
8459         */
8460        public WearableExtender clearActions() {
8461            mActions.clear();
8462            return this;
8463        }
8464
8465        /**
8466         * Get the wearable actions present on this notification.
8467         */
8468        public List<Action> getActions() {
8469            return mActions;
8470        }
8471
8472        /**
8473         * Set an intent to launch inside of an activity view when displaying
8474         * this notification. The {@link PendingIntent} provided should be for an activity.
8475         *
8476         * <pre class="prettyprint">
8477         * Intent displayIntent = new Intent(context, MyDisplayActivity.class);
8478         * PendingIntent displayPendingIntent = PendingIntent.getActivity(context,
8479         *         0, displayIntent, PendingIntent.FLAG_UPDATE_CURRENT);
8480         * Notification notif = new Notification.Builder(context)
8481         *         .extend(new Notification.WearableExtender()
8482         *                 .setDisplayIntent(displayPendingIntent)
8483         *                 .setCustomSizePreset(Notification.WearableExtender.SIZE_MEDIUM))
8484         *         .build();</pre>
8485         *
8486         * <p>The activity to launch needs to allow embedding, must be exported, and
8487         * should have an empty task affinity. It is also recommended to use the device
8488         * default light theme.
8489         *
8490         * <p>Example AndroidManifest.xml entry:
8491         * <pre class="prettyprint">
8492         * &lt;activity android:name=&quot;com.example.MyDisplayActivity&quot;
8493         *     android:exported=&quot;true&quot;
8494         *     android:allowEmbedded=&quot;true&quot;
8495         *     android:taskAffinity=&quot;&quot;
8496         *     android:theme=&quot;@android:style/Theme.DeviceDefault.Light&quot; /&gt;</pre>
8497         *
8498         * @param intent the {@link PendingIntent} for an activity
8499         * @return this object for method chaining
8500         * @see android.app.Notification.WearableExtender#getDisplayIntent
8501         */
8502        public WearableExtender setDisplayIntent(PendingIntent intent) {
8503            mDisplayIntent = intent;
8504            return this;
8505        }
8506
8507        /**
8508         * Get the intent to launch inside of an activity view when displaying this
8509         * notification. This {@code PendingIntent} should be for an activity.
8510         */
8511        public PendingIntent getDisplayIntent() {
8512            return mDisplayIntent;
8513        }
8514
8515        /**
8516         * Add an additional page of content to display with this notification. The current
8517         * notification forms the first page, and pages added using this function form
8518         * subsequent pages. This field can be used to separate a notification into multiple
8519         * sections.
8520         *
8521         * @param page the notification to add as another page
8522         * @return this object for method chaining
8523         * @see android.app.Notification.WearableExtender#getPages
8524         */
8525        public WearableExtender addPage(Notification page) {
8526            mPages.add(page);
8527            return this;
8528        }
8529
8530        /**
8531         * Add additional pages of content to display with this notification. The current
8532         * notification forms the first page, and pages added using this function form
8533         * subsequent pages. This field can be used to separate a notification into multiple
8534         * sections.
8535         *
8536         * @param pages a list of notifications
8537         * @return this object for method chaining
8538         * @see android.app.Notification.WearableExtender#getPages
8539         */
8540        public WearableExtender addPages(List<Notification> pages) {
8541            mPages.addAll(pages);
8542            return this;
8543        }
8544
8545        /**
8546         * Clear all additional pages present on this builder.
8547         * @return this object for method chaining.
8548         * @see #addPage
8549         */
8550        public WearableExtender clearPages() {
8551            mPages.clear();
8552            return this;
8553        }
8554
8555        /**
8556         * Get the array of additional pages of content for displaying this notification. The
8557         * current notification forms the first page, and elements within this array form
8558         * subsequent pages. This field can be used to separate a notification into multiple
8559         * sections.
8560         * @return the pages for this notification
8561         */
8562        public List<Notification> getPages() {
8563            return mPages;
8564        }
8565
8566        /**
8567         * Set a background image to be displayed behind the notification content.
8568         * Contrary to the {@link android.app.Notification.BigPictureStyle}, this background
8569         * will work with any notification style.
8570         *
8571         * @param background the background bitmap
8572         * @return this object for method chaining
8573         * @see android.app.Notification.WearableExtender#getBackground
8574         */
8575        public WearableExtender setBackground(Bitmap background) {
8576            mBackground = background;
8577            return this;
8578        }
8579
8580        /**
8581         * Get a background image to be displayed behind the notification content.
8582         * Contrary to the {@link android.app.Notification.BigPictureStyle}, this background
8583         * will work with any notification style.
8584         *
8585         * @return the background image
8586         * @see android.app.Notification.WearableExtender#setBackground
8587         */
8588        public Bitmap getBackground() {
8589            return mBackground;
8590        }
8591
8592        /**
8593         * Set an icon that goes with the content of this notification.
8594         */
8595        @Deprecated
8596        public WearableExtender setContentIcon(int icon) {
8597            mContentIcon = icon;
8598            return this;
8599        }
8600
8601        /**
8602         * Get an icon that goes with the content of this notification.
8603         */
8604        @Deprecated
8605        public int getContentIcon() {
8606            return mContentIcon;
8607        }
8608
8609        /**
8610         * Set the gravity that the content icon should have within the notification display.
8611         * Supported values include {@link android.view.Gravity#START} and
8612         * {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}.
8613         * @see #setContentIcon
8614         */
8615        @Deprecated
8616        public WearableExtender setContentIconGravity(int contentIconGravity) {
8617            mContentIconGravity = contentIconGravity;
8618            return this;
8619        }
8620
8621        /**
8622         * Get the gravity that the content icon should have within the notification display.
8623         * Supported values include {@link android.view.Gravity#START} and
8624         * {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}.
8625         * @see #getContentIcon
8626         */
8627        @Deprecated
8628        public int getContentIconGravity() {
8629            return mContentIconGravity;
8630        }
8631
8632        /**
8633         * Set an action from this notification's actions to be clickable with the content of
8634         * this notification. This action will no longer display separately from the
8635         * notification's content.
8636         *
8637         * <p>For notifications with multiple pages, child pages can also have content actions
8638         * set, although the list of available actions comes from the main notification and not
8639         * from the child page's notification.
8640         *
8641         * @param actionIndex The index of the action to hoist onto the current notification page.
8642         *                    If wearable actions were added to the main notification, this index
8643         *                    will apply to that list, otherwise it will apply to the regular
8644         *                    actions list.
8645         */
8646        public WearableExtender setContentAction(int actionIndex) {
8647            mContentActionIndex = actionIndex;
8648            return this;
8649        }
8650
8651        /**
8652         * Get the index of the notification action, if any, that was specified as being clickable
8653         * with the content of this notification. This action will no longer display separately
8654         * from the notification's content.
8655         *
8656         * <p>For notifications with multiple pages, child pages can also have content actions
8657         * set, although the list of available actions comes from the main notification and not
8658         * from the child page's notification.
8659         *
8660         * <p>If wearable specific actions were added to the main notification, this index will
8661         * apply to that list, otherwise it will apply to the regular actions list.
8662         *
8663         * @return the action index or {@link #UNSET_ACTION_INDEX} if no action was selected.
8664         */
8665        public int getContentAction() {
8666            return mContentActionIndex;
8667        }
8668
8669        /**
8670         * Set the gravity that this notification should have within the available viewport space.
8671         * Supported values include {@link android.view.Gravity#TOP},
8672         * {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}.
8673         * The default value is {@link android.view.Gravity#BOTTOM}.
8674         */
8675        @Deprecated
8676        public WearableExtender setGravity(int gravity) {
8677            mGravity = gravity;
8678            return this;
8679        }
8680
8681        /**
8682         * Get the gravity that this notification should have within the available viewport space.
8683         * Supported values include {@link android.view.Gravity#TOP},
8684         * {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}.
8685         * The default value is {@link android.view.Gravity#BOTTOM}.
8686         */
8687        @Deprecated
8688        public int getGravity() {
8689            return mGravity;
8690        }
8691
8692        /**
8693         * Set the custom size preset for the display of this notification out of the available
8694         * presets found in {@link android.app.Notification.WearableExtender}, e.g.
8695         * {@link #SIZE_LARGE}.
8696         * <p>Some custom size presets are only applicable for custom display notifications created
8697         * using {@link android.app.Notification.WearableExtender#setDisplayIntent}. Check the
8698         * documentation for the preset in question. See also
8699         * {@link #setCustomContentHeight} and {@link #getCustomSizePreset}.
8700         */
8701        @Deprecated
8702        public WearableExtender setCustomSizePreset(int sizePreset) {
8703            mCustomSizePreset = sizePreset;
8704            return this;
8705        }
8706
8707        /**
8708         * Get the custom size preset for the display of this notification out of the available
8709         * presets found in {@link android.app.Notification.WearableExtender}, e.g.
8710         * {@link #SIZE_LARGE}.
8711         * <p>Some custom size presets are only applicable for custom display notifications created
8712         * using {@link #setDisplayIntent}. Check the documentation for the preset in question.
8713         * See also {@link #setCustomContentHeight} and {@link #setCustomSizePreset}.
8714         */
8715        @Deprecated
8716        public int getCustomSizePreset() {
8717            return mCustomSizePreset;
8718        }
8719
8720        /**
8721         * Set the custom height in pixels for the display of this notification's content.
8722         * <p>This option is only available for custom display notifications created
8723         * using {@link android.app.Notification.WearableExtender#setDisplayIntent}. See also
8724         * {@link android.app.Notification.WearableExtender#setCustomSizePreset} and
8725         * {@link #getCustomContentHeight}.
8726         */
8727        @Deprecated
8728        public WearableExtender setCustomContentHeight(int height) {
8729            mCustomContentHeight = height;
8730            return this;
8731        }
8732
8733        /**
8734         * Get the custom height in pixels for the display of this notification's content.
8735         * <p>This option is only available for custom display notifications created
8736         * using {@link #setDisplayIntent}. See also {@link #setCustomSizePreset} and
8737         * {@link #setCustomContentHeight}.
8738         */
8739        @Deprecated
8740        public int getCustomContentHeight() {
8741            return mCustomContentHeight;
8742        }
8743
8744        /**
8745         * Set whether the scrolling position for the contents of this notification should start
8746         * at the bottom of the contents instead of the top when the contents are too long to
8747         * display within the screen.  Default is false (start scroll at the top).
8748         */
8749        public WearableExtender setStartScrollBottom(boolean startScrollBottom) {
8750            setFlag(FLAG_START_SCROLL_BOTTOM, startScrollBottom);
8751            return this;
8752        }
8753
8754        /**
8755         * Get whether the scrolling position for the contents of this notification should start
8756         * at the bottom of the contents instead of the top when the contents are too long to
8757         * display within the screen. Default is false (start scroll at the top).
8758         */
8759        public boolean getStartScrollBottom() {
8760            return (mFlags & FLAG_START_SCROLL_BOTTOM) != 0;
8761        }
8762
8763        /**
8764         * Set whether the content intent is available when the wearable device is not connected
8765         * to a companion device.  The user can still trigger this intent when the wearable device
8766         * is offline, but a visual hint will indicate that the content intent may not be available.
8767         * Defaults to true.
8768         */
8769        public WearableExtender setContentIntentAvailableOffline(
8770                boolean contentIntentAvailableOffline) {
8771            setFlag(FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE, contentIntentAvailableOffline);
8772            return this;
8773        }
8774
8775        /**
8776         * Get whether the content intent is available when the wearable device is not connected
8777         * to a companion device.  The user can still trigger this intent when the wearable device
8778         * is offline, but a visual hint will indicate that the content intent may not be available.
8779         * Defaults to true.
8780         */
8781        public boolean getContentIntentAvailableOffline() {
8782            return (mFlags & FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE) != 0;
8783        }
8784
8785        /**
8786         * Set a hint that this notification's icon should not be displayed.
8787         * @param hintHideIcon {@code true} to hide the icon, {@code false} otherwise.
8788         * @return this object for method chaining
8789         */
8790        @Deprecated
8791        public WearableExtender setHintHideIcon(boolean hintHideIcon) {
8792            setFlag(FLAG_HINT_HIDE_ICON, hintHideIcon);
8793            return this;
8794        }
8795
8796        /**
8797         * Get a hint that this notification's icon should not be displayed.
8798         * @return {@code true} if this icon should not be displayed, false otherwise.
8799         * The default value is {@code false} if this was never set.
8800         */
8801        @Deprecated
8802        public boolean getHintHideIcon() {
8803            return (mFlags & FLAG_HINT_HIDE_ICON) != 0;
8804        }
8805
8806        /**
8807         * Set a visual hint that only the background image of this notification should be
8808         * displayed, and other semantic content should be hidden. This hint is only applicable
8809         * to sub-pages added using {@link #addPage}.
8810         */
8811        @Deprecated
8812        public WearableExtender setHintShowBackgroundOnly(boolean hintShowBackgroundOnly) {
8813            setFlag(FLAG_HINT_SHOW_BACKGROUND_ONLY, hintShowBackgroundOnly);
8814            return this;
8815        }
8816
8817        /**
8818         * Get a visual hint that only the background image of this notification should be
8819         * displayed, and other semantic content should be hidden. This hint is only applicable
8820         * to sub-pages added using {@link android.app.Notification.WearableExtender#addPage}.
8821         */
8822        @Deprecated
8823        public boolean getHintShowBackgroundOnly() {
8824            return (mFlags & FLAG_HINT_SHOW_BACKGROUND_ONLY) != 0;
8825        }
8826
8827        /**
8828         * Set a hint that this notification's background should not be clipped if possible,
8829         * and should instead be resized to fully display on the screen, retaining the aspect
8830         * ratio of the image. This can be useful for images like barcodes or qr codes.
8831         * @param hintAvoidBackgroundClipping {@code true} to avoid clipping if possible.
8832         * @return this object for method chaining
8833         */
8834        @Deprecated
8835        public WearableExtender setHintAvoidBackgroundClipping(
8836                boolean hintAvoidBackgroundClipping) {
8837            setFlag(FLAG_HINT_AVOID_BACKGROUND_CLIPPING, hintAvoidBackgroundClipping);
8838            return this;
8839        }
8840
8841        /**
8842         * Get a hint that this notification's background should not be clipped if possible,
8843         * and should instead be resized to fully display on the screen, retaining the aspect
8844         * ratio of the image. This can be useful for images like barcodes or qr codes.
8845         * @return {@code true} if it's ok if the background is clipped on the screen, false
8846         * otherwise. The default value is {@code false} if this was never set.
8847         */
8848        @Deprecated
8849        public boolean getHintAvoidBackgroundClipping() {
8850            return (mFlags & FLAG_HINT_AVOID_BACKGROUND_CLIPPING) != 0;
8851        }
8852
8853        /**
8854         * Set a hint that the screen should remain on for at least this duration when
8855         * this notification is displayed on the screen.
8856         * @param timeout The requested screen timeout in milliseconds. Can also be either
8857         *     {@link #SCREEN_TIMEOUT_SHORT} or {@link #SCREEN_TIMEOUT_LONG}.
8858         * @return this object for method chaining
8859         */
8860        @Deprecated
8861        public WearableExtender setHintScreenTimeout(int timeout) {
8862            mHintScreenTimeout = timeout;
8863            return this;
8864        }
8865
8866        /**
8867         * Get the duration, in milliseconds, that the screen should remain on for
8868         * when this notification is displayed.
8869         * @return the duration in milliseconds if > 0, or either one of the sentinel values
8870         *     {@link #SCREEN_TIMEOUT_SHORT} or {@link #SCREEN_TIMEOUT_LONG}.
8871         */
8872        @Deprecated
8873        public int getHintScreenTimeout() {
8874            return mHintScreenTimeout;
8875        }
8876
8877        /**
8878         * Set a hint that this notification's {@link BigPictureStyle} (if present) should be
8879         * converted to low-bit and displayed in ambient mode, especially useful for barcodes and
8880         * qr codes, as well as other simple black-and-white tickets.
8881         * @param hintAmbientBigPicture {@code true} to enable converstion and ambient.
8882         * @return this object for method chaining
8883         */
8884        public WearableExtender setHintAmbientBigPicture(boolean hintAmbientBigPicture) {
8885            setFlag(FLAG_BIG_PICTURE_AMBIENT, hintAmbientBigPicture);
8886            return this;
8887        }
8888
8889        /**
8890         * Get a hint that this notification's {@link BigPictureStyle} (if present) should be
8891         * converted to low-bit and displayed in ambient mode, especially useful for barcodes and
8892         * qr codes, as well as other simple black-and-white tickets.
8893         * @return {@code true} if it should be displayed in ambient, false otherwise
8894         * otherwise. The default value is {@code false} if this was never set.
8895         */
8896        public boolean getHintAmbientBigPicture() {
8897            return (mFlags & FLAG_BIG_PICTURE_AMBIENT) != 0;
8898        }
8899
8900        /**
8901         * Set a hint that this notification's content intent will launch an {@link Activity}
8902         * directly, telling the platform that it can generate the appropriate transitions.
8903         * @param hintContentIntentLaunchesActivity {@code true} if the content intent will launch
8904         * an activity and transitions should be generated, false otherwise.
8905         * @return this object for method chaining
8906         */
8907        public WearableExtender setHintContentIntentLaunchesActivity(
8908                boolean hintContentIntentLaunchesActivity) {
8909            setFlag(FLAG_HINT_CONTENT_INTENT_LAUNCHES_ACTIVITY, hintContentIntentLaunchesActivity);
8910            return this;
8911        }
8912
8913        /**
8914         * Get a hint that this notification's content intent will launch an {@link Activity}
8915         * directly, telling the platform that it can generate the appropriate transitions
8916         * @return {@code true} if the content intent will launch an activity and transitions should
8917         * be generated, false otherwise. The default value is {@code false} if this was never set.
8918         */
8919        public boolean getHintContentIntentLaunchesActivity() {
8920            return (mFlags & FLAG_HINT_CONTENT_INTENT_LAUNCHES_ACTIVITY) != 0;
8921        }
8922
8923        /**
8924         * Sets the dismissal id for this notification. If a notification is posted with a
8925         * dismissal id, then when that notification is canceled, notifications on other wearables
8926         * and the paired Android phone having that same dismissal id will also be canceled. See
8927         * <a href="{@docRoot}wear/notifications/index.html">Adding Wearable Features to
8928         * Notifications</a> for more information.
8929         * @param dismissalId the dismissal id of the notification.
8930         * @return this object for method chaining
8931         */
8932        public WearableExtender setDismissalId(String dismissalId) {
8933            mDismissalId = dismissalId;
8934            return this;
8935        }
8936
8937        /**
8938         * Returns the dismissal id of the notification.
8939         * @return the dismissal id of the notification or null if it has not been set.
8940         */
8941        public String getDismissalId() {
8942            return mDismissalId;
8943        }
8944
8945        /**
8946         * Sets a bridge tag for this notification. A bridge tag can be set for notifications
8947         * posted from a phone to provide finer-grained control on what notifications are bridged
8948         * to wearables. See <a href="{@docRoot}wear/notifications/index.html">Adding Wearable
8949         * Features to Notifications</a> for more information.
8950         * @param bridgeTag the bridge tag of the notification.
8951         * @return this object for method chaining
8952         */
8953        public WearableExtender setBridgeTag(String bridgeTag) {
8954            mBridgeTag = bridgeTag;
8955            return this;
8956        }
8957
8958        /**
8959         * Returns the bridge tag of the notification.
8960         * @return the bridge tag or null if not present.
8961         */
8962        public String getBridgeTag() {
8963            return mBridgeTag;
8964        }
8965
8966        private void setFlag(int mask, boolean value) {
8967            if (value) {
8968                mFlags |= mask;
8969            } else {
8970                mFlags &= ~mask;
8971            }
8972        }
8973    }
8974
8975    /**
8976     * <p>Helper class to add Android Auto extensions to notifications. To create a notification
8977     * with car extensions:
8978     *
8979     * <ol>
8980     *  <li>Create an {@link Notification.Builder}, setting any desired
8981     *  properties.
8982     *  <li>Create a {@link CarExtender}.
8983     *  <li>Set car-specific properties using the {@code add} and {@code set} methods of
8984     *  {@link CarExtender}.
8985     *  <li>Call {@link Notification.Builder#extend(Notification.Extender)}
8986     *  to apply the extensions to a notification.
8987     * </ol>
8988     *
8989     * <pre class="prettyprint">
8990     * Notification notification = new Notification.Builder(context)
8991     *         ...
8992     *         .extend(new CarExtender()
8993     *                 .set*(...))
8994     *         .build();
8995     * </pre>
8996     *
8997     * <p>Car extensions can be accessed on an existing notification by using the
8998     * {@code CarExtender(Notification)} constructor, and then using the {@code get} methods
8999     * to access values.
9000     */
9001    public static final class CarExtender implements Extender {
9002        private static final String TAG = "CarExtender";
9003
9004        private static final String EXTRA_CAR_EXTENDER = "android.car.EXTENSIONS";
9005        private static final String EXTRA_LARGE_ICON = "large_icon";
9006        private static final String EXTRA_CONVERSATION = "car_conversation";
9007        private static final String EXTRA_COLOR = "app_color";
9008
9009        private Bitmap mLargeIcon;
9010        private UnreadConversation mUnreadConversation;
9011        private int mColor = Notification.COLOR_DEFAULT;
9012
9013        /**
9014         * Create a {@link CarExtender} with default options.
9015         */
9016        public CarExtender() {
9017        }
9018
9019        /**
9020         * Create a {@link CarExtender} from the CarExtender options of an existing Notification.
9021         *
9022         * @param notif The notification from which to copy options.
9023         */
9024        public CarExtender(Notification notif) {
9025            Bundle carBundle = notif.extras == null ?
9026                    null : notif.extras.getBundle(EXTRA_CAR_EXTENDER);
9027            if (carBundle != null) {
9028                mLargeIcon = carBundle.getParcelable(EXTRA_LARGE_ICON);
9029                mColor = carBundle.getInt(EXTRA_COLOR, Notification.COLOR_DEFAULT);
9030
9031                Bundle b = carBundle.getBundle(EXTRA_CONVERSATION);
9032                mUnreadConversation = UnreadConversation.getUnreadConversationFromBundle(b);
9033            }
9034        }
9035
9036        /**
9037         * Apply car extensions to a notification that is being built. This is typically called by
9038         * the {@link Notification.Builder#extend(Notification.Extender)}
9039         * method of {@link Notification.Builder}.
9040         */
9041        @Override
9042        public Notification.Builder extend(Notification.Builder builder) {
9043            Bundle carExtensions = new Bundle();
9044
9045            if (mLargeIcon != null) {
9046                carExtensions.putParcelable(EXTRA_LARGE_ICON, mLargeIcon);
9047            }
9048            if (mColor != Notification.COLOR_DEFAULT) {
9049                carExtensions.putInt(EXTRA_COLOR, mColor);
9050            }
9051
9052            if (mUnreadConversation != null) {
9053                Bundle b = mUnreadConversation.getBundleForUnreadConversation();
9054                carExtensions.putBundle(EXTRA_CONVERSATION, b);
9055            }
9056
9057            builder.getExtras().putBundle(EXTRA_CAR_EXTENDER, carExtensions);
9058            return builder;
9059        }
9060
9061        /**
9062         * Sets the accent color to use when Android Auto presents the notification.
9063         *
9064         * Android Auto uses the color set with {@link Notification.Builder#setColor(int)}
9065         * to accent the displayed notification. However, not all colors are acceptable in an
9066         * automotive setting. This method can be used to override the color provided in the
9067         * notification in such a situation.
9068         */
9069        public CarExtender setColor(@ColorInt int color) {
9070            mColor = color;
9071            return this;
9072        }
9073
9074        /**
9075         * Gets the accent color.
9076         *
9077         * @see #setColor
9078         */
9079        @ColorInt
9080        public int getColor() {
9081            return mColor;
9082        }
9083
9084        /**
9085         * Sets the large icon of the car notification.
9086         *
9087         * If no large icon is set in the extender, Android Auto will display the icon
9088         * specified by {@link Notification.Builder#setLargeIcon(android.graphics.Bitmap)}
9089         *
9090         * @param largeIcon The large icon to use in the car notification.
9091         * @return This object for method chaining.
9092         */
9093        public CarExtender setLargeIcon(Bitmap largeIcon) {
9094            mLargeIcon = largeIcon;
9095            return this;
9096        }
9097
9098        /**
9099         * Gets the large icon used in this car notification, or null if no icon has been set.
9100         *
9101         * @return The large icon for the car notification.
9102         * @see CarExtender#setLargeIcon
9103         */
9104        public Bitmap getLargeIcon() {
9105            return mLargeIcon;
9106        }
9107
9108        /**
9109         * Sets the unread conversation in a message notification.
9110         *
9111         * @param unreadConversation The unread part of the conversation this notification conveys.
9112         * @return This object for method chaining.
9113         */
9114        public CarExtender setUnreadConversation(UnreadConversation unreadConversation) {
9115            mUnreadConversation = unreadConversation;
9116            return this;
9117        }
9118
9119        /**
9120         * Returns the unread conversation conveyed by this notification.
9121         * @see #setUnreadConversation(UnreadConversation)
9122         */
9123        public UnreadConversation getUnreadConversation() {
9124            return mUnreadConversation;
9125        }
9126
9127        /**
9128         * A class which holds the unread messages from a conversation.
9129         */
9130        public static class UnreadConversation {
9131            private static final String KEY_AUTHOR = "author";
9132            private static final String KEY_TEXT = "text";
9133            private static final String KEY_MESSAGES = "messages";
9134            private static final String KEY_REMOTE_INPUT = "remote_input";
9135            private static final String KEY_ON_REPLY = "on_reply";
9136            private static final String KEY_ON_READ = "on_read";
9137            private static final String KEY_PARTICIPANTS = "participants";
9138            private static final String KEY_TIMESTAMP = "timestamp";
9139
9140            private final String[] mMessages;
9141            private final RemoteInput mRemoteInput;
9142            private final PendingIntent mReplyPendingIntent;
9143            private final PendingIntent mReadPendingIntent;
9144            private final String[] mParticipants;
9145            private final long mLatestTimestamp;
9146
9147            UnreadConversation(String[] messages, RemoteInput remoteInput,
9148                    PendingIntent replyPendingIntent, PendingIntent readPendingIntent,
9149                    String[] participants, long latestTimestamp) {
9150                mMessages = messages;
9151                mRemoteInput = remoteInput;
9152                mReadPendingIntent = readPendingIntent;
9153                mReplyPendingIntent = replyPendingIntent;
9154                mParticipants = participants;
9155                mLatestTimestamp = latestTimestamp;
9156            }
9157
9158            /**
9159             * Gets the list of messages conveyed by this notification.
9160             */
9161            public String[] getMessages() {
9162                return mMessages;
9163            }
9164
9165            /**
9166             * Gets the remote input that will be used to convey the response to a message list, or
9167             * null if no such remote input exists.
9168             */
9169            public RemoteInput getRemoteInput() {
9170                return mRemoteInput;
9171            }
9172
9173            /**
9174             * Gets the pending intent that will be triggered when the user replies to this
9175             * notification.
9176             */
9177            public PendingIntent getReplyPendingIntent() {
9178                return mReplyPendingIntent;
9179            }
9180
9181            /**
9182             * Gets the pending intent that Android Auto will send after it reads aloud all messages
9183             * in this object's message list.
9184             */
9185            public PendingIntent getReadPendingIntent() {
9186                return mReadPendingIntent;
9187            }
9188
9189            /**
9190             * Gets the participants in the conversation.
9191             */
9192            public String[] getParticipants() {
9193                return mParticipants;
9194            }
9195
9196            /**
9197             * Gets the firs participant in the conversation.
9198             */
9199            public String getParticipant() {
9200                return mParticipants.length > 0 ? mParticipants[0] : null;
9201            }
9202
9203            /**
9204             * Gets the timestamp of the conversation.
9205             */
9206            public long getLatestTimestamp() {
9207                return mLatestTimestamp;
9208            }
9209
9210            Bundle getBundleForUnreadConversation() {
9211                Bundle b = new Bundle();
9212                String author = null;
9213                if (mParticipants != null && mParticipants.length > 1) {
9214                    author = mParticipants[0];
9215                }
9216                Parcelable[] messages = new Parcelable[mMessages.length];
9217                for (int i = 0; i < messages.length; i++) {
9218                    Bundle m = new Bundle();
9219                    m.putString(KEY_TEXT, mMessages[i]);
9220                    m.putString(KEY_AUTHOR, author);
9221                    messages[i] = m;
9222                }
9223                b.putParcelableArray(KEY_MESSAGES, messages);
9224                if (mRemoteInput != null) {
9225                    b.putParcelable(KEY_REMOTE_INPUT, mRemoteInput);
9226                }
9227                b.putParcelable(KEY_ON_REPLY, mReplyPendingIntent);
9228                b.putParcelable(KEY_ON_READ, mReadPendingIntent);
9229                b.putStringArray(KEY_PARTICIPANTS, mParticipants);
9230                b.putLong(KEY_TIMESTAMP, mLatestTimestamp);
9231                return b;
9232            }
9233
9234            static UnreadConversation getUnreadConversationFromBundle(Bundle b) {
9235                if (b == null) {
9236                    return null;
9237                }
9238                Parcelable[] parcelableMessages = b.getParcelableArray(KEY_MESSAGES);
9239                String[] messages = null;
9240                if (parcelableMessages != null) {
9241                    String[] tmp = new String[parcelableMessages.length];
9242                    boolean success = true;
9243                    for (int i = 0; i < tmp.length; i++) {
9244                        if (!(parcelableMessages[i] instanceof Bundle)) {
9245                            success = false;
9246                            break;
9247                        }
9248                        tmp[i] = ((Bundle) parcelableMessages[i]).getString(KEY_TEXT);
9249                        if (tmp[i] == null) {
9250                            success = false;
9251                            break;
9252                        }
9253                    }
9254                    if (success) {
9255                        messages = tmp;
9256                    } else {
9257                        return null;
9258                    }
9259                }
9260
9261                PendingIntent onRead = b.getParcelable(KEY_ON_READ);
9262                PendingIntent onReply = b.getParcelable(KEY_ON_REPLY);
9263
9264                RemoteInput remoteInput = b.getParcelable(KEY_REMOTE_INPUT);
9265
9266                String[] participants = b.getStringArray(KEY_PARTICIPANTS);
9267                if (participants == null || participants.length != 1) {
9268                    return null;
9269                }
9270
9271                return new UnreadConversation(messages,
9272                        remoteInput,
9273                        onReply,
9274                        onRead,
9275                        participants, b.getLong(KEY_TIMESTAMP));
9276            }
9277        };
9278
9279        /**
9280         * Builder class for {@link CarExtender.UnreadConversation} objects.
9281         */
9282        public static class Builder {
9283            private final List<String> mMessages = new ArrayList<String>();
9284            private final String mParticipant;
9285            private RemoteInput mRemoteInput;
9286            private PendingIntent mReadPendingIntent;
9287            private PendingIntent mReplyPendingIntent;
9288            private long mLatestTimestamp;
9289
9290            /**
9291             * Constructs a new builder for {@link CarExtender.UnreadConversation}.
9292             *
9293             * @param name The name of the other participant in the conversation.
9294             */
9295            public Builder(String name) {
9296                mParticipant = name;
9297            }
9298
9299            /**
9300             * Appends a new unread message to the list of messages for this conversation.
9301             *
9302             * The messages should be added from oldest to newest.
9303             *
9304             * @param message The text of the new unread message.
9305             * @return This object for method chaining.
9306             */
9307            public Builder addMessage(String message) {
9308                mMessages.add(message);
9309                return this;
9310            }
9311
9312            /**
9313             * Sets the pending intent and remote input which will convey the reply to this
9314             * notification.
9315             *
9316             * @param pendingIntent The pending intent which will be triggered on a reply.
9317             * @param remoteInput The remote input parcelable which will carry the reply.
9318             * @return This object for method chaining.
9319             *
9320             * @see CarExtender.UnreadConversation#getRemoteInput
9321             * @see CarExtender.UnreadConversation#getReplyPendingIntent
9322             */
9323            public Builder setReplyAction(
9324                    PendingIntent pendingIntent, RemoteInput remoteInput) {
9325                mRemoteInput = remoteInput;
9326                mReplyPendingIntent = pendingIntent;
9327
9328                return this;
9329            }
9330
9331            /**
9332             * Sets the pending intent that will be sent once the messages in this notification
9333             * are read.
9334             *
9335             * @param pendingIntent The pending intent to use.
9336             * @return This object for method chaining.
9337             */
9338            public Builder setReadPendingIntent(PendingIntent pendingIntent) {
9339                mReadPendingIntent = pendingIntent;
9340                return this;
9341            }
9342
9343            /**
9344             * Sets the timestamp of the most recent message in an unread conversation.
9345             *
9346             * If a messaging notification has been posted by your application and has not
9347             * yet been cancelled, posting a later notification with the same id and tag
9348             * but without a newer timestamp may result in Android Auto not displaying a
9349             * heads up notification for the later notification.
9350             *
9351             * @param timestamp The timestamp of the most recent message in the conversation.
9352             * @return This object for method chaining.
9353             */
9354            public Builder setLatestTimestamp(long timestamp) {
9355                mLatestTimestamp = timestamp;
9356                return this;
9357            }
9358
9359            /**
9360             * Builds a new unread conversation object.
9361             *
9362             * @return The new unread conversation object.
9363             */
9364            public UnreadConversation build() {
9365                String[] messages = mMessages.toArray(new String[mMessages.size()]);
9366                String[] participants = { mParticipant };
9367                return new UnreadConversation(messages, mRemoteInput, mReplyPendingIntent,
9368                        mReadPendingIntent, participants, mLatestTimestamp);
9369            }
9370        }
9371    }
9372
9373    /**
9374     * <p>Helper class to add Android TV extensions to notifications. To create a notification
9375     * with a TV extension:
9376     *
9377     * <ol>
9378     *  <li>Create an {@link Notification.Builder}, setting any desired properties.
9379     *  <li>Create a {@link TvExtender}.
9380     *  <li>Set TV-specific properties using the {@code set} methods of
9381     *  {@link TvExtender}.
9382     *  <li>Call {@link Notification.Builder#extend(Notification.Extender)}
9383     *  to apply the extension to a notification.
9384     * </ol>
9385     *
9386     * <pre class="prettyprint">
9387     * Notification notification = new Notification.Builder(context)
9388     *         ...
9389     *         .extend(new TvExtender()
9390     *                 .set*(...))
9391     *         .build();
9392     * </pre>
9393     *
9394     * <p>TV extensions can be accessed on an existing notification by using the
9395     * {@code TvExtender(Notification)} constructor, and then using the {@code get} methods
9396     * to access values.
9397     *
9398     * @hide
9399     */
9400    @SystemApi
9401    public static final class TvExtender implements Extender {
9402        private static final String TAG = "TvExtender";
9403
9404        private static final String EXTRA_TV_EXTENDER = "android.tv.EXTENSIONS";
9405        private static final String EXTRA_FLAGS = "flags";
9406        private static final String EXTRA_CONTENT_INTENT = "content_intent";
9407        private static final String EXTRA_DELETE_INTENT = "delete_intent";
9408        private static final String EXTRA_CHANNEL_ID = "channel_id";
9409        private static final String EXTRA_SUPPRESS_SHOW_OVER_APPS = "suppressShowOverApps";
9410
9411        // Flags bitwise-ored to mFlags
9412        private static final int FLAG_AVAILABLE_ON_TV = 0x1;
9413
9414        private int mFlags;
9415        private String mChannelId;
9416        private PendingIntent mContentIntent;
9417        private PendingIntent mDeleteIntent;
9418        private boolean mSuppressShowOverApps;
9419
9420        /**
9421         * Create a {@link TvExtender} with default options.
9422         */
9423        public TvExtender() {
9424            mFlags = FLAG_AVAILABLE_ON_TV;
9425        }
9426
9427        /**
9428         * Create a {@link TvExtender} from the TvExtender options of an existing Notification.
9429         *
9430         * @param notif The notification from which to copy options.
9431         */
9432        public TvExtender(Notification notif) {
9433            Bundle bundle = notif.extras == null ?
9434                null : notif.extras.getBundle(EXTRA_TV_EXTENDER);
9435            if (bundle != null) {
9436                mFlags = bundle.getInt(EXTRA_FLAGS);
9437                mChannelId = bundle.getString(EXTRA_CHANNEL_ID);
9438                mSuppressShowOverApps = bundle.getBoolean(EXTRA_SUPPRESS_SHOW_OVER_APPS);
9439                mContentIntent = bundle.getParcelable(EXTRA_CONTENT_INTENT);
9440                mDeleteIntent = bundle.getParcelable(EXTRA_DELETE_INTENT);
9441            }
9442        }
9443
9444        /**
9445         * Apply a TV extension to a notification that is being built. This is typically called by
9446         * the {@link Notification.Builder#extend(Notification.Extender)}
9447         * method of {@link Notification.Builder}.
9448         */
9449        @Override
9450        public Notification.Builder extend(Notification.Builder builder) {
9451            Bundle bundle = new Bundle();
9452
9453            bundle.putInt(EXTRA_FLAGS, mFlags);
9454            bundle.putString(EXTRA_CHANNEL_ID, mChannelId);
9455            bundle.putBoolean(EXTRA_SUPPRESS_SHOW_OVER_APPS, mSuppressShowOverApps);
9456            if (mContentIntent != null) {
9457                bundle.putParcelable(EXTRA_CONTENT_INTENT, mContentIntent);
9458            }
9459
9460            if (mDeleteIntent != null) {
9461                bundle.putParcelable(EXTRA_DELETE_INTENT, mDeleteIntent);
9462            }
9463
9464            builder.getExtras().putBundle(EXTRA_TV_EXTENDER, bundle);
9465            return builder;
9466        }
9467
9468        /**
9469         * Returns true if this notification should be shown on TV. This method return true
9470         * if the notification was extended with a TvExtender.
9471         */
9472        public boolean isAvailableOnTv() {
9473            return (mFlags & FLAG_AVAILABLE_ON_TV) != 0;
9474        }
9475
9476        /**
9477         * Specifies the channel the notification should be delivered on when shown on TV.
9478         * It can be different from the channel that the notification is delivered to when
9479         * posting on a non-TV device.
9480         */
9481        public TvExtender setChannel(String channelId) {
9482            mChannelId = channelId;
9483            return this;
9484        }
9485
9486        /**
9487         * Specifies the channel the notification should be delivered on when shown on TV.
9488         * It can be different from the channel that the notification is delivered to when
9489         * posting on a non-TV device.
9490         */
9491        public TvExtender setChannelId(String channelId) {
9492            mChannelId = channelId;
9493            return this;
9494        }
9495
9496        /** @removed */
9497        @Deprecated
9498        public String getChannel() {
9499            return mChannelId;
9500        }
9501
9502        /**
9503         * Returns the id of the channel this notification posts to on TV.
9504         */
9505        public String getChannelId() {
9506            return mChannelId;
9507        }
9508
9509        /**
9510         * Supplies a {@link PendingIntent} to be sent when the notification is selected on TV.
9511         * If provided, it is used instead of the content intent specified
9512         * at the level of Notification.
9513         */
9514        public TvExtender setContentIntent(PendingIntent intent) {
9515            mContentIntent = intent;
9516            return this;
9517        }
9518
9519        /**
9520         * Returns the TV-specific content intent.  If this method returns null, the
9521         * main content intent on the notification should be used.
9522         *
9523         * @see {@link Notification#contentIntent}
9524         */
9525        public PendingIntent getContentIntent() {
9526            return mContentIntent;
9527        }
9528
9529        /**
9530         * Supplies a {@link PendingIntent} to send when the notification is cleared explicitly
9531         * by the user on TV.  If provided, it is used instead of the delete intent specified
9532         * at the level of Notification.
9533         */
9534        public TvExtender setDeleteIntent(PendingIntent intent) {
9535            mDeleteIntent = intent;
9536            return this;
9537        }
9538
9539        /**
9540         * Returns the TV-specific delete intent.  If this method returns null, the
9541         * main delete intent on the notification should be used.
9542         *
9543         * @see {@link Notification#deleteIntent}
9544         */
9545        public PendingIntent getDeleteIntent() {
9546            return mDeleteIntent;
9547        }
9548
9549        /**
9550         * Specifies whether this notification should suppress showing a message over top of apps
9551         * outside of the launcher.
9552         */
9553        public TvExtender setSuppressShowOverApps(boolean suppress) {
9554            mSuppressShowOverApps = suppress;
9555            return this;
9556        }
9557
9558        /**
9559         * Returns true if this notification should not show messages over top of apps
9560         * outside of the launcher.
9561         */
9562        public boolean getSuppressShowOverApps() {
9563            return mSuppressShowOverApps;
9564        }
9565    }
9566
9567    /**
9568     * Get an array of Notification objects from a parcelable array bundle field.
9569     * Update the bundle to have a typed array so fetches in the future don't need
9570     * to do an array copy.
9571     */
9572    private static Notification[] getNotificationArrayFromBundle(Bundle bundle, String key) {
9573        Parcelable[] array = bundle.getParcelableArray(key);
9574        if (array instanceof Notification[] || array == null) {
9575            return (Notification[]) array;
9576        }
9577        Notification[] typedArray = Arrays.copyOf(array, array.length,
9578                Notification[].class);
9579        bundle.putParcelableArray(key, typedArray);
9580        return typedArray;
9581    }
9582
9583    private static class BuilderRemoteViews extends RemoteViews {
9584        public BuilderRemoteViews(Parcel parcel) {
9585            super(parcel);
9586        }
9587
9588        public BuilderRemoteViews(ApplicationInfo appInfo, int layoutId) {
9589            super(appInfo, layoutId);
9590        }
9591
9592        @Override
9593        public BuilderRemoteViews clone() {
9594            Parcel p = Parcel.obtain();
9595            writeToParcel(p, 0);
9596            p.setDataPosition(0);
9597            BuilderRemoteViews brv = new BuilderRemoteViews(p);
9598            p.recycle();
9599            return brv;
9600        }
9601    }
9602
9603    /**
9604     * A result object where information about the template that was created is saved.
9605     */
9606    private static class TemplateBindResult {
9607        int mIconMarginEnd;
9608
9609        /**
9610         * Get the margin end that needs to be added to any fields that may overlap
9611         * with the right actions.
9612         */
9613        public int getIconMarginEnd() {
9614            return mIconMarginEnd;
9615        }
9616
9617        public void setIconMarginEnd(int iconMarginEnd) {
9618            this.mIconMarginEnd = iconMarginEnd;
9619        }
9620    }
9621
9622    private static class StandardTemplateParams {
9623        boolean hasProgress = true;
9624        boolean ambient = false;
9625        CharSequence title;
9626        CharSequence text;
9627        CharSequence headerTextSecondary;
9628        int maxRemoteInputHistory = Style.MAX_REMOTE_INPUT_HISTORY_LINES;
9629        boolean hideLargeIcon;
9630        boolean hideReplyIcon;
9631
9632        final StandardTemplateParams reset() {
9633            hasProgress = true;
9634            ambient = false;
9635            title = null;
9636            text = null;
9637            headerTextSecondary = null;
9638            maxRemoteInputHistory = Style.MAX_REMOTE_INPUT_HISTORY_LINES;
9639            return this;
9640        }
9641
9642        final StandardTemplateParams hasProgress(boolean hasProgress) {
9643            this.hasProgress = hasProgress;
9644            return this;
9645        }
9646
9647        final StandardTemplateParams title(CharSequence title) {
9648            this.title = title;
9649            return this;
9650        }
9651
9652        final StandardTemplateParams text(CharSequence text) {
9653            this.text = text;
9654            return this;
9655        }
9656
9657        final StandardTemplateParams headerTextSecondary(CharSequence text) {
9658            this.headerTextSecondary = text;
9659            return this;
9660        }
9661
9662        final StandardTemplateParams hideLargeIcon(boolean hideLargeIcon) {
9663            this.hideLargeIcon = hideLargeIcon;
9664            return this;
9665        }
9666
9667        final StandardTemplateParams hideReplyIcon(boolean hideReplyIcon) {
9668            this.hideReplyIcon = hideReplyIcon;
9669            return this;
9670        }
9671
9672        final StandardTemplateParams ambient(boolean ambient) {
9673            Preconditions.checkState(title == null && text == null, "must set ambient before text");
9674            this.ambient = ambient;
9675            return this;
9676        }
9677
9678        final StandardTemplateParams fillTextsFrom(Builder b) {
9679            Bundle extras = b.mN.extras;
9680            this.title = b.processLegacyText(extras.getCharSequence(EXTRA_TITLE), ambient);
9681
9682            // Big text notifications should contain their content when viewed in ambient mode.
9683            CharSequence text = extras.getCharSequence(EXTRA_BIG_TEXT);
9684            if (!ambient || TextUtils.isEmpty(text)) {
9685                text = extras.getCharSequence(EXTRA_TEXT);
9686            }
9687            this.text = b.processLegacyText(text, ambient);
9688            return this;
9689        }
9690
9691        /**
9692         * Set the maximum lines of remote input history lines allowed.
9693         * @param maxRemoteInputHistory The number of lines.
9694         * @return The builder for method chaining.
9695         */
9696        public StandardTemplateParams setMaxRemoteInputHistory(int maxRemoteInputHistory) {
9697            this.maxRemoteInputHistory = maxRemoteInputHistory;
9698            return this;
9699        }
9700    }
9701}
9702