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