Notification.java revision 18896e08938bc1e1fcb7928996803af935b826b7
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 android.annotation.ColorInt;
20import android.annotation.DrawableRes;
21import android.annotation.IntDef;
22import android.annotation.SdkConstant;
23import android.annotation.SdkConstant.SdkConstantType;
24import android.content.Context;
25import android.content.Intent;
26import android.content.pm.ApplicationInfo;
27import android.content.pm.PackageManager.NameNotFoundException;
28import android.content.res.ColorStateList;
29import android.graphics.Bitmap;
30import android.graphics.Canvas;
31import android.graphics.PorterDuff;
32import android.graphics.drawable.Drawable;
33import android.graphics.drawable.Icon;
34import android.media.AudioAttributes;
35import android.media.AudioManager;
36import android.media.session.MediaSession;
37import android.net.Uri;
38import android.os.BadParcelableException;
39import android.os.Build;
40import android.os.Bundle;
41import android.os.Parcel;
42import android.os.Parcelable;
43import android.os.SystemClock;
44import android.os.UserHandle;
45import android.text.TextUtils;
46import android.util.Log;
47import android.util.MathUtils;
48import android.util.TypedValue;
49import android.view.Gravity;
50import android.view.View;
51import android.widget.ProgressBar;
52import android.widget.RemoteViews;
53
54import com.android.internal.R;
55import com.android.internal.util.NotificationColorUtil;
56
57import java.lang.annotation.Retention;
58import java.lang.annotation.RetentionPolicy;
59import java.lang.reflect.Constructor;
60import java.text.NumberFormat;
61import java.util.ArrayList;
62import java.util.Arrays;
63import java.util.Collections;
64import java.util.List;
65import java.util.Objects;
66
67/**
68 * A class that represents how a persistent notification is to be presented to
69 * the user using the {@link android.app.NotificationManager}.
70 *
71 * <p>The {@link Notification.Builder Notification.Builder} has been added to make it
72 * easier to construct Notifications.</p>
73 *
74 * <div class="special reference">
75 * <h3>Developer Guides</h3>
76 * <p>For a guide to creating notifications, read the
77 * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a>
78 * developer guide.</p>
79 * </div>
80 */
81public class Notification implements Parcelable
82{
83    private static final String TAG = "Notification";
84
85    /**
86     * An activity that provides a user interface for adjusting notification preferences for its
87     * containing application. Optional but recommended for apps that post
88     * {@link android.app.Notification Notifications}.
89     */
90    @SdkConstant(SdkConstantType.INTENT_CATEGORY)
91    public static final String INTENT_CATEGORY_NOTIFICATION_PREFERENCES
92            = "android.intent.category.NOTIFICATION_PREFERENCES";
93
94    /**
95     * Use all default values (where applicable).
96     */
97    public static final int DEFAULT_ALL = ~0;
98
99    /**
100     * Use the default notification sound. This will ignore any given
101     * {@link #sound}.
102     *
103     * <p>
104     * A notification that is noisy is more likely to be presented as a heads-up notification.
105     * </p>
106     *
107     * @see #defaults
108     */
109
110    public static final int DEFAULT_SOUND = 1;
111
112    /**
113     * Use the default notification vibrate. This will ignore any given
114     * {@link #vibrate}. Using phone vibration requires the
115     * {@link android.Manifest.permission#VIBRATE VIBRATE} permission.
116     *
117     * <p>
118     * A notification that vibrates is more likely to be presented as a heads-up notification.
119     * </p>
120     *
121     * @see #defaults
122     */
123
124    public static final int DEFAULT_VIBRATE = 2;
125
126    /**
127     * Use the default notification lights. This will ignore the
128     * {@link #FLAG_SHOW_LIGHTS} bit, and {@link #ledARGB}, {@link #ledOffMS}, or
129     * {@link #ledOnMS}.
130     *
131     * @see #defaults
132     */
133
134    public static final int DEFAULT_LIGHTS = 4;
135
136    /**
137     * Maximum length of CharSequences accepted by Builder and friends.
138     *
139     * <p>
140     * Avoids spamming the system with overly large strings such as full e-mails.
141     */
142    private static final int MAX_CHARSEQUENCE_LENGTH = 5 * 1024;
143
144    /**
145     * A timestamp related to this notification, in milliseconds since the epoch.
146     *
147     * Default value: {@link System#currentTimeMillis() Now}.
148     *
149     * Choose a timestamp that will be most relevant to the user. For most finite events, this
150     * corresponds to the time the event happened (or will happen, in the case of events that have
151     * yet to occur but about which the user is being informed). Indefinite events should be
152     * timestamped according to when the activity began.
153     *
154     * Some examples:
155     *
156     * <ul>
157     *   <li>Notification of a new chat message should be stamped when the message was received.</li>
158     *   <li>Notification of an ongoing file download (with a progress bar, for example) should be stamped when the download started.</li>
159     *   <li>Notification of a completed file download should be stamped when the download finished.</li>
160     *   <li>Notification of an upcoming meeting should be stamped with the time the meeting will begin (that is, in the future).</li>
161     *   <li>Notification of an ongoing stopwatch (increasing timer) should be stamped with the watch's start time.
162     *   <li>Notification of an ongoing countdown timer should be stamped with the timer's end time.
163     * </ul>
164     *
165     */
166    public long when;
167
168    /**
169     * The resource id of a drawable to use as the icon in the status bar.
170     *
171     * @deprecated Use {@link Builder#setSmallIcon(Icon)} instead.
172     */
173    @Deprecated
174    @DrawableRes
175    public int icon;
176
177    /**
178     * If the icon in the status bar is to have more than one level, you can set this.  Otherwise,
179     * leave it at its default value of 0.
180     *
181     * @see android.widget.ImageView#setImageLevel
182     * @see android.graphics.drawable.Drawable#setLevel
183     */
184    public int iconLevel;
185
186    /**
187     * The number of events that this notification represents. For example, in a new mail
188     * notification, this could be the number of unread messages.
189     *
190     * The system may or may not use this field to modify the appearance of the notification. For
191     * example, before {@link android.os.Build.VERSION_CODES#HONEYCOMB}, this number was
192     * superimposed over the icon in the status bar. Starting with
193     * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, the template used by
194     * {@link Notification.Builder} has displayed the number in the expanded notification view.
195     *
196     * If the number is 0 or negative, it is never shown.
197     */
198    public int number;
199
200    /**
201     * The intent to execute when the expanded status entry is clicked.  If
202     * this is an activity, it must include the
203     * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires
204     * that you take care of task management as described in the
205     * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back
206     * Stack</a> document.  In particular, make sure to read the notification section
207     * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html#HandlingNotifications">Handling
208     * Notifications</a> for the correct ways to launch an application from a
209     * notification.
210     */
211    public PendingIntent contentIntent;
212
213    /**
214     * The intent to execute when the notification is explicitly dismissed by the user, either with
215     * the "Clear All" button or by swiping it away individually.
216     *
217     * This probably shouldn't be launching an activity since several of those will be sent
218     * at the same time.
219     */
220    public PendingIntent deleteIntent;
221
222    /**
223     * An intent to launch instead of posting the notification to the status bar.
224     *
225     * <p>
226     * The system UI may choose to display a heads-up notification, instead of
227     * launching this intent, while the user is using the device.
228     * </p>
229     *
230     * @see Notification.Builder#setFullScreenIntent
231     */
232    public PendingIntent fullScreenIntent;
233
234    /**
235     * Text that summarizes this notification for accessibility services.
236     *
237     * As of the L release, this text is no longer shown on screen, but it is still useful to
238     * accessibility services (where it serves as an audible announcement of the notification's
239     * appearance).
240     *
241     * @see #tickerView
242     */
243    public CharSequence tickerText;
244
245    /**
246     * Formerly, a view showing the {@link #tickerText}.
247     *
248     * No longer displayed in the status bar as of API 21.
249     */
250    @Deprecated
251    public RemoteViews tickerView;
252
253    /**
254     * The view that will represent this notification in the notification list (which is pulled
255     * down from the status bar).
256     *
257     * As of N, this field is not used. The notification view is determined by the inputs to
258     * {@link Notification.Builder}; a custom RemoteViews can optionally be
259     * supplied with {@link Notification.Builder#setCustomContentView(RemoteViews)}.
260     */
261    @Deprecated
262    public RemoteViews contentView;
263
264    /**
265     * A large-format version of {@link #contentView}, giving the Notification an
266     * opportunity to show more detail. The system UI may choose to show this
267     * instead of the normal content view at its discretion.
268     *
269     * As of N, this field is not used. The expanded notification view is determined by the
270     * inputs to {@link Notification.Builder}; a custom RemoteViews can optionally be
271     * supplied with {@link Notification.Builder#setCustomBigContentView(RemoteViews)}.
272     */
273    @Deprecated
274    public RemoteViews bigContentView;
275
276
277    /**
278     * A medium-format version of {@link #contentView}, providing the Notification an
279     * opportunity to add action buttons to contentView. At its discretion, the system UI may
280     * choose to show this as a heads-up notification, which will pop up so the user can see
281     * it without leaving their current activity.
282     *
283     * As of N, this field is not used. The heads-up notification view is determined by the
284     * inputs to {@link Notification.Builder}; a custom RemoteViews can optionally be
285     * supplied with {@link Notification.Builder#setCustomHeadsUpContentView(RemoteViews)}.
286     */
287    @Deprecated
288    public RemoteViews headsUpContentView;
289
290    /**
291     * A large bitmap to be shown in the notification content area.
292     *
293     * @deprecated Use {@link Builder#setLargeIcon(Icon)} instead.
294     */
295    @Deprecated
296    public Bitmap largeIcon;
297
298    /**
299     * The sound to play.
300     *
301     * <p>
302     * A notification that is noisy is more likely to be presented as a heads-up notification.
303     * </p>
304     *
305     * <p>
306     * To play the default notification sound, see {@link #defaults}.
307     * </p>
308     */
309    public Uri sound;
310
311    /**
312     * Use this constant as the value for audioStreamType to request that
313     * the default stream type for notifications be used.  Currently the
314     * default stream type is {@link AudioManager#STREAM_NOTIFICATION}.
315     *
316     * @deprecated Use {@link #audioAttributes} instead.
317     */
318    @Deprecated
319    public static final int STREAM_DEFAULT = -1;
320
321    /**
322     * The audio stream type to use when playing the sound.
323     * Should be one of the STREAM_ constants from
324     * {@link android.media.AudioManager}.
325     *
326     * @deprecated Use {@link #audioAttributes} instead.
327     */
328    @Deprecated
329    public int audioStreamType = STREAM_DEFAULT;
330
331    /**
332     * The default value of {@link #audioAttributes}.
333     */
334    public static final AudioAttributes AUDIO_ATTRIBUTES_DEFAULT = new AudioAttributes.Builder()
335            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
336            .setUsage(AudioAttributes.USAGE_NOTIFICATION)
337            .build();
338
339    /**
340     * The {@link AudioAttributes audio attributes} to use when playing the sound.
341     */
342    public AudioAttributes audioAttributes = AUDIO_ATTRIBUTES_DEFAULT;
343
344    /**
345     * The pattern with which to vibrate.
346     *
347     * <p>
348     * To vibrate the default pattern, see {@link #defaults}.
349     * </p>
350     *
351     * <p>
352     * A notification that vibrates is more likely to be presented as a heads-up notification.
353     * </p>
354     *
355     * @see android.os.Vibrator#vibrate(long[],int)
356     */
357    public long[] vibrate;
358
359    /**
360     * The color of the led.  The hardware will do its best approximation.
361     *
362     * @see #FLAG_SHOW_LIGHTS
363     * @see #flags
364     */
365    @ColorInt
366    public int ledARGB;
367
368    /**
369     * The number of milliseconds for the LED to be on while it's flashing.
370     * The hardware will do its best approximation.
371     *
372     * @see #FLAG_SHOW_LIGHTS
373     * @see #flags
374     */
375    public int ledOnMS;
376
377    /**
378     * The number of milliseconds for the LED to be off while it's flashing.
379     * The hardware will do its best approximation.
380     *
381     * @see #FLAG_SHOW_LIGHTS
382     * @see #flags
383     */
384    public int ledOffMS;
385
386    /**
387     * Specifies which values should be taken from the defaults.
388     * <p>
389     * To set, OR the desired from {@link #DEFAULT_SOUND},
390     * {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}. For all default
391     * values, use {@link #DEFAULT_ALL}.
392     * </p>
393     */
394    public int defaults;
395
396    /**
397     * Bit to be bitwise-ored into the {@link #flags} field that should be
398     * set if you want the LED on for this notification.
399     * <ul>
400     * <li>To turn the LED off, pass 0 in the alpha channel for colorARGB
401     *      or 0 for both ledOnMS and ledOffMS.</li>
402     * <li>To turn the LED on, pass 1 for ledOnMS and 0 for ledOffMS.</li>
403     * <li>To flash the LED, pass the number of milliseconds that it should
404     *      be on and off to ledOnMS and ledOffMS.</li>
405     * </ul>
406     * <p>
407     * Since hardware varies, you are not guaranteed that any of the values
408     * you pass are honored exactly.  Use the system defaults (TODO) if possible
409     * because they will be set to values that work on any given hardware.
410     * <p>
411     * The alpha channel must be set for forward compatibility.
412     *
413     */
414    public static final int FLAG_SHOW_LIGHTS        = 0x00000001;
415
416    /**
417     * Bit to be bitwise-ored into the {@link #flags} field that should be
418     * set if this notification is in reference to something that is ongoing,
419     * like a phone call.  It should not be set if this notification is in
420     * reference to something that happened at a particular point in time,
421     * like a missed phone call.
422     */
423    public static final int FLAG_ONGOING_EVENT      = 0x00000002;
424
425    /**
426     * Bit to be bitwise-ored into the {@link #flags} field that if set,
427     * the audio will be repeated until the notification is
428     * cancelled or the notification window is opened.
429     */
430    public static final int FLAG_INSISTENT          = 0x00000004;
431
432    /**
433     * Bit to be bitwise-ored into the {@link #flags} field that should be
434     * set if you would only like the sound, vibrate and ticker to be played
435     * if the notification was not already showing.
436     */
437    public static final int FLAG_ONLY_ALERT_ONCE    = 0x00000008;
438
439    /**
440     * Bit to be bitwise-ored into the {@link #flags} field that should be
441     * set if the notification should be canceled when it is clicked by the
442     * user.
443     */
444    public static final int FLAG_AUTO_CANCEL        = 0x00000010;
445
446    /**
447     * Bit to be bitwise-ored into the {@link #flags} field that should be
448     * set if the notification should not be canceled when the user clicks
449     * the Clear all button.
450     */
451    public static final int FLAG_NO_CLEAR           = 0x00000020;
452
453    /**
454     * Bit to be bitwise-ored into the {@link #flags} field that should be
455     * set if this notification represents a currently running service.  This
456     * will normally be set for you by {@link Service#startForeground}.
457     */
458    public static final int FLAG_FOREGROUND_SERVICE = 0x00000040;
459
460    /**
461     * Obsolete flag indicating high-priority notifications; use the priority field instead.
462     *
463     * @deprecated Use {@link #priority} with a positive value.
464     */
465    public static final int FLAG_HIGH_PRIORITY      = 0x00000080;
466
467    /**
468     * Bit to be bitswise-ored into the {@link #flags} field that should be
469     * set if this notification is relevant to the current device only
470     * and it is not recommended that it bridge to other devices.
471     */
472    public static final int FLAG_LOCAL_ONLY         = 0x00000100;
473
474    /**
475     * Bit to be bitswise-ored into the {@link #flags} field that should be
476     * set if this notification is the group summary for a group of notifications.
477     * Grouped notifications may display in a cluster or stack on devices which
478     * support such rendering. Requires a group key also be set using {@link Builder#setGroup}.
479     */
480    public static final int FLAG_GROUP_SUMMARY      = 0x00000200;
481
482    public int flags;
483
484    /** @hide */
485    @IntDef({PRIORITY_DEFAULT,PRIORITY_LOW,PRIORITY_MIN,PRIORITY_HIGH,PRIORITY_MAX})
486    @Retention(RetentionPolicy.SOURCE)
487    public @interface Priority {}
488
489    /**
490     * Default notification {@link #priority}. If your application does not prioritize its own
491     * notifications, use this value for all notifications.
492     */
493    public static final int PRIORITY_DEFAULT = 0;
494
495    /**
496     * Lower {@link #priority}, for items that are less important. The UI may choose to show these
497     * items smaller, or at a different position in the list, compared with your app's
498     * {@link #PRIORITY_DEFAULT} items.
499     */
500    public static final int PRIORITY_LOW = -1;
501
502    /**
503     * Lowest {@link #priority}; these items might not be shown to the user except under special
504     * circumstances, such as detailed notification logs.
505     */
506    public static final int PRIORITY_MIN = -2;
507
508    /**
509     * Higher {@link #priority}, for more important notifications or alerts. The UI may choose to
510     * show these items larger, or at a different position in notification lists, compared with
511     * your app's {@link #PRIORITY_DEFAULT} items.
512     */
513    public static final int PRIORITY_HIGH = 1;
514
515    /**
516     * Highest {@link #priority}, for your application's most important items that require the
517     * user's prompt attention or input.
518     */
519    public static final int PRIORITY_MAX = 2;
520
521    /**
522     * Relative priority for this notification.
523     *
524     * Priority is an indication of how much of the user's valuable attention should be consumed by
525     * this notification. Low-priority notifications may be hidden from the user in certain
526     * situations, while the user might be interrupted for a higher-priority notification. The
527     * system will make a determination about how to interpret this priority when presenting
528     * the notification.
529     *
530     * <p>
531     * A notification that is at least {@link #PRIORITY_HIGH} is more likely to be presented
532     * as a heads-up notification.
533     * </p>
534     *
535     */
536    @Priority
537    public int priority;
538
539    /**
540     * Accent color (an ARGB integer like the constants in {@link android.graphics.Color})
541     * to be applied by the standard Style templates when presenting this notification.
542     *
543     * The current template design constructs a colorful header image by overlaying the
544     * {@link #icon} image (stenciled in white) atop a field of this color. Alpha components are
545     * ignored.
546     */
547    @ColorInt
548    public int color = COLOR_DEFAULT;
549
550    /**
551     * Special value of {@link #color} telling the system not to decorate this notification with
552     * any special color but instead use default colors when presenting this notification.
553     */
554    @ColorInt
555    public static final int COLOR_DEFAULT = 0; // AKA Color.TRANSPARENT
556
557    /**
558     * Sphere of visibility of this notification, which affects how and when the SystemUI reveals
559     * the notification's presence and contents in untrusted situations (namely, on the secure
560     * lockscreen).
561     *
562     * The default level, {@link #VISIBILITY_PRIVATE}, behaves exactly as notifications have always
563     * done on Android: The notification's {@link #icon} and {@link #tickerText} (if available) are
564     * shown in all situations, but the contents are only available if the device is unlocked for
565     * the appropriate user.
566     *
567     * A more permissive policy can be expressed by {@link #VISIBILITY_PUBLIC}; such a notification
568     * can be read even in an "insecure" context (that is, above a secure lockscreen).
569     * To modify the public version of this notification—for example, to redact some portions—see
570     * {@link Builder#setPublicVersion(Notification)}.
571     *
572     * Finally, a notification can be made {@link #VISIBILITY_SECRET}, which will suppress its icon
573     * and ticker until the user has bypassed the lockscreen.
574     */
575    public int visibility;
576
577    /**
578     * Notification visibility: Show this notification in its entirety on all lockscreens.
579     *
580     * {@see #visibility}
581     */
582    public static final int VISIBILITY_PUBLIC = 1;
583
584    /**
585     * Notification visibility: Show this notification on all lockscreens, but conceal sensitive or
586     * private information on secure lockscreens.
587     *
588     * {@see #visibility}
589     */
590    public static final int VISIBILITY_PRIVATE = 0;
591
592    /**
593     * Notification visibility: Do not reveal any part of this notification on a secure lockscreen.
594     *
595     * {@see #visibility}
596     */
597    public static final int VISIBILITY_SECRET = -1;
598
599    /**
600     * Notification category: incoming call (voice or video) or similar synchronous communication request.
601     */
602    public static final String CATEGORY_CALL = "call";
603
604    /**
605     * Notification category: incoming direct message (SMS, instant message, etc.).
606     */
607    public static final String CATEGORY_MESSAGE = "msg";
608
609    /**
610     * Notification category: asynchronous bulk message (email).
611     */
612    public static final String CATEGORY_EMAIL = "email";
613
614    /**
615     * Notification category: calendar event.
616     */
617    public static final String CATEGORY_EVENT = "event";
618
619    /**
620     * Notification category: promotion or advertisement.
621     */
622    public static final String CATEGORY_PROMO = "promo";
623
624    /**
625     * Notification category: alarm or timer.
626     */
627    public static final String CATEGORY_ALARM = "alarm";
628
629    /**
630     * Notification category: progress of a long-running background operation.
631     */
632    public static final String CATEGORY_PROGRESS = "progress";
633
634    /**
635     * Notification category: social network or sharing update.
636     */
637    public static final String CATEGORY_SOCIAL = "social";
638
639    /**
640     * Notification category: error in background operation or authentication status.
641     */
642    public static final String CATEGORY_ERROR = "err";
643
644    /**
645     * Notification category: media transport control for playback.
646     */
647    public static final String CATEGORY_TRANSPORT = "transport";
648
649    /**
650     * Notification category: system or device status update.  Reserved for system use.
651     */
652    public static final String CATEGORY_SYSTEM = "sys";
653
654    /**
655     * Notification category: indication of running background service.
656     */
657    public static final String CATEGORY_SERVICE = "service";
658
659    /**
660     * Notification category: a specific, timely recommendation for a single thing.
661     * For example, a news app might want to recommend a news story it believes the user will
662     * want to read next.
663     */
664    public static final String CATEGORY_RECOMMENDATION = "recommendation";
665
666    /**
667     * Notification category: ongoing information about device or contextual status.
668     */
669    public static final String CATEGORY_STATUS = "status";
670
671    /**
672     * Notification category: user-scheduled reminder.
673     */
674    public static final String CATEGORY_REMINDER = "reminder";
675
676    /**
677     * One of the predefined notification categories (see the <code>CATEGORY_*</code> constants)
678     * that best describes this Notification.  May be used by the system for ranking and filtering.
679     */
680    public String category;
681
682    private String mGroupKey;
683
684    /**
685     * Get the key used to group this notification into a cluster or stack
686     * with other notifications on devices which support such rendering.
687     */
688    public String getGroup() {
689        return mGroupKey;
690    }
691
692    private String mSortKey;
693
694    /**
695     * Get a sort key that orders this notification among other notifications from the
696     * same package. This can be useful if an external sort was already applied and an app
697     * would like to preserve this. Notifications will be sorted lexicographically using this
698     * value, although providing different priorities in addition to providing sort key may
699     * cause this value to be ignored.
700     *
701     * <p>This sort key can also be used to order members of a notification group. See
702     * {@link Builder#setGroup}.
703     *
704     * @see String#compareTo(String)
705     */
706    public String getSortKey() {
707        return mSortKey;
708    }
709
710    /**
711     * Additional semantic data to be carried around with this Notification.
712     * <p>
713     * The extras keys defined here are intended to capture the original inputs to {@link Builder}
714     * APIs, and are intended to be used by
715     * {@link android.service.notification.NotificationListenerService} implementations to extract
716     * detailed information from notification objects.
717     */
718    public Bundle extras = new Bundle();
719
720    /**
721     * {@link #extras} key: this is the title of the notification,
722     * as supplied to {@link Builder#setContentTitle(CharSequence)}.
723     */
724    public static final String EXTRA_TITLE = "android.title";
725
726    /**
727     * {@link #extras} key: this is the title of the notification when shown in expanded form,
728     * e.g. as supplied to {@link BigTextStyle#setBigContentTitle(CharSequence)}.
729     */
730    public static final String EXTRA_TITLE_BIG = EXTRA_TITLE + ".big";
731
732    /**
733     * {@link #extras} key: this is the main text payload, as supplied to
734     * {@link Builder#setContentText(CharSequence)}.
735     */
736    public static final String EXTRA_TEXT = "android.text";
737
738    /**
739     * {@link #extras} key: this is a third line of text, as supplied to
740     * {@link Builder#setSubText(CharSequence)}.
741     */
742    public static final String EXTRA_SUB_TEXT = "android.subText";
743
744    /**
745     * {@link #extras} key: this is a small piece of additional text as supplied to
746     * {@link Builder#setContentInfo(CharSequence)}.
747     */
748    public static final String EXTRA_INFO_TEXT = "android.infoText";
749
750    /**
751     * {@link #extras} key: this is a line of summary information intended to be shown
752     * alongside expanded notifications, as supplied to (e.g.)
753     * {@link BigTextStyle#setSummaryText(CharSequence)}.
754     */
755    public static final String EXTRA_SUMMARY_TEXT = "android.summaryText";
756
757    /**
758     * {@link #extras} key: this is the longer text shown in the big form of a
759     * {@link BigTextStyle} notification, as supplied to
760     * {@link BigTextStyle#bigText(CharSequence)}.
761     */
762    public static final String EXTRA_BIG_TEXT = "android.bigText";
763
764    /**
765     * {@link #extras} key: this is the resource ID of the notification's main small icon, as
766     * supplied to {@link Builder#setSmallIcon(int)}.
767     */
768    public static final String EXTRA_SMALL_ICON = "android.icon";
769
770    /**
771     * {@link #extras} key: this is a bitmap to be used instead of the small icon when showing the
772     * notification payload, as
773     * supplied to {@link Builder#setLargeIcon(android.graphics.Bitmap)}.
774     */
775    public static final String EXTRA_LARGE_ICON = "android.largeIcon";
776
777    /**
778     * {@link #extras} key: this is a bitmap to be used instead of the one from
779     * {@link Builder#setLargeIcon(android.graphics.Bitmap)} when the notification is
780     * shown in its expanded form, as supplied to
781     * {@link BigPictureStyle#bigLargeIcon(android.graphics.Bitmap)}.
782     */
783    public static final String EXTRA_LARGE_ICON_BIG = EXTRA_LARGE_ICON + ".big";
784
785    /**
786     * {@link #extras} key: this is the progress value supplied to
787     * {@link Builder#setProgress(int, int, boolean)}.
788     */
789    public static final String EXTRA_PROGRESS = "android.progress";
790
791    /**
792     * {@link #extras} key: this is the maximum value supplied to
793     * {@link Builder#setProgress(int, int, boolean)}.
794     */
795    public static final String EXTRA_PROGRESS_MAX = "android.progressMax";
796
797    /**
798     * {@link #extras} key: whether the progress bar is indeterminate, supplied to
799     * {@link Builder#setProgress(int, int, boolean)}.
800     */
801    public static final String EXTRA_PROGRESS_INDETERMINATE = "android.progressIndeterminate";
802
803    /**
804     * {@link #extras} key: whether {@link #when} should be shown as a count-up timer (specifically
805     * a {@link android.widget.Chronometer}) instead of a timestamp, as supplied to
806     * {@link Builder#setUsesChronometer(boolean)}.
807     */
808    public static final String EXTRA_SHOW_CHRONOMETER = "android.showChronometer";
809
810    /**
811     * {@link #extras} key: whether {@link #when} should be shown,
812     * as supplied to {@link Builder#setShowWhen(boolean)}.
813     */
814    public static final String EXTRA_SHOW_WHEN = "android.showWhen";
815
816    /**
817     * {@link #extras} key: this is a bitmap to be shown in {@link BigPictureStyle} expanded
818     * notifications, supplied to {@link BigPictureStyle#bigPicture(android.graphics.Bitmap)}.
819     */
820    public static final String EXTRA_PICTURE = "android.picture";
821
822    /**
823     * {@link #extras} key: An array of CharSequences to show in {@link InboxStyle} expanded
824     * notifications, each of which was supplied to {@link InboxStyle#addLine(CharSequence)}.
825     */
826    public static final String EXTRA_TEXT_LINES = "android.textLines";
827
828    /**
829     * {@link #extras} key: A string representing the name of the specific
830     * {@link android.app.Notification.Style} used to create this notification.
831     */
832    public static final String EXTRA_TEMPLATE = "android.template";
833
834    /**
835     * {@link #extras} key: A String array containing the people that this notification relates to,
836     * each of which was supplied to {@link Builder#addPerson(String)}.
837     */
838    public static final String EXTRA_PEOPLE = "android.people";
839
840    /**
841     * {@link #extras} key: used to provide hints about the appropriateness of
842     * displaying this notification as a heads-up notification.
843     * @hide
844     */
845    public static final String EXTRA_AS_HEADS_UP = "headsup";
846
847    /**
848     * Allow certain system-generated notifications to appear before the device is provisioned.
849     * Only available to notifications coming from the android package.
850     * @hide
851     */
852    public static final String EXTRA_ALLOW_DURING_SETUP = "android.allowDuringSetup";
853
854    /**
855     * {@link #extras} key: A
856     * {@link android.content.ContentUris content URI} pointing to an image that can be displayed
857     * in the background when the notification is selected. The URI must point to an image stream
858     * suitable for passing into
859     * {@link android.graphics.BitmapFactory#decodeStream(java.io.InputStream)
860     * BitmapFactory.decodeStream}; all other content types will be ignored. The content provider
861     * URI used for this purpose must require no permissions to read the image data.
862     */
863    public static final String EXTRA_BACKGROUND_IMAGE_URI = "android.backgroundImageUri";
864
865    /**
866     * {@link #extras} key: A
867     * {@link android.media.session.MediaSession.Token} associated with a
868     * {@link android.app.Notification.MediaStyle} notification.
869     */
870    public static final String EXTRA_MEDIA_SESSION = "android.mediaSession";
871
872    /**
873     * {@link #extras} key: the indices of actions to be shown in the compact view,
874     * as supplied to (e.g.) {@link MediaStyle#setShowActionsInCompactView(int...)}.
875     */
876    public static final String EXTRA_COMPACT_ACTIONS = "android.compactActions";
877
878    /**
879     * {@link #extras} key: the user that built the notification.
880     *
881     * @hide
882     */
883    public static final String EXTRA_ORIGINATING_USERID = "android.originatingUserId";
884
885    /**
886     * @hide
887     */
888    public static final String EXTRA_BUILDER_APPLICATION_INFO = "android.appInfo";
889
890    /**
891     * Value for {@link #EXTRA_AS_HEADS_UP} that indicates this notification should not be
892     * displayed in the heads up space.
893     *
894     * <p>
895     * If this notification has a {@link #fullScreenIntent}, then it will always launch the
896     * full-screen intent when posted.
897     * </p>
898     * @hide
899     */
900    public static final int HEADS_UP_NEVER = 0;
901
902    /**
903     * Default value for {@link #EXTRA_AS_HEADS_UP} that indicates this notification may be
904     * displayed as a heads up.
905     * @hide
906     */
907    public static final int HEADS_UP_ALLOWED = 1;
908
909    /**
910     * Value for {@link #EXTRA_AS_HEADS_UP} that indicates this notification is a
911     * good candidate for display as a heads up.
912     * @hide
913     */
914    public static final int HEADS_UP_REQUESTED = 2;
915
916    private Icon mSmallIcon;
917    private Icon mLargeIcon;
918
919    /**
920     * Structure to encapsulate a named action that can be shown as part of this notification.
921     * It must include an icon, a label, and a {@link PendingIntent} to be fired when the action is
922     * selected by the user.
923     * <p>
924     * Apps should use {@link Notification.Builder#addAction(int, CharSequence, PendingIntent)}
925     * or {@link Notification.Builder#addAction(Notification.Action)}
926     * to attach actions.
927     */
928    public static class Action implements Parcelable {
929        private final Bundle mExtras;
930        private Icon mIcon;
931        private final RemoteInput[] mRemoteInputs;
932
933        /**
934         * Small icon representing the action.
935         *
936         * @deprecated Use {@link Action#getIcon()} instead.
937         */
938        @Deprecated
939        public int icon;
940
941        /**
942         * Title of the action.
943         */
944        public CharSequence title;
945
946        /**
947         * Intent to send when the user invokes this action. May be null, in which case the action
948         * may be rendered in a disabled presentation by the system UI.
949         */
950        public PendingIntent actionIntent;
951
952        private Action(Parcel in) {
953            if (in.readInt() != 0) {
954                mIcon = Icon.CREATOR.createFromParcel(in);
955                if (mIcon.getType() == Icon.TYPE_RESOURCE) {
956                    icon = mIcon.getResId();
957                }
958            }
959            title = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
960            if (in.readInt() == 1) {
961                actionIntent = PendingIntent.CREATOR.createFromParcel(in);
962            }
963            mExtras = in.readBundle();
964            mRemoteInputs = in.createTypedArray(RemoteInput.CREATOR);
965        }
966
967        /**
968         * @deprecated Use {@link android.app.Notification.Action.Builder}.
969         */
970        @Deprecated
971        public Action(int icon, CharSequence title, PendingIntent intent) {
972            this(Icon.createWithResource("", icon), title, intent, new Bundle(), null);
973        }
974
975        private Action(Icon icon, CharSequence title, PendingIntent intent, Bundle extras,
976                RemoteInput[] remoteInputs) {
977            this.mIcon = icon;
978            if (icon != null && icon.getType() == Icon.TYPE_RESOURCE) {
979                this.icon = icon.getResId();
980            }
981            this.title = title;
982            this.actionIntent = intent;
983            this.mExtras = extras != null ? extras : new Bundle();
984            this.mRemoteInputs = remoteInputs;
985        }
986
987        /**
988         * Return an icon representing the action.
989         */
990        public Icon getIcon() {
991            if (mIcon == null && icon != 0) {
992                // you snuck an icon in here without using the builder; let's try to keep it
993                mIcon = Icon.createWithResource("", icon);
994            }
995            return mIcon;
996        }
997
998        /**
999         * Get additional metadata carried around with this Action.
1000         */
1001        public Bundle getExtras() {
1002            return mExtras;
1003        }
1004
1005        /**
1006         * Get the list of inputs to be collected from the user when this action is sent.
1007         * May return null if no remote inputs were added.
1008         */
1009        public RemoteInput[] getRemoteInputs() {
1010            return mRemoteInputs;
1011        }
1012
1013        /**
1014         * Builder class for {@link Action} objects.
1015         */
1016        public static final class Builder {
1017            private final Icon mIcon;
1018            private final CharSequence mTitle;
1019            private final PendingIntent mIntent;
1020            private final Bundle mExtras;
1021            private ArrayList<RemoteInput> mRemoteInputs;
1022
1023            /**
1024             * Construct a new builder for {@link Action} object.
1025             * @param icon icon to show for this action
1026             * @param title the title of the action
1027             * @param intent the {@link PendingIntent} to fire when users trigger this action
1028             */
1029            @Deprecated
1030            public Builder(int icon, CharSequence title, PendingIntent intent) {
1031                this(Icon.createWithResource("", icon), title, intent, new Bundle(), null);
1032            }
1033
1034            /**
1035             * Construct a new builder for {@link Action} object.
1036             * @param icon icon to show for this action
1037             * @param title the title of the action
1038             * @param intent the {@link PendingIntent} to fire when users trigger this action
1039             */
1040            public Builder(Icon icon, CharSequence title, PendingIntent intent) {
1041                this(icon, title, intent, new Bundle(), null);
1042            }
1043
1044            /**
1045             * Construct a new builder for {@link Action} object using the fields from an
1046             * {@link Action}.
1047             * @param action the action to read fields from.
1048             */
1049            public Builder(Action action) {
1050                this(action.getIcon(), action.title, action.actionIntent, new Bundle(action.mExtras),
1051                        action.getRemoteInputs());
1052            }
1053
1054            private Builder(Icon icon, CharSequence title, PendingIntent intent, Bundle extras,
1055                    RemoteInput[] remoteInputs) {
1056                mIcon = icon;
1057                mTitle = title;
1058                mIntent = intent;
1059                mExtras = extras;
1060                if (remoteInputs != null) {
1061                    mRemoteInputs = new ArrayList<RemoteInput>(remoteInputs.length);
1062                    Collections.addAll(mRemoteInputs, remoteInputs);
1063                }
1064            }
1065
1066            /**
1067             * Merge additional metadata into this builder.
1068             *
1069             * <p>Values within the Bundle will replace existing extras values in this Builder.
1070             *
1071             * @see Notification.Action#extras
1072             */
1073            public Builder addExtras(Bundle extras) {
1074                if (extras != null) {
1075                    mExtras.putAll(extras);
1076                }
1077                return this;
1078            }
1079
1080            /**
1081             * Get the metadata Bundle used by this Builder.
1082             *
1083             * <p>The returned Bundle is shared with this Builder.
1084             */
1085            public Bundle getExtras() {
1086                return mExtras;
1087            }
1088
1089            /**
1090             * Add an input to be collected from the user when this action is sent.
1091             * Response values can be retrieved from the fired intent by using the
1092             * {@link RemoteInput#getResultsFromIntent} function.
1093             * @param remoteInput a {@link RemoteInput} to add to the action
1094             * @return this object for method chaining
1095             */
1096            public Builder addRemoteInput(RemoteInput remoteInput) {
1097                if (mRemoteInputs == null) {
1098                    mRemoteInputs = new ArrayList<RemoteInput>();
1099                }
1100                mRemoteInputs.add(remoteInput);
1101                return this;
1102            }
1103
1104            /**
1105             * Apply an extender to this action builder. Extenders may be used to add
1106             * metadata or change options on this builder.
1107             */
1108            public Builder extend(Extender extender) {
1109                extender.extend(this);
1110                return this;
1111            }
1112
1113            /**
1114             * Combine all of the options that have been set and return a new {@link Action}
1115             * object.
1116             * @return the built action
1117             */
1118            public Action build() {
1119                RemoteInput[] remoteInputs = mRemoteInputs != null
1120                        ? mRemoteInputs.toArray(new RemoteInput[mRemoteInputs.size()]) : null;
1121                return new Action(mIcon, mTitle, mIntent, mExtras, remoteInputs);
1122            }
1123        }
1124
1125        @Override
1126        public Action clone() {
1127            return new Action(
1128                    getIcon(),
1129                    title,
1130                    actionIntent, // safe to alias
1131                    new Bundle(mExtras),
1132                    getRemoteInputs());
1133        }
1134        @Override
1135        public int describeContents() {
1136            return 0;
1137        }
1138        @Override
1139        public void writeToParcel(Parcel out, int flags) {
1140            final Icon ic = getIcon();
1141            if (ic != null) {
1142                out.writeInt(1);
1143                ic.writeToParcel(out, 0);
1144            } else {
1145                out.writeInt(0);
1146            }
1147            TextUtils.writeToParcel(title, out, flags);
1148            if (actionIntent != null) {
1149                out.writeInt(1);
1150                actionIntent.writeToParcel(out, flags);
1151            } else {
1152                out.writeInt(0);
1153            }
1154            out.writeBundle(mExtras);
1155            out.writeTypedArray(mRemoteInputs, flags);
1156        }
1157        public static final Parcelable.Creator<Action> CREATOR =
1158                new Parcelable.Creator<Action>() {
1159            public Action createFromParcel(Parcel in) {
1160                return new Action(in);
1161            }
1162            public Action[] newArray(int size) {
1163                return new Action[size];
1164            }
1165        };
1166
1167        /**
1168         * Extender interface for use with {@link Builder#extend}. Extenders may be used to add
1169         * metadata or change options on an action builder.
1170         */
1171        public interface Extender {
1172            /**
1173             * Apply this extender to a notification action builder.
1174             * @param builder the builder to be modified.
1175             * @return the build object for chaining.
1176             */
1177            public Builder extend(Builder builder);
1178        }
1179
1180        /**
1181         * Wearable extender for notification actions. To add extensions to an action,
1182         * create a new {@link android.app.Notification.Action.WearableExtender} object using
1183         * the {@code WearableExtender()} constructor and apply it to a
1184         * {@link android.app.Notification.Action.Builder} using
1185         * {@link android.app.Notification.Action.Builder#extend}.
1186         *
1187         * <pre class="prettyprint">
1188         * Notification.Action action = new Notification.Action.Builder(
1189         *         R.drawable.archive_all, "Archive all", actionIntent)
1190         *         .extend(new Notification.Action.WearableExtender()
1191         *                 .setAvailableOffline(false))
1192         *         .build();</pre>
1193         */
1194        public static final class WearableExtender implements Extender {
1195            /** Notification action extra which contains wearable extensions */
1196            private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS";
1197
1198            // Keys within EXTRA_WEARABLE_EXTENSIONS for wearable options.
1199            private static final String KEY_FLAGS = "flags";
1200            private static final String KEY_IN_PROGRESS_LABEL = "inProgressLabel";
1201            private static final String KEY_CONFIRM_LABEL = "confirmLabel";
1202            private static final String KEY_CANCEL_LABEL = "cancelLabel";
1203
1204            // Flags bitwise-ored to mFlags
1205            private static final int FLAG_AVAILABLE_OFFLINE = 0x1;
1206
1207            // Default value for flags integer
1208            private static final int DEFAULT_FLAGS = FLAG_AVAILABLE_OFFLINE;
1209
1210            private int mFlags = DEFAULT_FLAGS;
1211
1212            private CharSequence mInProgressLabel;
1213            private CharSequence mConfirmLabel;
1214            private CharSequence mCancelLabel;
1215
1216            /**
1217             * Create a {@link android.app.Notification.Action.WearableExtender} with default
1218             * options.
1219             */
1220            public WearableExtender() {
1221            }
1222
1223            /**
1224             * Create a {@link android.app.Notification.Action.WearableExtender} by reading
1225             * wearable options present in an existing notification action.
1226             * @param action the notification action to inspect.
1227             */
1228            public WearableExtender(Action action) {
1229                Bundle wearableBundle = action.getExtras().getBundle(EXTRA_WEARABLE_EXTENSIONS);
1230                if (wearableBundle != null) {
1231                    mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS);
1232                    mInProgressLabel = wearableBundle.getCharSequence(KEY_IN_PROGRESS_LABEL);
1233                    mConfirmLabel = wearableBundle.getCharSequence(KEY_CONFIRM_LABEL);
1234                    mCancelLabel = wearableBundle.getCharSequence(KEY_CANCEL_LABEL);
1235                }
1236            }
1237
1238            /**
1239             * Apply wearable extensions to a notification action that is being built. This is
1240             * typically called by the {@link android.app.Notification.Action.Builder#extend}
1241             * method of {@link android.app.Notification.Action.Builder}.
1242             */
1243            @Override
1244            public Action.Builder extend(Action.Builder builder) {
1245                Bundle wearableBundle = new Bundle();
1246
1247                if (mFlags != DEFAULT_FLAGS) {
1248                    wearableBundle.putInt(KEY_FLAGS, mFlags);
1249                }
1250                if (mInProgressLabel != null) {
1251                    wearableBundle.putCharSequence(KEY_IN_PROGRESS_LABEL, mInProgressLabel);
1252                }
1253                if (mConfirmLabel != null) {
1254                    wearableBundle.putCharSequence(KEY_CONFIRM_LABEL, mConfirmLabel);
1255                }
1256                if (mCancelLabel != null) {
1257                    wearableBundle.putCharSequence(KEY_CANCEL_LABEL, mCancelLabel);
1258                }
1259
1260                builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle);
1261                return builder;
1262            }
1263
1264            @Override
1265            public WearableExtender clone() {
1266                WearableExtender that = new WearableExtender();
1267                that.mFlags = this.mFlags;
1268                that.mInProgressLabel = this.mInProgressLabel;
1269                that.mConfirmLabel = this.mConfirmLabel;
1270                that.mCancelLabel = this.mCancelLabel;
1271                return that;
1272            }
1273
1274            /**
1275             * Set whether this action is available when the wearable device is not connected to
1276             * a companion device. The user can still trigger this action when the wearable device is
1277             * offline, but a visual hint will indicate that the action may not be available.
1278             * Defaults to true.
1279             */
1280            public WearableExtender setAvailableOffline(boolean availableOffline) {
1281                setFlag(FLAG_AVAILABLE_OFFLINE, availableOffline);
1282                return this;
1283            }
1284
1285            /**
1286             * Get whether this action is available when the wearable device is not connected to
1287             * a companion device. The user can still trigger this action when the wearable device is
1288             * offline, but a visual hint will indicate that the action may not be available.
1289             * Defaults to true.
1290             */
1291            public boolean isAvailableOffline() {
1292                return (mFlags & FLAG_AVAILABLE_OFFLINE) != 0;
1293            }
1294
1295            private void setFlag(int mask, boolean value) {
1296                if (value) {
1297                    mFlags |= mask;
1298                } else {
1299                    mFlags &= ~mask;
1300                }
1301            }
1302
1303            /**
1304             * Set a label to display while the wearable is preparing to automatically execute the
1305             * action. This is usually a 'ing' verb ending in ellipsis like "Sending..."
1306             *
1307             * @param label the label to display while the action is being prepared to execute
1308             * @return this object for method chaining
1309             */
1310            public WearableExtender setInProgressLabel(CharSequence label) {
1311                mInProgressLabel = label;
1312                return this;
1313            }
1314
1315            /**
1316             * Get the label to display while the wearable is preparing to automatically execute
1317             * the action. This is usually a 'ing' verb ending in ellipsis like "Sending..."
1318             *
1319             * @return the label to display while the action is being prepared to execute
1320             */
1321            public CharSequence getInProgressLabel() {
1322                return mInProgressLabel;
1323            }
1324
1325            /**
1326             * Set a label to display to confirm that the action should be executed.
1327             * This is usually an imperative verb like "Send".
1328             *
1329             * @param label the label to confirm the action should be executed
1330             * @return this object for method chaining
1331             */
1332            public WearableExtender setConfirmLabel(CharSequence label) {
1333                mConfirmLabel = label;
1334                return this;
1335            }
1336
1337            /**
1338             * Get the label to display to confirm that the action should be executed.
1339             * This is usually an imperative verb like "Send".
1340             *
1341             * @return the label to confirm the action should be executed
1342             */
1343            public CharSequence getConfirmLabel() {
1344                return mConfirmLabel;
1345            }
1346
1347            /**
1348             * Set a label to display to cancel the action.
1349             * This is usually an imperative verb, like "Cancel".
1350             *
1351             * @param label the label to display to cancel the action
1352             * @return this object for method chaining
1353             */
1354            public WearableExtender setCancelLabel(CharSequence label) {
1355                mCancelLabel = label;
1356                return this;
1357            }
1358
1359            /**
1360             * Get the label to display to cancel the action.
1361             * This is usually an imperative verb like "Cancel".
1362             *
1363             * @return the label to display to cancel the action
1364             */
1365            public CharSequence getCancelLabel() {
1366                return mCancelLabel;
1367            }
1368        }
1369    }
1370
1371    /**
1372     * Array of all {@link Action} structures attached to this notification by
1373     * {@link Builder#addAction(int, CharSequence, PendingIntent)}. Mostly useful for instances of
1374     * {@link android.service.notification.NotificationListenerService} that provide an alternative
1375     * interface for invoking actions.
1376     */
1377    public Action[] actions;
1378
1379    /**
1380     * Replacement version of this notification whose content will be shown
1381     * in an insecure context such as atop a secure keyguard. See {@link #visibility}
1382     * and {@link #VISIBILITY_PUBLIC}.
1383     */
1384    public Notification publicVersion;
1385
1386    /**
1387     * Structure to encapsulate a topic that is shown in Notification settings.
1388     * It must include an id and label.
1389     */
1390    public static class Topic implements Parcelable {
1391        private final String id;
1392        private final CharSequence label;
1393
1394        public Topic(String id, CharSequence label) {
1395            this.id = id;
1396            this.label = safeCharSequence(label);
1397        }
1398
1399        private Topic(Parcel in) {
1400            if (in.readInt() != 0) {
1401                id = in.readString();
1402            } else {
1403                id = null;
1404            }
1405            label = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
1406        }
1407
1408        public String getId() {
1409            return id;
1410        }
1411
1412        public CharSequence getLabel() {
1413            return label;
1414        }
1415
1416        @Override
1417        public String toString() {
1418            return new StringBuilder(Topic.class.getSimpleName()).append('[')
1419                    .append("id=").append(id)
1420                    .append(",label=").append(label)
1421                    .append(']').toString();
1422        }
1423
1424        @Override
1425        public boolean equals(Object o) {
1426            if (!(o instanceof Topic)) return false;
1427            if (o == this) return true;
1428            final Topic other = (Topic) o;
1429            return Objects.equals(other.id, id)
1430                    && Objects.equals(other.label, label);
1431        }
1432
1433        @Override
1434        public int hashCode() {
1435            return Objects.hash(id, label);
1436        }
1437
1438        @Override
1439        public Topic clone() {
1440            return new Topic(id, label);
1441        }
1442
1443        @Override
1444        public int describeContents() {
1445            return 0;
1446        }
1447
1448        @Override
1449        public void writeToParcel(Parcel out, int flags) {
1450            if (id != null) {
1451                out.writeInt(1);
1452                out.writeString(id);
1453            } else {
1454                out.writeInt(0);
1455            }
1456            TextUtils.writeToParcel(label, out, flags);
1457        }
1458        public static final Parcelable.Creator<Topic> CREATOR =
1459                new Parcelable.Creator<Topic>() {
1460                    public Topic createFromParcel(Parcel in) {
1461                        return new Topic(in);
1462                    }
1463                    public Topic[] newArray(int size) {
1464                        return new Topic[size];
1465                    }
1466                };
1467    }
1468
1469    private Topic[] topics;
1470
1471    public Topic[] getTopics() {
1472        return topics;
1473    }
1474
1475    /**
1476     * Constructs a Notification object with default values.
1477     * You might want to consider using {@link Builder} instead.
1478     */
1479    public Notification()
1480    {
1481        this.when = System.currentTimeMillis();
1482        this.priority = PRIORITY_DEFAULT;
1483    }
1484
1485    /**
1486     * @hide
1487     */
1488    public Notification(Context context, int icon, CharSequence tickerText, long when,
1489            CharSequence contentTitle, CharSequence contentText, Intent contentIntent)
1490    {
1491        new Builder(context)
1492                .setWhen(when)
1493                .setSmallIcon(icon)
1494                .setTicker(tickerText)
1495                .setContentTitle(contentTitle)
1496                .setContentText(contentText)
1497                .setContentIntent(PendingIntent.getActivity(context, 0, contentIntent, 0))
1498                .buildInto(this);
1499    }
1500
1501    /**
1502     * Constructs a Notification object with the information needed to
1503     * have a status bar icon without the standard expanded view.
1504     *
1505     * @param icon          The resource id of the icon to put in the status bar.
1506     * @param tickerText    The text that flows by in the status bar when the notification first
1507     *                      activates.
1508     * @param when          The time to show in the time field.  In the System.currentTimeMillis
1509     *                      timebase.
1510     *
1511     * @deprecated Use {@link Builder} instead.
1512     */
1513    @Deprecated
1514    public Notification(int icon, CharSequence tickerText, long when)
1515    {
1516        this.icon = icon;
1517        this.tickerText = tickerText;
1518        this.when = when;
1519    }
1520
1521    /**
1522     * Unflatten the notification from a parcel.
1523     */
1524    public Notification(Parcel parcel)
1525    {
1526        int version = parcel.readInt();
1527
1528        when = parcel.readLong();
1529        if (parcel.readInt() != 0) {
1530            mSmallIcon = Icon.CREATOR.createFromParcel(parcel);
1531            if (mSmallIcon.getType() == Icon.TYPE_RESOURCE) {
1532                icon = mSmallIcon.getResId();
1533            }
1534        }
1535        number = parcel.readInt();
1536        if (parcel.readInt() != 0) {
1537            contentIntent = PendingIntent.CREATOR.createFromParcel(parcel);
1538        }
1539        if (parcel.readInt() != 0) {
1540            deleteIntent = PendingIntent.CREATOR.createFromParcel(parcel);
1541        }
1542        if (parcel.readInt() != 0) {
1543            tickerText = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(parcel);
1544        }
1545        if (parcel.readInt() != 0) {
1546            tickerView = RemoteViews.CREATOR.createFromParcel(parcel);
1547        }
1548        if (parcel.readInt() != 0) {
1549            contentView = RemoteViews.CREATOR.createFromParcel(parcel);
1550        }
1551        if (parcel.readInt() != 0) {
1552            mLargeIcon = Icon.CREATOR.createFromParcel(parcel);
1553        }
1554        defaults = parcel.readInt();
1555        flags = parcel.readInt();
1556        if (parcel.readInt() != 0) {
1557            sound = Uri.CREATOR.createFromParcel(parcel);
1558        }
1559
1560        audioStreamType = parcel.readInt();
1561        if (parcel.readInt() != 0) {
1562            audioAttributes = AudioAttributes.CREATOR.createFromParcel(parcel);
1563        }
1564        vibrate = parcel.createLongArray();
1565        ledARGB = parcel.readInt();
1566        ledOnMS = parcel.readInt();
1567        ledOffMS = parcel.readInt();
1568        iconLevel = parcel.readInt();
1569
1570        if (parcel.readInt() != 0) {
1571            fullScreenIntent = PendingIntent.CREATOR.createFromParcel(parcel);
1572        }
1573
1574        priority = parcel.readInt();
1575
1576        category = parcel.readString();
1577
1578        mGroupKey = parcel.readString();
1579
1580        mSortKey = parcel.readString();
1581
1582        extras = parcel.readBundle(); // may be null
1583
1584        actions = parcel.createTypedArray(Action.CREATOR); // may be null
1585
1586        if (parcel.readInt() != 0) {
1587            bigContentView = RemoteViews.CREATOR.createFromParcel(parcel);
1588        }
1589
1590        if (parcel.readInt() != 0) {
1591            headsUpContentView = RemoteViews.CREATOR.createFromParcel(parcel);
1592        }
1593
1594        visibility = parcel.readInt();
1595
1596        if (parcel.readInt() != 0) {
1597            publicVersion = Notification.CREATOR.createFromParcel(parcel);
1598        }
1599
1600        color = parcel.readInt();
1601
1602        topics = parcel.createTypedArray(Topic.CREATOR); // may be null
1603    }
1604
1605    @Override
1606    public Notification clone() {
1607        Notification that = new Notification();
1608        cloneInto(that, true);
1609        return that;
1610    }
1611
1612    /**
1613     * Copy all (or if heavy is false, all except Bitmaps and RemoteViews) members
1614     * of this into that.
1615     * @hide
1616     */
1617    public void cloneInto(Notification that, boolean heavy) {
1618        that.when = this.when;
1619        that.mSmallIcon = this.mSmallIcon;
1620        that.number = this.number;
1621
1622        // PendingIntents are global, so there's no reason (or way) to clone them.
1623        that.contentIntent = this.contentIntent;
1624        that.deleteIntent = this.deleteIntent;
1625        that.fullScreenIntent = this.fullScreenIntent;
1626
1627        if (this.tickerText != null) {
1628            that.tickerText = this.tickerText.toString();
1629        }
1630        if (heavy && this.tickerView != null) {
1631            that.tickerView = this.tickerView.clone();
1632        }
1633        if (heavy && this.contentView != null) {
1634            that.contentView = this.contentView.clone();
1635        }
1636        if (heavy && this.mLargeIcon != null) {
1637            that.mLargeIcon = this.mLargeIcon;
1638        }
1639        that.iconLevel = this.iconLevel;
1640        that.sound = this.sound; // android.net.Uri is immutable
1641        that.audioStreamType = this.audioStreamType;
1642        if (this.audioAttributes != null) {
1643            that.audioAttributes = new AudioAttributes.Builder(this.audioAttributes).build();
1644        }
1645
1646        final long[] vibrate = this.vibrate;
1647        if (vibrate != null) {
1648            final int N = vibrate.length;
1649            final long[] vib = that.vibrate = new long[N];
1650            System.arraycopy(vibrate, 0, vib, 0, N);
1651        }
1652
1653        that.ledARGB = this.ledARGB;
1654        that.ledOnMS = this.ledOnMS;
1655        that.ledOffMS = this.ledOffMS;
1656        that.defaults = this.defaults;
1657
1658        that.flags = this.flags;
1659
1660        that.priority = this.priority;
1661
1662        that.category = this.category;
1663
1664        that.mGroupKey = this.mGroupKey;
1665
1666        that.mSortKey = this.mSortKey;
1667
1668        if (this.extras != null) {
1669            try {
1670                that.extras = new Bundle(this.extras);
1671                // will unparcel
1672                that.extras.size();
1673            } catch (BadParcelableException e) {
1674                Log.e(TAG, "could not unparcel extras from notification: " + this, e);
1675                that.extras = null;
1676            }
1677        }
1678
1679        if (this.actions != null) {
1680            that.actions = new Action[this.actions.length];
1681            for(int i=0; i<this.actions.length; i++) {
1682                that.actions[i] = this.actions[i].clone();
1683            }
1684        }
1685
1686        if (heavy && this.bigContentView != null) {
1687            that.bigContentView = this.bigContentView.clone();
1688        }
1689
1690        if (heavy && this.headsUpContentView != null) {
1691            that.headsUpContentView = this.headsUpContentView.clone();
1692        }
1693
1694        that.visibility = this.visibility;
1695
1696        if (this.publicVersion != null) {
1697            that.publicVersion = new Notification();
1698            this.publicVersion.cloneInto(that.publicVersion, heavy);
1699        }
1700
1701        that.color = this.color;
1702
1703        if (this.topics != null) {
1704            that.topics = new Topic[this.topics.length];
1705            for(int i=0; i<this.topics.length; i++) {
1706                that.topics[i] = this.topics[i].clone();
1707            }
1708        }
1709
1710        if (!heavy) {
1711            that.lightenPayload(); // will clean out extras
1712        }
1713    }
1714
1715    /**
1716     * Removes heavyweight parts of the Notification object for archival or for sending to
1717     * listeners when the full contents are not necessary.
1718     * @hide
1719     */
1720    public final void lightenPayload() {
1721        tickerView = null;
1722        contentView = null;
1723        bigContentView = null;
1724        headsUpContentView = null;
1725        mLargeIcon = null;
1726        if (extras != null) {
1727            extras.remove(Notification.EXTRA_LARGE_ICON);
1728            extras.remove(Notification.EXTRA_LARGE_ICON_BIG);
1729            extras.remove(Notification.EXTRA_PICTURE);
1730            extras.remove(Notification.EXTRA_BIG_TEXT);
1731        }
1732    }
1733
1734    /**
1735     * Make sure this CharSequence is safe to put into a bundle, which basically
1736     * means it had better not be some custom Parcelable implementation.
1737     * @hide
1738     */
1739    public static CharSequence safeCharSequence(CharSequence cs) {
1740        if (cs == null) return cs;
1741        if (cs.length() > MAX_CHARSEQUENCE_LENGTH) {
1742            cs = cs.subSequence(0, MAX_CHARSEQUENCE_LENGTH);
1743        }
1744        if (cs instanceof Parcelable) {
1745            Log.e(TAG, "warning: " + cs.getClass().getCanonicalName()
1746                    + " instance is a custom Parcelable and not allowed in Notification");
1747            return cs.toString();
1748        }
1749
1750        return cs;
1751    }
1752
1753    public int describeContents() {
1754        return 0;
1755    }
1756
1757    /**
1758     * Flatten this notification into a parcel.
1759     */
1760    public void writeToParcel(Parcel parcel, int flags)
1761    {
1762        parcel.writeInt(1);
1763
1764        parcel.writeLong(when);
1765        if (mSmallIcon == null && icon != 0) {
1766            // you snuck an icon in here without using the builder; let's try to keep it
1767            mSmallIcon = Icon.createWithResource("", icon);
1768        }
1769        if (mSmallIcon != null) {
1770            parcel.writeInt(1);
1771            mSmallIcon.writeToParcel(parcel, 0);
1772        } else {
1773            parcel.writeInt(0);
1774        }
1775        parcel.writeInt(number);
1776        if (contentIntent != null) {
1777            parcel.writeInt(1);
1778            contentIntent.writeToParcel(parcel, 0);
1779        } else {
1780            parcel.writeInt(0);
1781        }
1782        if (deleteIntent != null) {
1783            parcel.writeInt(1);
1784            deleteIntent.writeToParcel(parcel, 0);
1785        } else {
1786            parcel.writeInt(0);
1787        }
1788        if (tickerText != null) {
1789            parcel.writeInt(1);
1790            TextUtils.writeToParcel(tickerText, parcel, flags);
1791        } else {
1792            parcel.writeInt(0);
1793        }
1794        if (tickerView != null) {
1795            parcel.writeInt(1);
1796            tickerView.writeToParcel(parcel, 0);
1797        } else {
1798            parcel.writeInt(0);
1799        }
1800        if (contentView != null) {
1801            parcel.writeInt(1);
1802            contentView.writeToParcel(parcel, 0);
1803        } else {
1804            parcel.writeInt(0);
1805        }
1806        if (mLargeIcon != null) {
1807            parcel.writeInt(1);
1808            mLargeIcon.writeToParcel(parcel, 0);
1809        } else {
1810            parcel.writeInt(0);
1811        }
1812
1813        parcel.writeInt(defaults);
1814        parcel.writeInt(this.flags);
1815
1816        if (sound != null) {
1817            parcel.writeInt(1);
1818            sound.writeToParcel(parcel, 0);
1819        } else {
1820            parcel.writeInt(0);
1821        }
1822        parcel.writeInt(audioStreamType);
1823
1824        if (audioAttributes != null) {
1825            parcel.writeInt(1);
1826            audioAttributes.writeToParcel(parcel, 0);
1827        } else {
1828            parcel.writeInt(0);
1829        }
1830
1831        parcel.writeLongArray(vibrate);
1832        parcel.writeInt(ledARGB);
1833        parcel.writeInt(ledOnMS);
1834        parcel.writeInt(ledOffMS);
1835        parcel.writeInt(iconLevel);
1836
1837        if (fullScreenIntent != null) {
1838            parcel.writeInt(1);
1839            fullScreenIntent.writeToParcel(parcel, 0);
1840        } else {
1841            parcel.writeInt(0);
1842        }
1843
1844        parcel.writeInt(priority);
1845
1846        parcel.writeString(category);
1847
1848        parcel.writeString(mGroupKey);
1849
1850        parcel.writeString(mSortKey);
1851
1852        parcel.writeBundle(extras); // null ok
1853
1854        parcel.writeTypedArray(actions, 0); // null ok
1855
1856        if (bigContentView != null) {
1857            parcel.writeInt(1);
1858            bigContentView.writeToParcel(parcel, 0);
1859        } else {
1860            parcel.writeInt(0);
1861        }
1862
1863        if (headsUpContentView != null) {
1864            parcel.writeInt(1);
1865            headsUpContentView.writeToParcel(parcel, 0);
1866        } else {
1867            parcel.writeInt(0);
1868        }
1869
1870        parcel.writeInt(visibility);
1871
1872        if (publicVersion != null) {
1873            parcel.writeInt(1);
1874            publicVersion.writeToParcel(parcel, 0);
1875        } else {
1876            parcel.writeInt(0);
1877        }
1878
1879        parcel.writeInt(color);
1880
1881        parcel.writeTypedArray(topics, 0); // null ok
1882    }
1883
1884    /**
1885     * Parcelable.Creator that instantiates Notification objects
1886     */
1887    public static final Parcelable.Creator<Notification> CREATOR
1888            = new Parcelable.Creator<Notification>()
1889    {
1890        public Notification createFromParcel(Parcel parcel)
1891        {
1892            return new Notification(parcel);
1893        }
1894
1895        public Notification[] newArray(int size)
1896        {
1897            return new Notification[size];
1898        }
1899    };
1900
1901    /**
1902     * Sets the {@link #contentView} field to be a view with the standard "Latest Event"
1903     * layout.
1904     *
1905     * <p>Uses the {@link #icon} and {@link #when} fields to set the icon and time fields
1906     * in the view.</p>
1907     * @param context       The context for your application / activity.
1908     * @param contentTitle The title that goes in the expanded entry.
1909     * @param contentText  The text that goes in the expanded entry.
1910     * @param contentIntent The intent to launch when the user clicks the expanded notification.
1911     * If this is an activity, it must include the
1912     * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires
1913     * that you take care of task management as described in the
1914     * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back
1915     * Stack</a> document.
1916     *
1917     * @deprecated Use {@link Builder} instead.
1918     * @removed
1919     */
1920    @Deprecated
1921    public void setLatestEventInfo(Context context,
1922            CharSequence contentTitle, CharSequence contentText, PendingIntent contentIntent) {
1923        if (context.getApplicationInfo().targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1){
1924            Log.e(TAG, "setLatestEventInfo() is deprecated and you should feel deprecated.",
1925                    new Throwable());
1926        }
1927
1928        // ensure that any information already set directly is preserved
1929        final Notification.Builder builder = new Notification.Builder(context, this);
1930
1931        // now apply the latestEventInfo fields
1932        if (contentTitle != null) {
1933            builder.setContentTitle(contentTitle);
1934        }
1935        if (contentText != null) {
1936            builder.setContentText(contentText);
1937        }
1938        builder.setContentIntent(contentIntent);
1939
1940        builder.build(); // callers expect this notification to be ready to use
1941    }
1942
1943    @Override
1944    public String toString() {
1945        StringBuilder sb = new StringBuilder();
1946        sb.append("Notification(pri=");
1947        sb.append(priority);
1948        sb.append(" contentView=");
1949        if (contentView != null) {
1950            sb.append(contentView.getPackage());
1951            sb.append("/0x");
1952            sb.append(Integer.toHexString(contentView.getLayoutId()));
1953        } else {
1954            sb.append("null");
1955        }
1956        sb.append(" vibrate=");
1957        if ((this.defaults & DEFAULT_VIBRATE) != 0) {
1958            sb.append("default");
1959        } else if (this.vibrate != null) {
1960            int N = this.vibrate.length-1;
1961            sb.append("[");
1962            for (int i=0; i<N; i++) {
1963                sb.append(this.vibrate[i]);
1964                sb.append(',');
1965            }
1966            if (N != -1) {
1967                sb.append(this.vibrate[N]);
1968            }
1969            sb.append("]");
1970        } else {
1971            sb.append("null");
1972        }
1973        sb.append(" sound=");
1974        if ((this.defaults & DEFAULT_SOUND) != 0) {
1975            sb.append("default");
1976        } else if (this.sound != null) {
1977            sb.append(this.sound.toString());
1978        } else {
1979            sb.append("null");
1980        }
1981        if (this.tickerText != null) {
1982            sb.append(" tick");
1983        }
1984        sb.append(" defaults=0x");
1985        sb.append(Integer.toHexString(this.defaults));
1986        sb.append(" flags=0x");
1987        sb.append(Integer.toHexString(this.flags));
1988        sb.append(String.format(" color=0x%08x", this.color));
1989        if (this.category != null) {
1990            sb.append(" category=");
1991            sb.append(this.category);
1992        }
1993        if (this.mGroupKey != null) {
1994            sb.append(" groupKey=");
1995            sb.append(this.mGroupKey);
1996        }
1997        if (this.mSortKey != null) {
1998            sb.append(" sortKey=");
1999            sb.append(this.mSortKey);
2000        }
2001        if (actions != null) {
2002            sb.append(" actions=");
2003            sb.append(actions.length);
2004        }
2005        sb.append(" vis=");
2006        sb.append(visibilityToString(this.visibility));
2007        if (this.publicVersion != null) {
2008            sb.append(" publicVersion=");
2009            sb.append(publicVersion.toString());
2010        }
2011        if (topics != null) {
2012            sb.append("topics=[");
2013            int N = topics.length;
2014            if (N > 0) {
2015                for (int i = 0; i < N-1; i++) {
2016                    sb.append(topics[i]);
2017                    sb.append(',');
2018                }
2019                sb.append(topics[N-1]);
2020            }
2021            sb.append("]");
2022        }
2023        sb.append(")");
2024        return sb.toString();
2025    }
2026
2027    /**
2028     * {@hide}
2029     */
2030    public static String visibilityToString(int vis) {
2031        switch (vis) {
2032            case VISIBILITY_PRIVATE:
2033                return "PRIVATE";
2034            case VISIBILITY_PUBLIC:
2035                return "PUBLIC";
2036            case VISIBILITY_SECRET:
2037                return "SECRET";
2038            default:
2039                return "UNKNOWN(" + String.valueOf(vis) + ")";
2040        }
2041    }
2042
2043    /**
2044     * {@hide}
2045     */
2046    public static String priorityToString(@Priority int pri) {
2047        switch (pri) {
2048            case PRIORITY_MIN:
2049                return "MIN";
2050            case PRIORITY_LOW:
2051                return "LOW";
2052            case PRIORITY_DEFAULT:
2053                return "DEFAULT";
2054            case PRIORITY_HIGH:
2055                return "HIGH";
2056            case PRIORITY_MAX:
2057                return "MAX";
2058            default:
2059                return "UNKNOWN(" + String.valueOf(pri) + ")";
2060        }
2061    }
2062
2063    /**
2064     * The small icon representing this notification in the status bar and content view.
2065     *
2066     * @return the small icon representing this notification.
2067     *
2068     * @see Builder#getSmallIcon()
2069     * @see Builder#setSmallIcon(Icon)
2070     */
2071    public Icon getSmallIcon() {
2072        return mSmallIcon;
2073    }
2074
2075    /**
2076     * Used when notifying to clean up legacy small icons.
2077     * @hide
2078     */
2079    public void setSmallIcon(Icon icon) {
2080        mSmallIcon = icon;
2081    }
2082
2083    /**
2084     * The large icon shown in this notification's content view.
2085     * @see Builder#getLargeIcon()
2086     * @see Builder#setLargeIcon(Icon)
2087     */
2088    public Icon getLargeIcon() {
2089        return mLargeIcon;
2090    }
2091
2092    /**
2093     * @hide
2094     */
2095    public boolean isGroupSummary() {
2096        return mGroupKey != null && (flags & FLAG_GROUP_SUMMARY) != 0;
2097    }
2098
2099    /**
2100     * @hide
2101     */
2102    public boolean isGroupChild() {
2103        return mGroupKey != null && (flags & FLAG_GROUP_SUMMARY) == 0;
2104    }
2105
2106    /**
2107     * Builder class for {@link Notification} objects.
2108     *
2109     * Provides a convenient way to set the various fields of a {@link Notification} and generate
2110     * content views using the platform's notification layout template. If your app supports
2111     * versions of Android as old as API level 4, you can instead use
2112     * {@link android.support.v4.app.NotificationCompat.Builder NotificationCompat.Builder},
2113     * available in the <a href="{@docRoot}tools/extras/support-library.html">Android Support
2114     * library</a>.
2115     *
2116     * <p>Example:
2117     *
2118     * <pre class="prettyprint">
2119     * Notification noti = new Notification.Builder(mContext)
2120     *         .setContentTitle(&quot;New mail from &quot; + sender.toString())
2121     *         .setContentText(subject)
2122     *         .setSmallIcon(R.drawable.new_mail)
2123     *         .setLargeIcon(aBitmap)
2124     *         .build();
2125     * </pre>
2126     */
2127    public static class Builder {
2128        private static final int MAX_ACTION_BUTTONS = 3;
2129        private static final float LARGE_TEXT_SCALE = 1.3f;
2130
2131        private Context mContext;
2132        private Notification mN;
2133        private Bundle mUserExtras = new Bundle();
2134        private Style mStyle;
2135        private ArrayList<Action> mActions = new ArrayList<Action>(MAX_ACTION_BUTTONS);
2136        private ArrayList<String> mPersonList = new ArrayList<String>();
2137        private NotificationColorUtil mColorUtil;
2138        private boolean mColorUtilInited = false;
2139        private List<Topic> mTopics = new ArrayList<>();
2140
2141        /**
2142         * The user that built the notification originally.
2143         */
2144        private int mOriginatingUserId;
2145
2146        /**
2147         * Constructs a new Builder with the defaults:
2148         *
2149
2150         * <table>
2151         * <tr><th align=right>priority</th>
2152         *     <td>{@link #PRIORITY_DEFAULT}</td></tr>
2153         * <tr><th align=right>when</th>
2154         *     <td>now ({@link System#currentTimeMillis()})</td></tr>
2155         * <tr><th align=right>audio stream</th>
2156         *     <td>{@link #STREAM_DEFAULT}</td></tr>
2157         * </table>
2158         *
2159
2160         * @param context
2161         *            A {@link Context} that will be used by the Builder to construct the
2162         *            RemoteViews. The Context will not be held past the lifetime of this Builder
2163         *            object.
2164         */
2165        public Builder(Context context) {
2166            this(context, null);
2167        }
2168
2169        /**
2170         * @hide
2171         */
2172        public Builder(Context context, Notification toAdopt) {
2173            mContext = context;
2174
2175            if (toAdopt == null) {
2176                mN = new Notification();
2177                mN.extras.putBoolean(EXTRA_SHOW_WHEN, true);
2178                mN.priority = PRIORITY_DEFAULT;
2179                mN.visibility = VISIBILITY_PRIVATE;
2180            } else {
2181                mN = toAdopt;
2182                if (mN.actions != null) {
2183                    Collections.addAll(mActions, mN.actions);
2184                }
2185
2186                if (mN.extras.containsKey(EXTRA_PEOPLE)) {
2187                    Collections.addAll(mPersonList, mN.extras.getStringArray(EXTRA_PEOPLE));
2188                }
2189
2190                if (mN.getTopics() != null) {
2191                    Collections.addAll(mTopics, mN.getTopics());
2192                }
2193
2194                String templateClass = mN.extras.getString(EXTRA_TEMPLATE);
2195                if (!TextUtils.isEmpty(templateClass)) {
2196                    final Class<? extends Style> styleClass
2197                            = getNotificationStyleClass(templateClass);
2198                    if (styleClass == null) {
2199                        Log.d(TAG, "Unknown style class: " + templateClass);
2200                    } else {
2201                        try {
2202                            final Constructor<? extends Style> ctor = styleClass.getConstructor();
2203                            ctor.setAccessible(true);
2204                            final Style style = ctor.newInstance();
2205                            style.restoreFromExtras(mN.extras);
2206
2207                            if (style != null) {
2208                                setStyle(style);
2209                            }
2210                        } catch (Throwable t) {
2211                            Log.e(TAG, "Could not create Style", t);
2212                        }
2213                    }
2214                }
2215
2216            }
2217        }
2218
2219        private NotificationColorUtil getColorUtil() {
2220            if (!mColorUtilInited) {
2221                mColorUtilInited = true;
2222                if (mContext.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.LOLLIPOP) {
2223                    mColorUtil = NotificationColorUtil.getInstance(mContext);
2224                }
2225            }
2226            return mColorUtil;
2227        }
2228
2229        /**
2230         * Add a timestamp pertaining to the notification (usually the time the event occurred).
2231         * It will be shown in the notification content view by default; use
2232         * {@link #setShowWhen(boolean) setShowWhen} to control this.
2233         *
2234         * @see Notification#when
2235         */
2236        public Builder setWhen(long when) {
2237            mN.when = when;
2238            return this;
2239        }
2240
2241        /**
2242         * Control whether the timestamp set with {@link #setWhen(long) setWhen} is shown
2243         * in the content view.
2244         */
2245        public Builder setShowWhen(boolean show) {
2246            mN.extras.putBoolean(EXTRA_SHOW_WHEN, show);
2247            return this;
2248        }
2249
2250        /**
2251         * Show the {@link Notification#when} field as a stopwatch.
2252         *
2253         * Instead of presenting <code>when</code> as a timestamp, the notification will show an
2254         * automatically updating display of the minutes and seconds since <code>when</code>.
2255         *
2256         * Useful when showing an elapsed time (like an ongoing phone call).
2257         *
2258         * @see android.widget.Chronometer
2259         * @see Notification#when
2260         */
2261        public Builder setUsesChronometer(boolean b) {
2262            mN.extras.putBoolean(EXTRA_SHOW_CHRONOMETER, b);
2263            return this;
2264        }
2265
2266        /**
2267         * Set the small icon resource, which will be used to represent the notification in the
2268         * status bar.
2269         *
2270
2271         * The platform template for the expanded view will draw this icon in the left, unless a
2272         * {@link #setLargeIcon(Bitmap) large icon} has also been specified, in which case the small
2273         * icon will be moved to the right-hand side.
2274         *
2275
2276         * @param icon
2277         *            A resource ID in the application's package of the drawable to use.
2278         * @see Notification#icon
2279         */
2280        public Builder setSmallIcon(@DrawableRes int icon) {
2281            return setSmallIcon(icon != 0
2282                    ? Icon.createWithResource(mContext, icon)
2283                    : null);
2284        }
2285
2286        /**
2287         * A variant of {@link #setSmallIcon(int) setSmallIcon(int)} that takes an additional
2288         * level parameter for when the icon is a {@link android.graphics.drawable.LevelListDrawable
2289         * LevelListDrawable}.
2290         *
2291         * @param icon A resource ID in the application's package of the drawable to use.
2292         * @param level The level to use for the icon.
2293         *
2294         * @see Notification#icon
2295         * @see Notification#iconLevel
2296         */
2297        public Builder setSmallIcon(@DrawableRes int icon, int level) {
2298            mN.iconLevel = level;
2299            return setSmallIcon(icon);
2300        }
2301
2302        /**
2303         * Set the small icon, which will be used to represent the notification in the
2304         * status bar and content view (unless overriden there by a
2305         * {@link #setLargeIcon(Bitmap) large icon}).
2306         *
2307         * @param icon An Icon object to use.
2308         * @see Notification#icon
2309         */
2310        public Builder setSmallIcon(Icon icon) {
2311            mN.setSmallIcon(icon);
2312            if (icon != null && icon.getType() == Icon.TYPE_RESOURCE) {
2313                mN.icon = icon.getResId();
2314            }
2315            return this;
2316        }
2317
2318        /**
2319         * Set the first line of text in the platform notification template.
2320         */
2321        public Builder setContentTitle(CharSequence title) {
2322            mN.extras.putCharSequence(EXTRA_TITLE, safeCharSequence(title));
2323            return this;
2324        }
2325
2326        /**
2327         * Set the second line of text in the platform notification template.
2328         */
2329        public Builder setContentText(CharSequence text) {
2330            mN.extras.putCharSequence(EXTRA_TEXT, safeCharSequence(text));
2331            return this;
2332        }
2333
2334        /**
2335         * Set the third line of text in the platform notification template.
2336         * Don't use if you're also using {@link #setProgress(int, int, boolean)}; they occupy the
2337         * same location in the standard template.
2338         */
2339        public Builder setSubText(CharSequence text) {
2340            mN.extras.putCharSequence(EXTRA_SUB_TEXT, safeCharSequence(text));
2341            return this;
2342        }
2343
2344        /**
2345         * Set the large number at the right-hand side of the notification.  This is
2346         * equivalent to setContentInfo, although it might show the number in a different
2347         * font size for readability.
2348         */
2349        public Builder setNumber(int number) {
2350            mN.number = number;
2351            return this;
2352        }
2353
2354        /**
2355         * A small piece of additional information pertaining to this notification.
2356         *
2357         * The platform template will draw this on the last line of the notification, at the far
2358         * right (to the right of a smallIcon if it has been placed there).
2359         */
2360        public Builder setContentInfo(CharSequence info) {
2361            mN.extras.putCharSequence(EXTRA_INFO_TEXT, safeCharSequence(info));
2362            return this;
2363        }
2364
2365        /**
2366         * Set the progress this notification represents.
2367         *
2368         * The platform template will represent this using a {@link ProgressBar}.
2369         */
2370        public Builder setProgress(int max, int progress, boolean indeterminate) {
2371            mN.extras.putInt(EXTRA_PROGRESS, progress);
2372            mN.extras.putInt(EXTRA_PROGRESS_MAX, max);
2373            mN.extras.putBoolean(EXTRA_PROGRESS_INDETERMINATE, indeterminate);
2374            return this;
2375        }
2376
2377        /**
2378         * Supply a custom RemoteViews to use instead of the platform template.
2379         *
2380         * Use {@link #setCustomContentView(RemoteViews)} instead.
2381         */
2382        @Deprecated
2383        public Builder setContent(RemoteViews views) {
2384            return setCustomContentView(views);
2385        }
2386
2387        /**
2388         * Supply custom RemoteViews to use instead of the platform template.
2389         *
2390         * This will override the layout that would otherwise be constructed by this Builder
2391         * object.
2392         */
2393        public Builder setCustomContentView(RemoteViews contentView) {
2394            mN.contentView = contentView;
2395            return this;
2396        }
2397
2398        /**
2399         * Supply custom RemoteViews to use instead of the platform template in the expanded form.
2400         *
2401         * This will override the expanded layout that would otherwise be constructed by this
2402         * Builder object.
2403         */
2404        public Builder setCustomBigContentView(RemoteViews contentView) {
2405            mN.bigContentView = contentView;
2406            return this;
2407        }
2408
2409        /**
2410         * Supply custom RemoteViews to use instead of the platform template in the heads up dialog.
2411         *
2412         * This will override the heads-up layout that would otherwise be constructed by this
2413         * Builder object.
2414         */
2415        public Builder setCustomHeadsUpContentView(RemoteViews contentView) {
2416            mN.headsUpContentView = contentView;
2417            return this;
2418        }
2419
2420        /**
2421         * Supply a {@link PendingIntent} to be sent when the notification is clicked.
2422         *
2423         * As of {@link android.os.Build.VERSION_CODES#HONEYCOMB}, if this field is unset and you
2424         * have specified a custom RemoteViews with {@link #setContent(RemoteViews)}, you can use
2425         * {@link RemoteViews#setOnClickPendingIntent RemoteViews.setOnClickPendingIntent(int,PendingIntent)}
2426         * to assign PendingIntents to individual views in that custom layout (i.e., to create
2427         * clickable buttons inside the notification view).
2428         *
2429         * @see Notification#contentIntent Notification.contentIntent
2430         */
2431        public Builder setContentIntent(PendingIntent intent) {
2432            mN.contentIntent = intent;
2433            return this;
2434        }
2435
2436        /**
2437         * Supply a {@link PendingIntent} to send when the notification is cleared explicitly by the user.
2438         *
2439         * @see Notification#deleteIntent
2440         */
2441        public Builder setDeleteIntent(PendingIntent intent) {
2442            mN.deleteIntent = intent;
2443            return this;
2444        }
2445
2446        /**
2447         * An intent to launch instead of posting the notification to the status bar.
2448         * Only for use with extremely high-priority notifications demanding the user's
2449         * <strong>immediate</strong> attention, such as an incoming phone call or
2450         * alarm clock that the user has explicitly set to a particular time.
2451         * If this facility is used for something else, please give the user an option
2452         * to turn it off and use a normal notification, as this can be extremely
2453         * disruptive.
2454         *
2455         * <p>
2456         * The system UI may choose to display a heads-up notification, instead of
2457         * launching this intent, while the user is using the device.
2458         * </p>
2459         *
2460         * @param intent The pending intent to launch.
2461         * @param highPriority Passing true will cause this notification to be sent
2462         *          even if other notifications are suppressed.
2463         *
2464         * @see Notification#fullScreenIntent
2465         */
2466        public Builder setFullScreenIntent(PendingIntent intent, boolean highPriority) {
2467            mN.fullScreenIntent = intent;
2468            setFlag(FLAG_HIGH_PRIORITY, highPriority);
2469            return this;
2470        }
2471
2472        /**
2473         * Set the "ticker" text which is sent to accessibility services.
2474         *
2475         * @see Notification#tickerText
2476         */
2477        public Builder setTicker(CharSequence tickerText) {
2478            mN.tickerText = safeCharSequence(tickerText);
2479            return this;
2480        }
2481
2482        /**
2483         * Obsolete version of {@link #setTicker(CharSequence)}.
2484         *
2485         */
2486        @Deprecated
2487        public Builder setTicker(CharSequence tickerText, RemoteViews views) {
2488            setTicker(tickerText);
2489            // views is ignored
2490            return this;
2491        }
2492
2493        /**
2494         * Add a large icon to the notification content view.
2495         *
2496         * In the platform template, this image will be shown on the left of the notification view
2497         * in place of the {@link #setSmallIcon(Icon) small icon} (which will be placed in a small
2498         * badge atop the large icon).
2499         */
2500        public Builder setLargeIcon(Bitmap b) {
2501            return setLargeIcon(b != null ? Icon.createWithBitmap(b) : null);
2502        }
2503
2504        /**
2505         * Add a large icon to the notification content view.
2506         *
2507         * In the platform template, this image will be shown on the left of the notification view
2508         * in place of the {@link #setSmallIcon(Icon) small icon} (which will be placed in a small
2509         * badge atop the large icon).
2510         */
2511        public Builder setLargeIcon(Icon icon) {
2512            mN.mLargeIcon = icon;
2513            mN.extras.putParcelable(EXTRA_LARGE_ICON, icon);
2514            return this;
2515        }
2516
2517        /**
2518         * Set the sound to play.
2519         *
2520         * It will be played using the {@link #AUDIO_ATTRIBUTES_DEFAULT default audio attributes}
2521         * for notifications.
2522         *
2523         * <p>
2524         * A notification that is noisy is more likely to be presented as a heads-up notification.
2525         * </p>
2526         *
2527         * @see Notification#sound
2528         */
2529        public Builder setSound(Uri sound) {
2530            mN.sound = sound;
2531            mN.audioAttributes = AUDIO_ATTRIBUTES_DEFAULT;
2532            return this;
2533        }
2534
2535        /**
2536         * Set the sound to play, along with a specific stream on which to play it.
2537         *
2538         * See {@link android.media.AudioManager} for the <code>STREAM_</code> constants.
2539         *
2540         * <p>
2541         * A notification that is noisy is more likely to be presented as a heads-up notification.
2542         * </p>
2543         * @deprecated use {@link #setSound(Uri, AudioAttributes)} instead.
2544         * @see Notification#sound
2545         */
2546        @Deprecated
2547        public Builder setSound(Uri sound, int streamType) {
2548            mN.sound = sound;
2549            mN.audioStreamType = streamType;
2550            return this;
2551        }
2552
2553        /**
2554         * Set the sound to play, along with specific {@link AudioAttributes audio attributes} to
2555         * use during playback.
2556         *
2557         * <p>
2558         * A notification that is noisy is more likely to be presented as a heads-up notification.
2559         * </p>
2560         *
2561         * @see Notification#sound
2562         */
2563        public Builder setSound(Uri sound, AudioAttributes audioAttributes) {
2564            mN.sound = sound;
2565            mN.audioAttributes = audioAttributes;
2566            return this;
2567        }
2568
2569        /**
2570         * Set the vibration pattern to use.
2571         *
2572         * See {@link android.os.Vibrator#vibrate(long[], int)} for a discussion of the
2573         * <code>pattern</code> parameter.
2574         *
2575         * <p>
2576         * A notification that vibrates is more likely to be presented as a heads-up notification.
2577         * </p>
2578         *
2579         * @see Notification#vibrate
2580         */
2581        public Builder setVibrate(long[] pattern) {
2582            mN.vibrate = pattern;
2583            return this;
2584        }
2585
2586        /**
2587         * Set the desired color for the indicator LED on the device, as well as the
2588         * blink duty cycle (specified in milliseconds).
2589         *
2590
2591         * Not all devices will honor all (or even any) of these values.
2592         *
2593
2594         * @see Notification#ledARGB
2595         * @see Notification#ledOnMS
2596         * @see Notification#ledOffMS
2597         */
2598        public Builder setLights(@ColorInt int argb, int onMs, int offMs) {
2599            mN.ledARGB = argb;
2600            mN.ledOnMS = onMs;
2601            mN.ledOffMS = offMs;
2602            return this;
2603        }
2604
2605        /**
2606         * Set whether this is an "ongoing" notification.
2607         *
2608
2609         * Ongoing notifications cannot be dismissed by the user, so your application or service
2610         * must take care of canceling them.
2611         *
2612
2613         * They are typically used to indicate a background task that the user is actively engaged
2614         * with (e.g., playing music) or is pending in some way and therefore occupying the device
2615         * (e.g., a file download, sync operation, active network connection).
2616         *
2617
2618         * @see Notification#FLAG_ONGOING_EVENT
2619         * @see Service#setForeground(boolean)
2620         */
2621        public Builder setOngoing(boolean ongoing) {
2622            setFlag(FLAG_ONGOING_EVENT, ongoing);
2623            return this;
2624        }
2625
2626        /**
2627         * Set this flag if you would only like the sound, vibrate
2628         * and ticker to be played if the notification is not already showing.
2629         *
2630         * @see Notification#FLAG_ONLY_ALERT_ONCE
2631         */
2632        public Builder setOnlyAlertOnce(boolean onlyAlertOnce) {
2633            setFlag(FLAG_ONLY_ALERT_ONCE, onlyAlertOnce);
2634            return this;
2635        }
2636
2637        /**
2638         * Make this notification automatically dismissed when the user touches it. The
2639         * PendingIntent set with {@link #setDeleteIntent} will be sent when this happens.
2640         *
2641         * @see Notification#FLAG_AUTO_CANCEL
2642         */
2643        public Builder setAutoCancel(boolean autoCancel) {
2644            setFlag(FLAG_AUTO_CANCEL, autoCancel);
2645            return this;
2646        }
2647
2648        /**
2649         * Set whether or not this notification should not bridge to other devices.
2650         *
2651         * <p>Some notifications can be bridged to other devices for remote display.
2652         * This hint can be set to recommend this notification not be bridged.
2653         */
2654        public Builder setLocalOnly(boolean localOnly) {
2655            setFlag(FLAG_LOCAL_ONLY, localOnly);
2656            return this;
2657        }
2658
2659        /**
2660         * Set which notification properties will be inherited from system defaults.
2661         * <p>
2662         * The value should be one or more of the following fields combined with
2663         * bitwise-or:
2664         * {@link #DEFAULT_SOUND}, {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}.
2665         * <p>
2666         * For all default values, use {@link #DEFAULT_ALL}.
2667         */
2668        public Builder setDefaults(int defaults) {
2669            mN.defaults = defaults;
2670            return this;
2671        }
2672
2673        /**
2674         * Set the priority of this notification.
2675         *
2676         * @see Notification#priority
2677         */
2678        public Builder setPriority(@Priority int pri) {
2679            mN.priority = pri;
2680            return this;
2681        }
2682
2683        /**
2684         * Set the notification category.
2685         *
2686         * @see Notification#category
2687         */
2688        public Builder setCategory(String category) {
2689            mN.category = category;
2690            return this;
2691        }
2692
2693        /**
2694         * Add a person that is relevant to this notification.
2695         *
2696         * <P>
2697         * Depending on user preferences, this annotation may allow the notification to pass
2698         * through interruption filters, and to appear more prominently in the user interface.
2699         * </P>
2700         *
2701         * <P>
2702         * The person should be specified by the {@code String} representation of a
2703         * {@link android.provider.ContactsContract.Contacts#CONTENT_LOOKUP_URI}.
2704         * </P>
2705         *
2706         * <P>The system will also attempt to resolve {@code mailto:} and {@code tel:} schema
2707         * URIs.  The path part of these URIs must exist in the contacts database, in the
2708         * appropriate column, or the reference will be discarded as invalid. Telephone schema
2709         * URIs will be resolved by {@link android.provider.ContactsContract.PhoneLookup}.
2710         * </P>
2711         *
2712         * @param uri A URI for the person.
2713         * @see Notification#EXTRA_PEOPLE
2714         */
2715        public Builder addPerson(String uri) {
2716            mPersonList.add(uri);
2717            return this;
2718        }
2719
2720        /**
2721         * Set this notification to be part of a group of notifications sharing the same key.
2722         * Grouped notifications may display in a cluster or stack on devices which
2723         * support such rendering.
2724         *
2725         * <p>To make this notification the summary for its group, also call
2726         * {@link #setGroupSummary}. A sort order can be specified for group members by using
2727         * {@link #setSortKey}.
2728         * @param groupKey The group key of the group.
2729         * @return this object for method chaining
2730         */
2731        public Builder setGroup(String groupKey) {
2732            mN.mGroupKey = groupKey;
2733            return this;
2734        }
2735
2736        /**
2737         * Set this notification to be the group summary for a group of notifications.
2738         * Grouped notifications may display in a cluster or stack on devices which
2739         * support such rendering. Requires a group key also be set using {@link #setGroup}.
2740         * @param isGroupSummary Whether this notification should be a group summary.
2741         * @return this object for method chaining
2742         */
2743        public Builder setGroupSummary(boolean isGroupSummary) {
2744            setFlag(FLAG_GROUP_SUMMARY, isGroupSummary);
2745            return this;
2746        }
2747
2748        /**
2749         * Set a sort key that orders this notification among other notifications from the
2750         * same package. This can be useful if an external sort was already applied and an app
2751         * would like to preserve this. Notifications will be sorted lexicographically using this
2752         * value, although providing different priorities in addition to providing sort key may
2753         * cause this value to be ignored.
2754         *
2755         * <p>This sort key can also be used to order members of a notification group. See
2756         * {@link #setGroup}.
2757         *
2758         * @see String#compareTo(String)
2759         */
2760        public Builder setSortKey(String sortKey) {
2761            mN.mSortKey = sortKey;
2762            return this;
2763        }
2764
2765        /**
2766         * Merge additional metadata into this notification.
2767         *
2768         * <p>Values within the Bundle will replace existing extras values in this Builder.
2769         *
2770         * @see Notification#extras
2771         */
2772        public Builder addExtras(Bundle extras) {
2773            if (extras != null) {
2774                mUserExtras.putAll(extras);
2775            }
2776            return this;
2777        }
2778
2779        /**
2780         * Set metadata for this notification.
2781         *
2782         * <p>A reference to the Bundle is held for the lifetime of this Builder, and the Bundle's
2783         * current contents are copied into the Notification each time {@link #build()} is
2784         * called.
2785         *
2786         * <p>Replaces any existing extras values with those from the provided Bundle.
2787         * Use {@link #addExtras} to merge in metadata instead.
2788         *
2789         * @see Notification#extras
2790         */
2791        public Builder setExtras(Bundle extras) {
2792            if (extras != null) {
2793                mUserExtras = extras;
2794            }
2795            return this;
2796        }
2797
2798        /**
2799         * Get the current metadata Bundle used by this notification Builder.
2800         *
2801         * <p>The returned Bundle is shared with this Builder.
2802         *
2803         * <p>The current contents of this Bundle are copied into the Notification each time
2804         * {@link #build()} is called.
2805         *
2806         * @see Notification#extras
2807         */
2808        public Bundle getExtras() {
2809            return mUserExtras;
2810        }
2811
2812        private Bundle getAllExtras() {
2813            final Bundle saveExtras = (Bundle) mUserExtras.clone();
2814            saveExtras.putAll(mN.extras);
2815            return saveExtras;
2816        }
2817
2818        /**
2819         * Add an action to this notification. Actions are typically displayed by
2820         * the system as a button adjacent to the notification content.
2821         * <p>
2822         * Every action must have an icon (32dp square and matching the
2823         * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo
2824         * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}.
2825         * <p>
2826         * A notification in its expanded form can display up to 3 actions, from left to right in
2827         * the order they were added. Actions will not be displayed when the notification is
2828         * collapsed, however, so be sure that any essential functions may be accessed by the user
2829         * in some other way (for example, in the Activity pointed to by {@link #contentIntent}).
2830         *
2831         * @param icon Resource ID of a drawable that represents the action.
2832         * @param title Text describing the action.
2833         * @param intent PendingIntent to be fired when the action is invoked.
2834         *
2835         * @deprecated Use {@link #addAction(Action)} instead.
2836         */
2837        @Deprecated
2838        public Builder addAction(int icon, CharSequence title, PendingIntent intent) {
2839            mActions.add(new Action(icon, safeCharSequence(title), intent));
2840            return this;
2841        }
2842
2843        /**
2844         * Add an action to this notification. Actions are typically displayed by
2845         * the system as a button adjacent to the notification content.
2846         * <p>
2847         * Every action must have an icon (32dp square and matching the
2848         * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo
2849         * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}.
2850         * <p>
2851         * A notification in its expanded form can display up to 3 actions, from left to right in
2852         * the order they were added. Actions will not be displayed when the notification is
2853         * collapsed, however, so be sure that any essential functions may be accessed by the user
2854         * in some other way (for example, in the Activity pointed to by {@link #contentIntent}).
2855         *
2856         * @param action The action to add.
2857         */
2858        public Builder addAction(Action action) {
2859            mActions.add(action);
2860            return this;
2861        }
2862
2863        /**
2864         * Alter the complete list of actions attached to this notification.
2865         * @see #addAction(Action).
2866         *
2867         * @param actions
2868         * @return
2869         */
2870        public Builder setActions(Action... actions) {
2871            mActions.clear();
2872            for (int i = 0; i < actions.length; i++) {
2873                mActions.add(actions[i]);
2874            }
2875            return this;
2876        }
2877
2878        /**
2879         * Add a rich notification style to be applied at build time.
2880         *
2881         * @param style Object responsible for modifying the notification style.
2882         */
2883        public Builder setStyle(Style style) {
2884            if (mStyle != style) {
2885                mStyle = style;
2886                if (mStyle != null) {
2887                    mStyle.setBuilder(this);
2888                    mN.extras.putString(EXTRA_TEMPLATE, style.getClass().getName());
2889                }  else {
2890                    mN.extras.remove(EXTRA_TEMPLATE);
2891                }
2892            }
2893            return this;
2894        }
2895
2896        /**
2897         * Specify the value of {@link #visibility}.
2898         *
2899         * @param visibility One of {@link #VISIBILITY_PRIVATE} (the default),
2900         * {@link #VISIBILITY_SECRET}, or {@link #VISIBILITY_PUBLIC}.
2901         *
2902         * @return The same Builder.
2903         */
2904        public Builder setVisibility(int visibility) {
2905            mN.visibility = visibility;
2906            return this;
2907        }
2908
2909        /**
2910         * Supply a replacement Notification whose contents should be shown in insecure contexts
2911         * (i.e. atop the secure lockscreen). See {@link #visibility} and {@link #VISIBILITY_PUBLIC}.
2912         * @param n A replacement notification, presumably with some or all info redacted.
2913         * @return The same Builder.
2914         */
2915        public Builder setPublicVersion(Notification n) {
2916            if (n != null) {
2917                mN.publicVersion = new Notification();
2918                n.cloneInto(mN.publicVersion, /*heavy=*/ true);
2919            } else {
2920                mN.publicVersion = null;
2921            }
2922            return this;
2923        }
2924
2925        /**
2926         * Apply an extender to this notification builder. Extenders may be used to add
2927         * metadata or change options on this builder.
2928         */
2929        public Builder extend(Extender extender) {
2930            extender.extend(this);
2931            return this;
2932        }
2933
2934        /**
2935         * @hide
2936         */
2937        public void setFlag(int mask, boolean value) {
2938            if (value) {
2939                mN.flags |= mask;
2940            } else {
2941                mN.flags &= ~mask;
2942            }
2943        }
2944
2945        /**
2946         * Sets {@link Notification#color}.
2947         *
2948         * @param argb The accent color to use
2949         *
2950         * @return The same Builder.
2951         */
2952        public Builder setColor(@ColorInt int argb) {
2953            mN.color = argb;
2954            return this;
2955        }
2956
2957        /**
2958         * Add a topic to this notification. Topics are typically displayed in Notification
2959         * settings.
2960         * <p>
2961         * Every topic must have an id and a textual label.
2962         *
2963         * @param topic The topic to add.
2964         */
2965        public Builder addTopic(Topic topic) {
2966            mTopics.add(topic);
2967            return this;
2968        }
2969
2970        private Drawable getProfileBadgeDrawable() {
2971            // Note: This assumes that the current user can read the profile badge of the
2972            // originating user.
2973            return mContext.getPackageManager().getUserBadgeForDensity(
2974                    new UserHandle(mOriginatingUserId), 0);
2975        }
2976
2977        private Bitmap getProfileBadge() {
2978            Drawable badge = getProfileBadgeDrawable();
2979            if (badge == null) {
2980                return null;
2981            }
2982            final int size = mContext.getResources().getDimensionPixelSize(
2983                    R.dimen.notification_badge_size);
2984            Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
2985            Canvas canvas = new Canvas(bitmap);
2986            badge.setBounds(0, 0, size, size);
2987            badge.draw(canvas);
2988            return bitmap;
2989        }
2990
2991        private boolean addProfileBadge(RemoteViews contentView, int resId) {
2992            Bitmap profileBadge = getProfileBadge();
2993
2994            contentView.setViewVisibility(R.id.profile_badge_large_template, View.GONE);
2995            contentView.setViewVisibility(R.id.profile_badge_line2, View.GONE);
2996            contentView.setViewVisibility(R.id.profile_badge_line3, View.GONE);
2997
2998            if (profileBadge != null) {
2999                contentView.setImageViewBitmap(resId, profileBadge);
3000                contentView.setViewVisibility(resId, View.VISIBLE);
3001
3002                // Make sure Line 3 is visible. As badge will be here if there
3003                // is no text to display.
3004                if (resId == R.id.profile_badge_line3) {
3005                    contentView.setViewVisibility(R.id.line3, View.VISIBLE);
3006                }
3007                return true;
3008            }
3009            return false;
3010        }
3011
3012        private void shrinkLine3Text(RemoteViews contentView) {
3013            float subTextSize = mContext.getResources().getDimensionPixelSize(
3014                    R.dimen.notification_subtext_size);
3015            contentView.setTextViewTextSize(R.id.text, TypedValue.COMPLEX_UNIT_PX, subTextSize);
3016        }
3017
3018        private void unshrinkLine3Text(RemoteViews contentView) {
3019            float regularTextSize = mContext.getResources().getDimensionPixelSize(
3020                    com.android.internal.R.dimen.notification_text_size);
3021            contentView.setTextViewTextSize(R.id.text, TypedValue.COMPLEX_UNIT_PX, regularTextSize);
3022        }
3023
3024        private void resetStandardTemplate(RemoteViews contentView) {
3025            removeLargeIconBackground(contentView);
3026            contentView.setViewPadding(R.id.icon, 0, 0, 0, 0);
3027            contentView.setImageViewResource(R.id.icon, 0);
3028            contentView.setInt(R.id.icon, "setBackgroundResource", 0);
3029            contentView.setViewVisibility(R.id.right_icon, View.GONE);
3030            contentView.setInt(R.id.right_icon, "setBackgroundResource", 0);
3031            contentView.setImageViewResource(R.id.right_icon, 0);
3032            contentView.setImageViewResource(R.id.icon, 0);
3033            contentView.setTextViewText(R.id.title, null);
3034            contentView.setTextViewText(R.id.text, null);
3035            unshrinkLine3Text(contentView);
3036            contentView.setTextViewText(R.id.text2, null);
3037            contentView.setViewVisibility(R.id.text2, View.GONE);
3038            contentView.setViewVisibility(R.id.info, View.GONE);
3039            contentView.setViewVisibility(R.id.time, View.GONE);
3040            contentView.setViewVisibility(R.id.line3, View.GONE);
3041            contentView.setViewVisibility(R.id.overflow_divider, View.GONE);
3042            contentView.setViewVisibility(R.id.progress, View.GONE);
3043            contentView.setViewVisibility(R.id.chronometer, View.GONE);
3044        }
3045
3046        private RemoteViews applyStandardTemplate(int resId) {
3047            return applyStandardTemplate(resId, true /* hasProgress */);
3048        }
3049
3050        /**
3051         * @param hasProgress whether the progress bar should be shown and set
3052         */
3053        private RemoteViews applyStandardTemplate(int resId, boolean hasProgress) {
3054            RemoteViews contentView = new BuilderRemoteViews(mContext.getApplicationInfo(), resId);
3055
3056            resetStandardTemplate(contentView);
3057
3058            boolean showLine3 = false;
3059            boolean showLine2 = false;
3060            boolean contentTextInLine2 = false;
3061            final Bundle ex = mN.extras;
3062
3063            if (mN.mLargeIcon != null) {
3064                contentView.setImageViewIcon(R.id.icon, mN.mLargeIcon);
3065                processLargeLegacyIcon(mN.mLargeIcon, contentView);
3066                contentView.setImageViewIcon(R.id.right_icon, mN.mSmallIcon);
3067                contentView.setViewVisibility(R.id.right_icon, View.VISIBLE);
3068                processSmallRightIcon(mN.mSmallIcon, contentView);
3069            } else { // small icon at left
3070                contentView.setImageViewIcon(R.id.icon, mN.mSmallIcon);
3071                contentView.setViewVisibility(R.id.icon, View.VISIBLE);
3072                processSmallIconAsLarge(mN.mSmallIcon, contentView);
3073            }
3074            if (ex.getCharSequence(EXTRA_TITLE) != null) {
3075                contentView.setTextViewText(R.id.title,
3076                        processLegacyText(ex.getCharSequence(EXTRA_TITLE)));
3077            }
3078            if (ex.getCharSequence(EXTRA_TEXT) != null) {
3079                contentView.setTextViewText(R.id.text,
3080                        processLegacyText(ex.getCharSequence(EXTRA_TEXT)));
3081                showLine3 = true;
3082            }
3083            if (ex.getCharSequence(EXTRA_INFO_TEXT) != null) {
3084                contentView.setTextViewText(R.id.info,
3085                        processLegacyText(ex.getCharSequence(EXTRA_INFO_TEXT)));
3086                contentView.setViewVisibility(R.id.info, View.VISIBLE);
3087                showLine3 = true;
3088            } else if (mN.number > 0) {
3089                final int tooBig = mContext.getResources().getInteger(
3090                        R.integer.status_bar_notification_info_maxnum);
3091                if (mN.number > tooBig) {
3092                    contentView.setTextViewText(R.id.info, processLegacyText(
3093                            mContext.getResources().getString(
3094                                    R.string.status_bar_notification_info_overflow)));
3095                } else {
3096                    NumberFormat f = NumberFormat.getIntegerInstance();
3097                    contentView.setTextViewText(R.id.info, processLegacyText(f.format(mN.number)));
3098                }
3099                contentView.setViewVisibility(R.id.info, View.VISIBLE);
3100                showLine3 = true;
3101            } else {
3102                contentView.setViewVisibility(R.id.info, View.GONE);
3103            }
3104
3105            // Need to show three lines?
3106            if (ex.getCharSequence(EXTRA_SUB_TEXT) != null) {
3107                contentView.setTextViewText(R.id.text,
3108                        processLegacyText(ex.getCharSequence(EXTRA_SUB_TEXT)));
3109                if (ex.getCharSequence(EXTRA_TEXT) != null) {
3110                    contentView.setTextViewText(R.id.text2,
3111                            processLegacyText(ex.getCharSequence(EXTRA_TEXT)));
3112                    contentView.setViewVisibility(R.id.text2, View.VISIBLE);
3113                    showLine2 = true;
3114                    contentTextInLine2 = true;
3115                } else {
3116                    contentView.setViewVisibility(R.id.text2, View.GONE);
3117                }
3118            } else {
3119                contentView.setViewVisibility(R.id.text2, View.GONE);
3120                final int max = ex.getInt(EXTRA_PROGRESS_MAX, 0);
3121                final int progress = ex.getInt(EXTRA_PROGRESS, 0);
3122                final boolean ind = ex.getBoolean(EXTRA_PROGRESS_INDETERMINATE);
3123                if (hasProgress && (max != 0 || ind)) {
3124                    contentView.setViewVisibility(R.id.progress, View.VISIBLE);
3125                    contentView.setProgressBar(
3126                            R.id.progress, max, progress, ind);
3127                    contentView.setProgressBackgroundTintList(
3128                            R.id.progress, ColorStateList.valueOf(mContext.getColor(
3129                                    R.color.notification_progress_background_color)));
3130                    if (mN.color != COLOR_DEFAULT) {
3131                        ColorStateList colorStateList = ColorStateList.valueOf(mN.color);
3132                        contentView.setProgressTintList(R.id.progress, colorStateList);
3133                        contentView.setProgressIndeterminateTintList(R.id.progress, colorStateList);
3134                    }
3135                    showLine2 = true;
3136                } else {
3137                    contentView.setViewVisibility(R.id.progress, View.GONE);
3138                }
3139            }
3140            if (showLine2) {
3141
3142                // need to shrink all the type to make sure everything fits
3143                shrinkLine3Text(contentView);
3144            }
3145
3146            if (showsTimeOrChronometer()) {
3147                if (ex.getBoolean(EXTRA_SHOW_CHRONOMETER)) {
3148                    contentView.setViewVisibility(R.id.chronometer, View.VISIBLE);
3149                    contentView.setLong(R.id.chronometer, "setBase",
3150                            mN.when + (SystemClock.elapsedRealtime() - System.currentTimeMillis()));
3151                    contentView.setBoolean(R.id.chronometer, "setStarted", true);
3152                } else {
3153                    contentView.setViewVisibility(R.id.time, View.VISIBLE);
3154                    contentView.setLong(R.id.time, "setTime", mN.when);
3155                }
3156            }
3157
3158            // Adjust padding depending on line count and font size.
3159            contentView.setViewPadding(R.id.line1, 0,
3160                    calculateTopPadding(mContext, hasThreeLines(),
3161                            mContext.getResources().getConfiguration().fontScale),
3162                    0, 0);
3163
3164            // We want to add badge to first line of text.
3165            boolean addedBadge = addProfileBadge(contentView,
3166                    contentTextInLine2 ? R.id.profile_badge_line2 : R.id.profile_badge_line3);
3167            // If we added the badge to line 3 then we should show line 3.
3168            if (addedBadge && !contentTextInLine2) {
3169                showLine3 = true;
3170            }
3171
3172            // Note getStandardView may hide line 3 again.
3173            contentView.setViewVisibility(R.id.line3, showLine3 ? View.VISIBLE : View.GONE);
3174            contentView.setViewVisibility(R.id.overflow_divider,
3175                    showLine3 ? View.VISIBLE : View.GONE);
3176            return contentView;
3177        }
3178
3179        /**
3180         * @return true if the built notification will show the time or the chronometer; false
3181         *         otherwise
3182         */
3183        private boolean showsTimeOrChronometer() {
3184            return mN.when != 0 && mN.extras.getBoolean(EXTRA_SHOW_WHEN);
3185        }
3186
3187        /**
3188         * Logic to find out whether the notification is going to have three lines in the contracted
3189         * layout. This is used to adjust the top padding.
3190         *
3191         * @return true if the notification is going to have three lines; false if the notification
3192         *         is going to have one or two lines
3193         */
3194        private boolean hasThreeLines() {
3195            final CharSequence subText = mN.extras.getCharSequence(EXTRA_SUB_TEXT);
3196            final CharSequence text = mN.extras.getCharSequence(EXTRA_TEXT);
3197            boolean contentTextInLine2 = subText != null && text != null;
3198            boolean hasProgress = mStyle == null || mStyle.hasProgress();
3199            // If we have content text in line 2, badge goes into line 2, or line 3 otherwise
3200            boolean badgeInLine3 = getProfileBadgeDrawable() != null && !contentTextInLine2;
3201            boolean hasLine3 = text != null || mN.extras.getCharSequence(EXTRA_INFO_TEXT) != null
3202                    || mN.number > 0 || badgeInLine3;
3203            final Bundle ex = mN.extras;
3204            final int max = ex.getInt(EXTRA_PROGRESS_MAX, 0);
3205            final boolean ind = ex.getBoolean(EXTRA_PROGRESS_INDETERMINATE);
3206            boolean hasLine2 = (subText != null && text != null) ||
3207                    (hasProgress && subText == null && (max != 0 || ind));
3208            return hasLine2 && hasLine3;
3209        }
3210
3211        /**
3212         * @hide
3213         */
3214        public static int calculateTopPadding(Context ctx, boolean hasThreeLines,
3215                float fontScale) {
3216            int padding = ctx.getResources().getDimensionPixelSize(hasThreeLines
3217                    ? R.dimen.notification_top_pad_narrow
3218                    : R.dimen.notification_top_pad);
3219            int largePadding = ctx.getResources().getDimensionPixelSize(hasThreeLines
3220                    ? R.dimen.notification_top_pad_large_text_narrow
3221                    : R.dimen.notification_top_pad_large_text);
3222            float largeFactor = (MathUtils.constrain(fontScale, 1.0f, LARGE_TEXT_SCALE) - 1f)
3223                    / (LARGE_TEXT_SCALE - 1f);
3224
3225            // Linearly interpolate the padding between large and normal with the font scale ranging
3226            // from 1f to LARGE_TEXT_SCALE
3227            return Math.round((1 - largeFactor) * padding + largeFactor * largePadding);
3228        }
3229
3230        private void resetStandardTemplateWithActions(RemoteViews big) {
3231            big.setViewVisibility(R.id.actions, View.GONE);
3232            big.setViewVisibility(R.id.action_divider, View.GONE);
3233            big.removeAllViews(R.id.actions);
3234        }
3235
3236        private RemoteViews applyStandardTemplateWithActions(int layoutId) {
3237            RemoteViews big = applyStandardTemplate(layoutId);
3238
3239            resetStandardTemplateWithActions(big);
3240
3241            int N = mActions.size();
3242            if (N > 0) {
3243                big.setViewVisibility(R.id.actions, View.VISIBLE);
3244                big.setViewVisibility(R.id.action_divider, View.VISIBLE);
3245                if (N>MAX_ACTION_BUTTONS) N=MAX_ACTION_BUTTONS;
3246                for (int i=0; i<N; i++) {
3247                    final RemoteViews button = generateActionButton(mActions.get(i));
3248                    big.addView(R.id.actions, button);
3249                }
3250            }
3251            return big;
3252        }
3253
3254        /**
3255         * Construct a RemoteViews for the final 1U notification layout. In order:
3256         *   1. Custom contentView from the caller
3257         *   2. Style's proposed content view
3258         *   3. Standard template view
3259         */
3260        public RemoteViews makeContentView() {
3261            if (mN.contentView != null) {
3262                return mN.contentView;
3263            } else if (mStyle != null) {
3264                final RemoteViews styleView = mStyle.makeContentView();
3265                if (styleView != null) {
3266                    return styleView;
3267                }
3268            }
3269            return applyStandardTemplate(getBaseLayoutResource());
3270        }
3271
3272        /**
3273         * Construct a RemoteViews for the final big notification layout.
3274         */
3275        public RemoteViews makeBigContentView() {
3276            if (mStyle != null) {
3277                final RemoteViews styleView = mStyle.makeBigContentView();
3278                if (styleView != null) {
3279                    return styleView;
3280                }
3281            } else if (mActions.size() == 0) return null;
3282
3283            return applyStandardTemplateWithActions(getBigBaseLayoutResource());
3284        }
3285
3286        /**
3287         * Construct a RemoteViews for the final heads-up notification layout.
3288         */
3289        public RemoteViews makeHeadsUpContentView() {
3290            if (mStyle != null) {
3291                final RemoteViews styleView = mStyle.makeHeadsUpContentView();
3292                if (styleView != null) {
3293                    return styleView;
3294                }
3295            } else if (mActions.size() == 0) return null;
3296
3297            return applyStandardTemplateWithActions(getBigBaseLayoutResource());
3298        }
3299
3300
3301        private RemoteViews generateActionButton(Action action) {
3302            final boolean tombstone = (action.actionIntent == null);
3303            RemoteViews button = new BuilderRemoteViews(mContext.getApplicationInfo(),
3304                    tombstone ? getActionTombstoneLayoutResource()
3305                              : getActionLayoutResource());
3306            final Icon ai = action.getIcon();
3307            button.setTextViewCompoundDrawablesRelative(R.id.action0, ai, null, null, null);
3308            button.setTextViewText(R.id.action0, processLegacyText(action.title));
3309            if (!tombstone) {
3310                button.setOnClickPendingIntent(R.id.action0, action.actionIntent);
3311            }
3312            button.setContentDescription(R.id.action0, action.title);
3313            processLegacyAction(action, button);
3314            return button;
3315        }
3316
3317        /**
3318         * @return Whether we are currently building a notification from a legacy (an app that
3319         *         doesn't create material notifications by itself) app.
3320         */
3321        private boolean isLegacy() {
3322            return getColorUtil() != null;
3323        }
3324
3325        private void processLegacyAction(Action action, RemoteViews button) {
3326            if (!isLegacy() || getColorUtil().isGrayscaleIcon(mContext, action.getIcon())) {
3327                button.setTextViewCompoundDrawablesRelativeColorFilter(R.id.action0, 0,
3328                        mContext.getColor(R.color.notification_action_color_filter),
3329                        PorterDuff.Mode.MULTIPLY);
3330            }
3331        }
3332
3333        private CharSequence processLegacyText(CharSequence charSequence) {
3334            if (isLegacy()) {
3335                return getColorUtil().invertCharSequenceColors(charSequence);
3336            } else {
3337                return charSequence;
3338            }
3339        }
3340
3341        /**
3342         * Apply any necessary background to smallIcons being used in the largeIcon spot.
3343         */
3344        private void processSmallIconAsLarge(Icon largeIcon, RemoteViews contentView) {
3345            if (!isLegacy()) {
3346                contentView.setDrawableParameters(R.id.icon, false, -1,
3347                        0xFFFFFFFF,
3348                        PorterDuff.Mode.SRC_ATOP, -1);
3349                applyLargeIconBackground(contentView);
3350            } else {
3351                if (getColorUtil().isGrayscaleIcon(mContext, largeIcon)) {
3352                    applyLargeIconBackground(contentView);
3353                }
3354            }
3355        }
3356
3357        /**
3358         * Apply any necessary background to a largeIcon if it's a fake smallIcon (that is,
3359         * if it's grayscale).
3360         */
3361        // TODO: also check bounds, transparency, that sort of thing.
3362        private void processLargeLegacyIcon(Icon largeIcon, RemoteViews contentView) {
3363            if (largeIcon != null && isLegacy()
3364                    && getColorUtil().isGrayscaleIcon(mContext, largeIcon)) {
3365                applyLargeIconBackground(contentView);
3366            } else {
3367                removeLargeIconBackground(contentView);
3368            }
3369        }
3370
3371        /**
3372         * Add a colored circle behind the largeIcon slot.
3373         */
3374        private void applyLargeIconBackground(RemoteViews contentView) {
3375            contentView.setInt(R.id.icon, "setBackgroundResource",
3376                    R.drawable.notification_icon_legacy_bg);
3377
3378            contentView.setDrawableParameters(
3379                    R.id.icon,
3380                    true,
3381                    -1,
3382                    resolveColor(),
3383                    PorterDuff.Mode.SRC_ATOP,
3384                    -1);
3385
3386            int padding = mContext.getResources().getDimensionPixelSize(
3387                    R.dimen.notification_large_icon_circle_padding);
3388            contentView.setViewPadding(R.id.icon, padding, padding, padding, padding);
3389        }
3390
3391        private void removeLargeIconBackground(RemoteViews contentView) {
3392            contentView.setInt(R.id.icon, "setBackgroundResource", 0);
3393        }
3394
3395        /**
3396         * Recolor small icons when used in the R.id.right_icon slot.
3397         */
3398        private void processSmallRightIcon(Icon smallIcon, RemoteViews contentView) {
3399            if (!isLegacy()) {
3400                contentView.setDrawableParameters(R.id.right_icon, false, -1,
3401                        0xFFFFFFFF,
3402                        PorterDuff.Mode.SRC_ATOP, -1);
3403            }
3404            final boolean gray = isLegacy()
3405                    && smallIcon.getType() == Icon.TYPE_RESOURCE
3406                    && getColorUtil().isGrayscaleIcon(mContext, smallIcon.getResId());
3407            if (!isLegacy() || gray) {
3408                contentView.setInt(R.id.right_icon,
3409                        "setBackgroundResource",
3410                        R.drawable.notification_icon_legacy_bg);
3411
3412                contentView.setDrawableParameters(
3413                        R.id.right_icon,
3414                        true,
3415                        -1,
3416                        resolveColor(),
3417                        PorterDuff.Mode.SRC_ATOP,
3418                        -1);
3419            }
3420        }
3421
3422        private int sanitizeColor() {
3423            if (mN.color != COLOR_DEFAULT) {
3424                mN.color |= 0xFF000000; // no alpha for custom colors
3425            }
3426            return mN.color;
3427        }
3428
3429        private int resolveColor() {
3430            if (mN.color == COLOR_DEFAULT) {
3431                return mContext.getColor(R.color.notification_icon_bg_color);
3432            }
3433            return mN.color;
3434        }
3435
3436        /**
3437         * Apply the unstyled operations and return a new {@link Notification} object.
3438         * @hide
3439         */
3440        public Notification buildUnstyled() {
3441            if (mActions.size() > 0) {
3442                mN.actions = new Action[mActions.size()];
3443                mActions.toArray(mN.actions);
3444            }
3445            if (!mPersonList.isEmpty()) {
3446                mN.extras.putStringArray(EXTRA_PEOPLE,
3447                        mPersonList.toArray(new String[mPersonList.size()]));
3448            }
3449            if (mTopics.size() > 0) {
3450                mN.topics = new Topic[mTopics.size()];
3451                mTopics.toArray(mN.topics);
3452            }
3453            return mN;
3454        }
3455
3456        public static Notification.Builder recoverBuilder(Context context, Notification n) {
3457            // Re-create notification context so we can access app resources.
3458            ApplicationInfo applicationInfo = n.extras.getParcelable(
3459                    EXTRA_BUILDER_APPLICATION_INFO);
3460            Context builderContext;
3461            try {
3462                builderContext = context.createApplicationContext(applicationInfo,
3463                        Context.CONTEXT_RESTRICTED);
3464            } catch (NameNotFoundException e) {
3465                Log.e(TAG, "ApplicationInfo " + applicationInfo + " not found");
3466                builderContext = context;  // try with our context
3467            }
3468
3469            return new Builder(builderContext, n);
3470        }
3471
3472        private static Class<? extends Style> getNotificationStyleClass(String templateClass) {
3473            Class<? extends Style>[] classes = new Class[]{
3474                    BigTextStyle.class, BigPictureStyle.class, InboxStyle.class, MediaStyle.class};
3475            for (Class<? extends Style> innerClass : classes) {
3476                if (templateClass.equals(innerClass.getName())) {
3477                    return innerClass;
3478                }
3479            }
3480            return null;
3481        }
3482
3483        private void setBuilderContentView(Notification n, RemoteViews contentView) {
3484            n.contentView = contentView;
3485        }
3486
3487        private void setBuilderBigContentView(Notification n, RemoteViews bigContentView) {
3488            n.bigContentView = bigContentView;
3489        }
3490
3491        private void setBuilderHeadsUpContentView(Notification n,
3492                RemoteViews headsUpContentView) {
3493            n.headsUpContentView = headsUpContentView;
3494        }
3495
3496        /**
3497         * @deprecated Use {@link #build()} instead.
3498         */
3499        @Deprecated
3500        public Notification getNotification() {
3501            return build();
3502        }
3503
3504        /**
3505         * Combine all of the options that have been set and return a new {@link Notification}
3506         * object.
3507         */
3508        public Notification build() {
3509            // first, add any extras from the calling code
3510            if (mUserExtras != null) {
3511                mN.extras = getAllExtras();
3512            }
3513
3514            // lazy stuff from mContext; see comment in Builder(Context, Notification)
3515            mN.extras.putParcelable(EXTRA_BUILDER_APPLICATION_INFO, mContext.getApplicationInfo());
3516            mOriginatingUserId = mContext.getUserId();
3517            mN.extras.putInt(EXTRA_ORIGINATING_USERID, mOriginatingUserId);
3518
3519            buildUnstyled();
3520
3521            if (mStyle != null) {
3522                mStyle.buildStyled(mN);
3523            }
3524
3525            return mN;
3526        }
3527
3528        /**
3529         * Apply this Builder to an existing {@link Notification} object.
3530         *
3531         * @hide
3532         */
3533        public Notification buildInto(Notification n) {
3534            build().cloneInto(n, true);
3535            return n;
3536        }
3537
3538        private int getBaseLayoutResource() {
3539            return R.layout.notification_template_material_base;
3540        }
3541
3542        private int getBigBaseLayoutResource() {
3543            return R.layout.notification_template_material_big_base;
3544        }
3545
3546        private int getBigPictureLayoutResource() {
3547            return R.layout.notification_template_material_big_picture;
3548        }
3549
3550        private int getBigTextLayoutResource() {
3551            return R.layout.notification_template_material_big_text;
3552        }
3553
3554        private int getInboxLayoutResource() {
3555            return R.layout.notification_template_material_inbox;
3556        }
3557
3558        private int getActionLayoutResource() {
3559            return R.layout.notification_material_action;
3560        }
3561
3562        private int getActionTombstoneLayoutResource() {
3563            return R.layout.notification_material_action_tombstone;
3564        }
3565    }
3566
3567    /**
3568     * An object that can apply a rich notification style to a {@link Notification.Builder}
3569     * object.
3570     */
3571    public static abstract class Style {
3572        private CharSequence mBigContentTitle;
3573
3574        /**
3575         * @hide
3576         */
3577        protected CharSequence mSummaryText = null;
3578
3579        /**
3580         * @hide
3581         */
3582        protected boolean mSummaryTextSet = false;
3583
3584        protected Builder mBuilder;
3585
3586        /**
3587         * Overrides ContentTitle in the big form of the template.
3588         * This defaults to the value passed to setContentTitle().
3589         */
3590        protected void internalSetBigContentTitle(CharSequence title) {
3591            mBigContentTitle = title;
3592        }
3593
3594        /**
3595         * Set the first line of text after the detail section in the big form of the template.
3596         */
3597        protected void internalSetSummaryText(CharSequence cs) {
3598            mSummaryText = cs;
3599            mSummaryTextSet = true;
3600        }
3601
3602        public void setBuilder(Builder builder) {
3603            if (mBuilder != builder) {
3604                mBuilder = builder;
3605                if (mBuilder != null) {
3606                    mBuilder.setStyle(this);
3607                }
3608            }
3609        }
3610
3611        protected void checkBuilder() {
3612            if (mBuilder == null) {
3613                throw new IllegalArgumentException("Style requires a valid Builder object");
3614            }
3615        }
3616
3617        protected RemoteViews getStandardView(int layoutId) {
3618            checkBuilder();
3619
3620            // Nasty.
3621            CharSequence oldBuilderContentTitle =
3622                    mBuilder.getAllExtras().getCharSequence(EXTRA_TITLE);
3623            if (mBigContentTitle != null) {
3624                mBuilder.setContentTitle(mBigContentTitle);
3625            }
3626
3627            RemoteViews contentView = mBuilder.applyStandardTemplateWithActions(layoutId);
3628
3629            mBuilder.getAllExtras().putCharSequence(EXTRA_TITLE, oldBuilderContentTitle);
3630
3631            if (mBigContentTitle != null && mBigContentTitle.equals("")) {
3632                contentView.setViewVisibility(R.id.line1, View.GONE);
3633            } else {
3634                contentView.setViewVisibility(R.id.line1, View.VISIBLE);
3635            }
3636
3637            // The last line defaults to the subtext, but can be replaced by mSummaryText
3638            final CharSequence overflowText =
3639                    mSummaryTextSet ? mSummaryText
3640                                    : mBuilder.getAllExtras().getCharSequence(EXTRA_SUB_TEXT);
3641            if (overflowText != null) {
3642                contentView.setTextViewText(R.id.text, mBuilder.processLegacyText(overflowText));
3643                contentView.setViewVisibility(R.id.overflow_divider, View.VISIBLE);
3644                contentView.setViewVisibility(R.id.line3, View.VISIBLE);
3645            } else {
3646                // Clear text in case we use the line to show the profile badge.
3647                contentView.setTextViewText(R.id.text, "");
3648                contentView.setViewVisibility(R.id.overflow_divider, View.GONE);
3649                contentView.setViewVisibility(R.id.line3, View.GONE);
3650            }
3651
3652            return contentView;
3653        }
3654
3655        /**
3656         * Construct a Style-specific RemoteViews for the final 1U notification layout.
3657         * The default implementation has nothing additional to add.
3658         * @hide
3659         */
3660        public RemoteViews makeContentView() {
3661            return null;
3662        }
3663
3664        /**
3665         * Construct a Style-specific RemoteViews for the final big notification layout.
3666         * @hide
3667         */
3668        public RemoteViews makeBigContentView() {
3669            return null;
3670        }
3671
3672        /**
3673         * Construct a Style-specific RemoteViews for the final HUN layout.
3674         * @hide
3675         */
3676        public RemoteViews makeHeadsUpContentView() {
3677            return null;
3678        }
3679
3680        /**
3681         * Changes the padding of the first line such that the big and small content view have the
3682         * same top padding.
3683         *
3684         * @hide
3685         */
3686        protected void applyTopPadding(RemoteViews contentView) {
3687            int topPadding = Builder.calculateTopPadding(mBuilder.mContext,
3688                    mBuilder.hasThreeLines(),
3689                    mBuilder.mContext.getResources().getConfiguration().fontScale);
3690            contentView.setViewPadding(R.id.line1, 0, topPadding, 0, 0);
3691        }
3692
3693        /**
3694         * Apply any style-specific extras to this notification before shipping it out.
3695         * @hide
3696         */
3697        public void addExtras(Bundle extras) {
3698            if (mSummaryTextSet) {
3699                extras.putCharSequence(EXTRA_SUMMARY_TEXT, mSummaryText);
3700            }
3701            if (mBigContentTitle != null) {
3702                extras.putCharSequence(EXTRA_TITLE_BIG, mBigContentTitle);
3703            }
3704            extras.putString(EXTRA_TEMPLATE, this.getClass().getName());
3705        }
3706
3707        /**
3708         * Reconstruct the internal state of this Style object from extras.
3709         * @hide
3710         */
3711        protected void restoreFromExtras(Bundle extras) {
3712            if (extras.containsKey(EXTRA_SUMMARY_TEXT)) {
3713                mSummaryText = extras.getCharSequence(EXTRA_SUMMARY_TEXT);
3714                mSummaryTextSet = true;
3715            }
3716            if (extras.containsKey(EXTRA_TITLE_BIG)) {
3717                mBigContentTitle = extras.getCharSequence(EXTRA_TITLE_BIG);
3718            }
3719        }
3720
3721
3722        /**
3723         * @hide
3724         */
3725        public Notification buildStyled(Notification wip) {
3726            addExtras(wip.extras);
3727            return wip;
3728        }
3729
3730        /**
3731         * @hide
3732         */
3733        public void purgeResources() {}
3734
3735        /**
3736         * Calls {@link android.app.Notification.Builder#build()} on the Builder this Style is
3737         * attached to.
3738         *
3739         * @return the fully constructed Notification.
3740         */
3741        public Notification build() {
3742            checkBuilder();
3743            return mBuilder.build();
3744        }
3745
3746        /**
3747         * @hide
3748         * @return true if the style positions the progress bar on the second line; false if the
3749         *         style hides the progress bar
3750         */
3751        protected boolean hasProgress() {
3752            return true;
3753        }
3754    }
3755
3756    /**
3757     * Helper class for generating large-format notifications that include a large image attachment.
3758     *
3759     * Here's how you'd set the <code>BigPictureStyle</code> on a notification:
3760     * <pre class="prettyprint">
3761     * Notification notif = new Notification.Builder(mContext)
3762     *     .setContentTitle(&quot;New photo from &quot; + sender.toString())
3763     *     .setContentText(subject)
3764     *     .setSmallIcon(R.drawable.new_post)
3765     *     .setLargeIcon(aBitmap)
3766     *     .setStyle(new Notification.BigPictureStyle()
3767     *         .bigPicture(aBigBitmap))
3768     *     .build();
3769     * </pre>
3770     *
3771     * @see Notification#bigContentView
3772     */
3773    public static class BigPictureStyle extends Style {
3774        private Bitmap mPicture;
3775        private Icon mBigLargeIcon;
3776        private boolean mBigLargeIconSet = false;
3777
3778        public BigPictureStyle() {
3779        }
3780
3781        public BigPictureStyle(Builder builder) {
3782            setBuilder(builder);
3783        }
3784
3785        /**
3786         * Overrides ContentTitle in the big form of the template.
3787         * This defaults to the value passed to setContentTitle().
3788         */
3789        public BigPictureStyle setBigContentTitle(CharSequence title) {
3790            internalSetBigContentTitle(safeCharSequence(title));
3791            return this;
3792        }
3793
3794        /**
3795         * Set the first line of text after the detail section in the big form of the template.
3796         */
3797        public BigPictureStyle setSummaryText(CharSequence cs) {
3798            internalSetSummaryText(safeCharSequence(cs));
3799            return this;
3800        }
3801
3802        /**
3803         * Provide the bitmap to be used as the payload for the BigPicture notification.
3804         */
3805        public BigPictureStyle bigPicture(Bitmap b) {
3806            mPicture = b;
3807            return this;
3808        }
3809
3810        /**
3811         * Override the large icon when the big notification is shown.
3812         */
3813        public BigPictureStyle bigLargeIcon(Bitmap b) {
3814            return bigLargeIcon(b != null ? Icon.createWithBitmap(b) : null);
3815        }
3816
3817        /**
3818         * Override the large icon when the big notification is shown.
3819         */
3820        public BigPictureStyle bigLargeIcon(Icon icon) {
3821            mBigLargeIconSet = true;
3822            mBigLargeIcon = icon;
3823            return this;
3824        }
3825
3826        /**
3827         * @hide
3828         */
3829        @Override
3830        public void purgeResources() {
3831            super.purgeResources();
3832            if (mPicture != null &&
3833                mPicture.isMutable() &&
3834                mPicture.getAllocationByteCount() >= (128 * (1 << 10))) {
3835                mPicture = mPicture.createAshmemBitmap();
3836            }
3837            if (mBigLargeIcon != null) {
3838                mBigLargeIcon.convertToAshmem();
3839            }
3840        }
3841
3842        /**
3843         * @hide
3844         */
3845        public RemoteViews makeBigContentView() {
3846            // Replace mN.mLargeIcon with mBigLargeIcon if mBigLargeIconSet
3847            // This covers the following cases:
3848            //   1. mBigLargeIconSet -> mBigLargeIcon (null or non-null) applies, overrides
3849            //          mN.mLargeIcon
3850            //   2. !mBigLargeIconSet -> mN.mLargeIcon applies
3851            Icon oldLargeIcon = null;
3852            if (mBigLargeIconSet) {
3853                oldLargeIcon = mBuilder.mN.mLargeIcon;
3854                mBuilder.mN.mLargeIcon = mBigLargeIcon;
3855            }
3856
3857            RemoteViews contentView = getStandardView(mBuilder.getBigPictureLayoutResource());
3858
3859            if (mBigLargeIconSet) {
3860                mBuilder.mN.mLargeIcon = oldLargeIcon;
3861            }
3862
3863            contentView.setImageViewBitmap(R.id.big_picture, mPicture);
3864
3865            applyTopPadding(contentView);
3866
3867            boolean twoTextLines = mBuilder.getAllExtras().getCharSequence(EXTRA_SUB_TEXT) != null
3868                    && mBuilder.getAllExtras().getCharSequence(EXTRA_TEXT) != null;
3869            mBuilder.addProfileBadge(contentView,
3870                    twoTextLines ? R.id.profile_badge_line2 : R.id.profile_badge_line3);
3871            return contentView;
3872        }
3873
3874        /**
3875         * @hide
3876         */
3877        public void addExtras(Bundle extras) {
3878            super.addExtras(extras);
3879
3880            if (mBigLargeIconSet) {
3881                extras.putParcelable(EXTRA_LARGE_ICON_BIG, mBigLargeIcon);
3882            }
3883            extras.putParcelable(EXTRA_PICTURE, mPicture);
3884        }
3885
3886        /**
3887         * @hide
3888         */
3889        @Override
3890        protected void restoreFromExtras(Bundle extras) {
3891            super.restoreFromExtras(extras);
3892
3893            if (extras.containsKey(EXTRA_LARGE_ICON_BIG)) {
3894                mBigLargeIconSet = true;
3895                mBigLargeIcon = extras.getParcelable(EXTRA_LARGE_ICON_BIG);
3896            }
3897            mPicture = extras.getParcelable(EXTRA_PICTURE);
3898        }
3899    }
3900
3901    /**
3902     * Helper class for generating large-format notifications that include a lot of text.
3903     *
3904     * Here's how you'd set the <code>BigTextStyle</code> on a notification:
3905     * <pre class="prettyprint">
3906     * Notification notif = new Notification.Builder(mContext)
3907     *     .setContentTitle(&quot;New mail from &quot; + sender.toString())
3908     *     .setContentText(subject)
3909     *     .setSmallIcon(R.drawable.new_mail)
3910     *     .setLargeIcon(aBitmap)
3911     *     .setStyle(new Notification.BigTextStyle()
3912     *         .bigText(aVeryLongString))
3913     *     .build();
3914     * </pre>
3915     *
3916     * @see Notification#bigContentView
3917     */
3918    public static class BigTextStyle extends Style {
3919
3920        private static final int MAX_LINES = 13;
3921        private static final int LINES_CONSUMED_BY_ACTIONS = 3;
3922        private static final int LINES_CONSUMED_BY_SUMMARY = 2;
3923
3924        private CharSequence mBigText;
3925
3926        public BigTextStyle() {
3927        }
3928
3929        public BigTextStyle(Builder builder) {
3930            setBuilder(builder);
3931        }
3932
3933        /**
3934         * Overrides ContentTitle in the big form of the template.
3935         * This defaults to the value passed to setContentTitle().
3936         */
3937        public BigTextStyle setBigContentTitle(CharSequence title) {
3938            internalSetBigContentTitle(safeCharSequence(title));
3939            return this;
3940        }
3941
3942        /**
3943         * Set the first line of text after the detail section in the big form of the template.
3944         */
3945        public BigTextStyle setSummaryText(CharSequence cs) {
3946            internalSetSummaryText(safeCharSequence(cs));
3947            return this;
3948        }
3949
3950        /**
3951         * Provide the longer text to be displayed in the big form of the
3952         * template in place of the content text.
3953         */
3954        public BigTextStyle bigText(CharSequence cs) {
3955            mBigText = safeCharSequence(cs);
3956            return this;
3957        }
3958
3959        /**
3960         * @hide
3961         */
3962        public void addExtras(Bundle extras) {
3963            super.addExtras(extras);
3964
3965            extras.putCharSequence(EXTRA_BIG_TEXT, mBigText);
3966        }
3967
3968        /**
3969         * @hide
3970         */
3971        @Override
3972        protected void restoreFromExtras(Bundle extras) {
3973            super.restoreFromExtras(extras);
3974
3975            mBigText = extras.getCharSequence(EXTRA_BIG_TEXT);
3976        }
3977
3978        /**
3979         * @hide
3980         */
3981        public RemoteViews makeBigContentView() {
3982
3983            // Nasty
3984            CharSequence oldBuilderContentText =
3985                    mBuilder.getAllExtras().getCharSequence(EXTRA_TEXT);
3986            mBuilder.getAllExtras().putCharSequence(EXTRA_TEXT, null);
3987
3988            RemoteViews contentView = getStandardView(mBuilder.getBigTextLayoutResource());
3989
3990            mBuilder.getAllExtras().putCharSequence(EXTRA_TEXT, oldBuilderContentText);
3991
3992            contentView.setTextViewText(R.id.big_text, mBuilder.processLegacyText(mBigText));
3993            contentView.setViewVisibility(R.id.big_text, View.VISIBLE);
3994            contentView.setInt(R.id.big_text, "setMaxLines", calculateMaxLines());
3995            contentView.setViewVisibility(R.id.text2, View.GONE);
3996
3997            applyTopPadding(contentView);
3998
3999            mBuilder.shrinkLine3Text(contentView);
4000
4001            mBuilder.addProfileBadge(contentView, R.id.profile_badge_large_template);
4002
4003            return contentView;
4004        }
4005
4006        private int calculateMaxLines() {
4007            int lineCount = MAX_LINES;
4008            boolean hasActions = mBuilder.mActions.size() > 0;
4009            boolean hasSummary = (mSummaryTextSet ? mSummaryText
4010                    : mBuilder.getAllExtras().getCharSequence(EXTRA_SUB_TEXT)) != null;
4011            if (hasActions) {
4012                lineCount -= LINES_CONSUMED_BY_ACTIONS;
4013            }
4014            if (hasSummary) {
4015                lineCount -= LINES_CONSUMED_BY_SUMMARY;
4016            }
4017
4018            // If we have less top padding at the top, we can fit less lines.
4019            if (!mBuilder.hasThreeLines()) {
4020                lineCount--;
4021            }
4022            return lineCount;
4023        }
4024    }
4025
4026    /**
4027     * Helper class for generating large-format notifications that include a list of (up to 5) strings.
4028     *
4029     * Here's how you'd set the <code>InboxStyle</code> on a notification:
4030     * <pre class="prettyprint">
4031     * Notification notif = new Notification.Builder(mContext)
4032     *     .setContentTitle(&quot;5 New mails from &quot; + sender.toString())
4033     *     .setContentText(subject)
4034     *     .setSmallIcon(R.drawable.new_mail)
4035     *     .setLargeIcon(aBitmap)
4036     *     .setStyle(new Notification.InboxStyle()
4037     *         .addLine(str1)
4038     *         .addLine(str2)
4039     *         .setContentTitle(&quot;&quot;)
4040     *         .setSummaryText(&quot;+3 more&quot;))
4041     *     .build();
4042     * </pre>
4043     *
4044     * @see Notification#bigContentView
4045     */
4046    public static class InboxStyle extends Style {
4047        private ArrayList<CharSequence> mTexts = new ArrayList<CharSequence>(5);
4048
4049        public InboxStyle() {
4050        }
4051
4052        public InboxStyle(Builder builder) {
4053            setBuilder(builder);
4054        }
4055
4056        /**
4057         * Overrides ContentTitle in the big form of the template.
4058         * This defaults to the value passed to setContentTitle().
4059         */
4060        public InboxStyle setBigContentTitle(CharSequence title) {
4061            internalSetBigContentTitle(safeCharSequence(title));
4062            return this;
4063        }
4064
4065        /**
4066         * Set the first line of text after the detail section in the big form of the template.
4067         */
4068        public InboxStyle setSummaryText(CharSequence cs) {
4069            internalSetSummaryText(safeCharSequence(cs));
4070            return this;
4071        }
4072
4073        /**
4074         * Append a line to the digest section of the Inbox notification.
4075         */
4076        public InboxStyle addLine(CharSequence cs) {
4077            mTexts.add(safeCharSequence(cs));
4078            return this;
4079        }
4080
4081        /**
4082         * @hide
4083         */
4084        public void addExtras(Bundle extras) {
4085            super.addExtras(extras);
4086
4087            CharSequence[] a = new CharSequence[mTexts.size()];
4088            extras.putCharSequenceArray(EXTRA_TEXT_LINES, mTexts.toArray(a));
4089        }
4090
4091        /**
4092         * @hide
4093         */
4094        @Override
4095        protected void restoreFromExtras(Bundle extras) {
4096            super.restoreFromExtras(extras);
4097
4098            mTexts.clear();
4099            if (extras.containsKey(EXTRA_TEXT_LINES)) {
4100                Collections.addAll(mTexts, extras.getCharSequenceArray(EXTRA_TEXT_LINES));
4101            }
4102        }
4103
4104        /**
4105         * @hide
4106         */
4107        public RemoteViews makeBigContentView() {
4108            // Remove the content text so line3 disappears unless you have a summary
4109            // Nasty
4110            CharSequence oldBuilderContentText = mBuilder.mN.extras.getCharSequence(EXTRA_TEXT);
4111            mBuilder.getAllExtras().putCharSequence(EXTRA_TEXT, null);
4112
4113            RemoteViews contentView = getStandardView(mBuilder.getInboxLayoutResource());
4114
4115            mBuilder.getAllExtras().putCharSequence(EXTRA_TEXT, oldBuilderContentText);
4116
4117            contentView.setViewVisibility(R.id.text2, View.GONE);
4118
4119            int[] rowIds = {R.id.inbox_text0, R.id.inbox_text1, R.id.inbox_text2, R.id.inbox_text3,
4120                    R.id.inbox_text4, R.id.inbox_text5, R.id.inbox_text6};
4121
4122            // Make sure all rows are gone in case we reuse a view.
4123            for (int rowId : rowIds) {
4124                contentView.setViewVisibility(rowId, View.GONE);
4125            }
4126
4127            final boolean largeText =
4128                    mBuilder.mContext.getResources().getConfiguration().fontScale > 1f;
4129            final float subTextSize = mBuilder.mContext.getResources().getDimensionPixelSize(
4130                    R.dimen.notification_subtext_size);
4131            int i=0;
4132            while (i < mTexts.size() && i < rowIds.length) {
4133                CharSequence str = mTexts.get(i);
4134                if (str != null && !str.equals("")) {
4135                    contentView.setViewVisibility(rowIds[i], View.VISIBLE);
4136                    contentView.setTextViewText(rowIds[i], mBuilder.processLegacyText(str));
4137                    if (largeText) {
4138                        contentView.setTextViewTextSize(rowIds[i], TypedValue.COMPLEX_UNIT_PX,
4139                                subTextSize);
4140                    }
4141                }
4142                i++;
4143            }
4144
4145            contentView.setViewVisibility(R.id.inbox_end_pad,
4146                    mTexts.size() > 0 ? View.VISIBLE : View.GONE);
4147
4148            contentView.setViewVisibility(R.id.inbox_more,
4149                    mTexts.size() > rowIds.length ? View.VISIBLE : View.GONE);
4150
4151            applyTopPadding(contentView);
4152
4153            mBuilder.shrinkLine3Text(contentView);
4154
4155            mBuilder.addProfileBadge(contentView, R.id.profile_badge_large_template);
4156
4157            return contentView;
4158        }
4159    }
4160
4161    /**
4162     * Notification style for media playback notifications.
4163     *
4164     * In the expanded form, {@link Notification#bigContentView}, up to 5
4165     * {@link Notification.Action}s specified with
4166     * {@link Notification.Builder#addAction(Action) addAction} will be
4167     * shown as icon-only pushbuttons, suitable for transport controls. The Bitmap given to
4168     * {@link Notification.Builder#setLargeIcon(android.graphics.Bitmap) setLargeIcon()} will be
4169     * treated as album artwork.
4170     *
4171     * Unlike the other styles provided here, MediaStyle can also modify the standard-size
4172     * {@link Notification#contentView}; by providing action indices to
4173     * {@link #setShowActionsInCompactView(int...)} you can promote up to 3 actions to be displayed
4174     * in the standard view alongside the usual content.
4175     *
4176     * Notifications created with MediaStyle will have their category set to
4177     * {@link Notification#CATEGORY_TRANSPORT CATEGORY_TRANSPORT} unless you set a different
4178     * category using {@link Notification.Builder#setCategory(String) setCategory()}.
4179     *
4180     * Finally, if you attach a {@link android.media.session.MediaSession.Token} using
4181     * {@link android.app.Notification.MediaStyle#setMediaSession(MediaSession.Token)},
4182     * the System UI can identify this as a notification representing an active media session
4183     * and respond accordingly (by showing album artwork in the lockscreen, for example).
4184     *
4185     * To use this style with your Notification, feed it to
4186     * {@link Notification.Builder#setStyle(android.app.Notification.Style)} like so:
4187     * <pre class="prettyprint">
4188     * Notification noti = new Notification.Builder()
4189     *     .setSmallIcon(R.drawable.ic_stat_player)
4190     *     .setContentTitle(&quot;Track title&quot;)
4191     *     .setContentText(&quot;Artist - Album&quot;)
4192     *     .setLargeIcon(albumArtBitmap))
4193     *     .setStyle(<b>new Notification.MediaStyle()</b>
4194     *         .setMediaSession(mySession))
4195     *     .build();
4196     * </pre>
4197     *
4198     * @see Notification#bigContentView
4199     */
4200    public static class MediaStyle extends Style {
4201        static final int MAX_MEDIA_BUTTONS_IN_COMPACT = 3;
4202        static final int MAX_MEDIA_BUTTONS = 5;
4203
4204        private int[] mActionsToShowInCompact = null;
4205        private MediaSession.Token mToken;
4206
4207        public MediaStyle() {
4208        }
4209
4210        public MediaStyle(Builder builder) {
4211            setBuilder(builder);
4212        }
4213
4214        /**
4215         * Request up to 3 actions (by index in the order of addition) to be shown in the compact
4216         * notification view.
4217         *
4218         * @param actions the indices of the actions to show in the compact notification view
4219         */
4220        public MediaStyle setShowActionsInCompactView(int...actions) {
4221            mActionsToShowInCompact = actions;
4222            return this;
4223        }
4224
4225        /**
4226         * Attach a {@link android.media.session.MediaSession.Token} to this Notification
4227         * to provide additional playback information and control to the SystemUI.
4228         */
4229        public MediaStyle setMediaSession(MediaSession.Token token) {
4230            mToken = token;
4231            return this;
4232        }
4233
4234        /**
4235         * @hide
4236         */
4237        @Override
4238        public Notification buildStyled(Notification wip) {
4239            super.buildStyled(wip);
4240            if (wip.category == null) {
4241                wip.category = Notification.CATEGORY_TRANSPORT;
4242            }
4243            return wip;
4244        }
4245
4246        /**
4247         * @hide
4248         */
4249        @Override
4250        public RemoteViews makeContentView() {
4251            return makeMediaContentView();
4252        }
4253
4254        /**
4255         * @hide
4256         */
4257        @Override
4258        public RemoteViews makeBigContentView() {
4259            return makeMediaBigContentView();
4260        }
4261
4262        /** @hide */
4263        @Override
4264        public void addExtras(Bundle extras) {
4265            super.addExtras(extras);
4266
4267            if (mToken != null) {
4268                extras.putParcelable(EXTRA_MEDIA_SESSION, mToken);
4269            }
4270            if (mActionsToShowInCompact != null) {
4271                extras.putIntArray(EXTRA_COMPACT_ACTIONS, mActionsToShowInCompact);
4272            }
4273        }
4274
4275        /**
4276         * @hide
4277         */
4278        @Override
4279        protected void restoreFromExtras(Bundle extras) {
4280            super.restoreFromExtras(extras);
4281
4282            if (extras.containsKey(EXTRA_MEDIA_SESSION)) {
4283                mToken = extras.getParcelable(EXTRA_MEDIA_SESSION);
4284            }
4285            if (extras.containsKey(EXTRA_COMPACT_ACTIONS)) {
4286                mActionsToShowInCompact = extras.getIntArray(EXTRA_COMPACT_ACTIONS);
4287            }
4288        }
4289
4290        private RemoteViews generateMediaActionButton(Action action) {
4291            final boolean tombstone = (action.actionIntent == null);
4292            RemoteViews button = new BuilderRemoteViews(mBuilder.mContext.getApplicationInfo(),
4293                    R.layout.notification_material_media_action);
4294            button.setImageViewIcon(R.id.action0, action.getIcon());
4295            button.setDrawableParameters(R.id.action0, false, -1,
4296                    0xFFFFFFFF,
4297                    PorterDuff.Mode.SRC_ATOP, -1);
4298            if (!tombstone) {
4299                button.setOnClickPendingIntent(R.id.action0, action.actionIntent);
4300            }
4301            button.setContentDescription(R.id.action0, action.title);
4302            return button;
4303        }
4304
4305        private RemoteViews makeMediaContentView() {
4306            RemoteViews view = mBuilder.applyStandardTemplate(
4307                    R.layout.notification_template_material_media, false /* hasProgress */);
4308
4309            final int numActions = mBuilder.mActions.size();
4310            final int N = mActionsToShowInCompact == null
4311                    ? 0
4312                    : Math.min(mActionsToShowInCompact.length, MAX_MEDIA_BUTTONS_IN_COMPACT);
4313            if (N > 0) {
4314                view.removeAllViews(com.android.internal.R.id.media_actions);
4315                for (int i = 0; i < N; i++) {
4316                    if (i >= numActions) {
4317                        throw new IllegalArgumentException(String.format(
4318                                "setShowActionsInCompactView: action %d out of bounds (max %d)",
4319                                i, numActions - 1));
4320                    }
4321
4322                    final Action action = mBuilder.mActions.get(mActionsToShowInCompact[i]);
4323                    final RemoteViews button = generateMediaActionButton(action);
4324                    view.addView(com.android.internal.R.id.media_actions, button);
4325                }
4326            }
4327            styleText(view);
4328            hideRightIcon(view);
4329            return view;
4330        }
4331
4332        private RemoteViews makeMediaBigContentView() {
4333            final int actionCount = Math.min(mBuilder.mActions.size(), MAX_MEDIA_BUTTONS);
4334            RemoteViews big = mBuilder.applyStandardTemplate(getBigLayoutResource(actionCount),
4335                    false /* hasProgress */);
4336
4337            if (actionCount > 0) {
4338                big.removeAllViews(com.android.internal.R.id.media_actions);
4339                for (int i = 0; i < actionCount; i++) {
4340                    final RemoteViews button = generateMediaActionButton(mBuilder.mActions.get(i));
4341                    big.addView(com.android.internal.R.id.media_actions, button);
4342                }
4343            }
4344            styleText(big);
4345            hideRightIcon(big);
4346            applyTopPadding(big);
4347            big.setViewVisibility(android.R.id.progress, View.GONE);
4348            return big;
4349        }
4350
4351        private int getBigLayoutResource(int actionCount) {
4352            if (actionCount <= 3) {
4353                return R.layout.notification_template_material_big_media_narrow;
4354            } else {
4355                return R.layout.notification_template_material_big_media;
4356            }
4357        }
4358
4359        private void hideRightIcon(RemoteViews contentView) {
4360            contentView.setViewVisibility(R.id.right_icon, View.GONE);
4361        }
4362
4363        /**
4364         * Applies the special text colors for media notifications to all text views.
4365         */
4366        private void styleText(RemoteViews contentView) {
4367            int primaryColor = mBuilder.mContext.getColor(
4368                    R.color.notification_media_primary_color);
4369            int secondaryColor = mBuilder.mContext.getColor(
4370                    R.color.notification_media_secondary_color);
4371            contentView.setTextColor(R.id.title, primaryColor);
4372            if (mBuilder.showsTimeOrChronometer()) {
4373                if (mBuilder.getAllExtras().getBoolean(EXTRA_SHOW_CHRONOMETER)) {
4374                    contentView.setTextColor(R.id.chronometer, secondaryColor);
4375                } else {
4376                    contentView.setTextColor(R.id.time, secondaryColor);
4377                }
4378            }
4379            contentView.setTextColor(R.id.text2, secondaryColor);
4380            contentView.setTextColor(R.id.text, secondaryColor);
4381            contentView.setTextColor(R.id.info, secondaryColor);
4382        }
4383
4384        /**
4385         * @hide
4386         */
4387        @Override
4388        protected boolean hasProgress() {
4389            return false;
4390        }
4391    }
4392
4393    // When adding a new Style subclass here, don't forget to update
4394    // Builder.getNotificationStyleClass.
4395
4396    /**
4397     * Extender interface for use with {@link Builder#extend}. Extenders may be used to add
4398     * metadata or change options on a notification builder.
4399     */
4400    public interface Extender {
4401        /**
4402         * Apply this extender to a notification builder.
4403         * @param builder the builder to be modified.
4404         * @return the build object for chaining.
4405         */
4406        public Builder extend(Builder builder);
4407    }
4408
4409    /**
4410     * Helper class to add wearable extensions to notifications.
4411     * <p class="note"> See
4412     * <a href="{@docRoot}wear/notifications/creating.html">Creating Notifications
4413     * for Android Wear</a> for more information on how to use this class.
4414     * <p>
4415     * To create a notification with wearable extensions:
4416     * <ol>
4417     *   <li>Create a {@link android.app.Notification.Builder}, setting any desired
4418     *   properties.
4419     *   <li>Create a {@link android.app.Notification.WearableExtender}.
4420     *   <li>Set wearable-specific properties using the
4421     *   {@code add} and {@code set} methods of {@link android.app.Notification.WearableExtender}.
4422     *   <li>Call {@link android.app.Notification.Builder#extend} to apply the extensions to a
4423     *   notification.
4424     *   <li>Post the notification to the notification system with the
4425     *   {@code NotificationManager.notify(...)} methods.
4426     * </ol>
4427     *
4428     * <pre class="prettyprint">
4429     * Notification notif = new Notification.Builder(mContext)
4430     *         .setContentTitle(&quot;New mail from &quot; + sender.toString())
4431     *         .setContentText(subject)
4432     *         .setSmallIcon(R.drawable.new_mail)
4433     *         .extend(new Notification.WearableExtender()
4434     *                 .setContentIcon(R.drawable.new_mail))
4435     *         .build();
4436     * NotificationManager notificationManger =
4437     *         (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
4438     * notificationManger.notify(0, notif);</pre>
4439     *
4440     * <p>Wearable extensions can be accessed on an existing notification by using the
4441     * {@code WearableExtender(Notification)} constructor,
4442     * and then using the {@code get} methods to access values.
4443     *
4444     * <pre class="prettyprint">
4445     * Notification.WearableExtender wearableExtender = new Notification.WearableExtender(
4446     *         notification);
4447     * List&lt;Notification&gt; pages = wearableExtender.getPages();</pre>
4448     */
4449    public static final class WearableExtender implements Extender {
4450        /**
4451         * Sentinel value for an action index that is unset.
4452         */
4453        public static final int UNSET_ACTION_INDEX = -1;
4454
4455        /**
4456         * Size value for use with {@link #setCustomSizePreset} to show this notification with
4457         * default sizing.
4458         * <p>For custom display notifications created using {@link #setDisplayIntent},
4459         * the default is {@link #SIZE_MEDIUM}. All other notifications size automatically based
4460         * on their content.
4461         */
4462        public static final int SIZE_DEFAULT = 0;
4463
4464        /**
4465         * Size value for use with {@link #setCustomSizePreset} to show this notification
4466         * with an extra small size.
4467         * <p>This value is only applicable for custom display notifications created using
4468         * {@link #setDisplayIntent}.
4469         */
4470        public static final int SIZE_XSMALL = 1;
4471
4472        /**
4473         * Size value for use with {@link #setCustomSizePreset} to show this notification
4474         * with a small size.
4475         * <p>This value is only applicable for custom display notifications created using
4476         * {@link #setDisplayIntent}.
4477         */
4478        public static final int SIZE_SMALL = 2;
4479
4480        /**
4481         * Size value for use with {@link #setCustomSizePreset} to show this notification
4482         * with a medium size.
4483         * <p>This value is only applicable for custom display notifications created using
4484         * {@link #setDisplayIntent}.
4485         */
4486        public static final int SIZE_MEDIUM = 3;
4487
4488        /**
4489         * Size value for use with {@link #setCustomSizePreset} to show this notification
4490         * with a large size.
4491         * <p>This value is only applicable for custom display notifications created using
4492         * {@link #setDisplayIntent}.
4493         */
4494        public static final int SIZE_LARGE = 4;
4495
4496        /**
4497         * Size value for use with {@link #setCustomSizePreset} to show this notification
4498         * full screen.
4499         * <p>This value is only applicable for custom display notifications created using
4500         * {@link #setDisplayIntent}.
4501         */
4502        public static final int SIZE_FULL_SCREEN = 5;
4503
4504        /**
4505         * Sentinel value for use with {@link #setHintScreenTimeout} to keep the screen on for a
4506         * short amount of time when this notification is displayed on the screen. This
4507         * is the default value.
4508         */
4509        public static final int SCREEN_TIMEOUT_SHORT = 0;
4510
4511        /**
4512         * Sentinel value for use with {@link #setHintScreenTimeout} to keep the screen on
4513         * for a longer amount of time when this notification is displayed on the screen.
4514         */
4515        public static final int SCREEN_TIMEOUT_LONG = -1;
4516
4517        /** Notification extra which contains wearable extensions */
4518        private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS";
4519
4520        // Keys within EXTRA_WEARABLE_EXTENSIONS for wearable options.
4521        private static final String KEY_ACTIONS = "actions";
4522        private static final String KEY_FLAGS = "flags";
4523        private static final String KEY_DISPLAY_INTENT = "displayIntent";
4524        private static final String KEY_PAGES = "pages";
4525        private static final String KEY_BACKGROUND = "background";
4526        private static final String KEY_CONTENT_ICON = "contentIcon";
4527        private static final String KEY_CONTENT_ICON_GRAVITY = "contentIconGravity";
4528        private static final String KEY_CONTENT_ACTION_INDEX = "contentActionIndex";
4529        private static final String KEY_CUSTOM_SIZE_PRESET = "customSizePreset";
4530        private static final String KEY_CUSTOM_CONTENT_HEIGHT = "customContentHeight";
4531        private static final String KEY_GRAVITY = "gravity";
4532        private static final String KEY_HINT_SCREEN_TIMEOUT = "hintScreenTimeout";
4533
4534        // Flags bitwise-ored to mFlags
4535        private static final int FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE = 0x1;
4536        private static final int FLAG_HINT_HIDE_ICON = 1 << 1;
4537        private static final int FLAG_HINT_SHOW_BACKGROUND_ONLY = 1 << 2;
4538        private static final int FLAG_START_SCROLL_BOTTOM = 1 << 3;
4539        private static final int FLAG_HINT_AVOID_BACKGROUND_CLIPPING = 1 << 4;
4540
4541        // Default value for flags integer
4542        private static final int DEFAULT_FLAGS = FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE;
4543
4544        private static final int DEFAULT_CONTENT_ICON_GRAVITY = Gravity.END;
4545        private static final int DEFAULT_GRAVITY = Gravity.BOTTOM;
4546
4547        private ArrayList<Action> mActions = new ArrayList<Action>();
4548        private int mFlags = DEFAULT_FLAGS;
4549        private PendingIntent mDisplayIntent;
4550        private ArrayList<Notification> mPages = new ArrayList<Notification>();
4551        private Bitmap mBackground;
4552        private int mContentIcon;
4553        private int mContentIconGravity = DEFAULT_CONTENT_ICON_GRAVITY;
4554        private int mContentActionIndex = UNSET_ACTION_INDEX;
4555        private int mCustomSizePreset = SIZE_DEFAULT;
4556        private int mCustomContentHeight;
4557        private int mGravity = DEFAULT_GRAVITY;
4558        private int mHintScreenTimeout;
4559
4560        /**
4561         * Create a {@link android.app.Notification.WearableExtender} with default
4562         * options.
4563         */
4564        public WearableExtender() {
4565        }
4566
4567        public WearableExtender(Notification notif) {
4568            Bundle wearableBundle = notif.extras.getBundle(EXTRA_WEARABLE_EXTENSIONS);
4569            if (wearableBundle != null) {
4570                List<Action> actions = wearableBundle.getParcelableArrayList(KEY_ACTIONS);
4571                if (actions != null) {
4572                    mActions.addAll(actions);
4573                }
4574
4575                mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS);
4576                mDisplayIntent = wearableBundle.getParcelable(KEY_DISPLAY_INTENT);
4577
4578                Notification[] pages = getNotificationArrayFromBundle(
4579                        wearableBundle, KEY_PAGES);
4580                if (pages != null) {
4581                    Collections.addAll(mPages, pages);
4582                }
4583
4584                mBackground = wearableBundle.getParcelable(KEY_BACKGROUND);
4585                mContentIcon = wearableBundle.getInt(KEY_CONTENT_ICON);
4586                mContentIconGravity = wearableBundle.getInt(KEY_CONTENT_ICON_GRAVITY,
4587                        DEFAULT_CONTENT_ICON_GRAVITY);
4588                mContentActionIndex = wearableBundle.getInt(KEY_CONTENT_ACTION_INDEX,
4589                        UNSET_ACTION_INDEX);
4590                mCustomSizePreset = wearableBundle.getInt(KEY_CUSTOM_SIZE_PRESET,
4591                        SIZE_DEFAULT);
4592                mCustomContentHeight = wearableBundle.getInt(KEY_CUSTOM_CONTENT_HEIGHT);
4593                mGravity = wearableBundle.getInt(KEY_GRAVITY, DEFAULT_GRAVITY);
4594                mHintScreenTimeout = wearableBundle.getInt(KEY_HINT_SCREEN_TIMEOUT);
4595            }
4596        }
4597
4598        /**
4599         * Apply wearable extensions to a notification that is being built. This is typically
4600         * called by the {@link android.app.Notification.Builder#extend} method of
4601         * {@link android.app.Notification.Builder}.
4602         */
4603        @Override
4604        public Notification.Builder extend(Notification.Builder builder) {
4605            Bundle wearableBundle = new Bundle();
4606
4607            if (!mActions.isEmpty()) {
4608                wearableBundle.putParcelableArrayList(KEY_ACTIONS, mActions);
4609            }
4610            if (mFlags != DEFAULT_FLAGS) {
4611                wearableBundle.putInt(KEY_FLAGS, mFlags);
4612            }
4613            if (mDisplayIntent != null) {
4614                wearableBundle.putParcelable(KEY_DISPLAY_INTENT, mDisplayIntent);
4615            }
4616            if (!mPages.isEmpty()) {
4617                wearableBundle.putParcelableArray(KEY_PAGES, mPages.toArray(
4618                        new Notification[mPages.size()]));
4619            }
4620            if (mBackground != null) {
4621                wearableBundle.putParcelable(KEY_BACKGROUND, mBackground);
4622            }
4623            if (mContentIcon != 0) {
4624                wearableBundle.putInt(KEY_CONTENT_ICON, mContentIcon);
4625            }
4626            if (mContentIconGravity != DEFAULT_CONTENT_ICON_GRAVITY) {
4627                wearableBundle.putInt(KEY_CONTENT_ICON_GRAVITY, mContentIconGravity);
4628            }
4629            if (mContentActionIndex != UNSET_ACTION_INDEX) {
4630                wearableBundle.putInt(KEY_CONTENT_ACTION_INDEX,
4631                        mContentActionIndex);
4632            }
4633            if (mCustomSizePreset != SIZE_DEFAULT) {
4634                wearableBundle.putInt(KEY_CUSTOM_SIZE_PRESET, mCustomSizePreset);
4635            }
4636            if (mCustomContentHeight != 0) {
4637                wearableBundle.putInt(KEY_CUSTOM_CONTENT_HEIGHT, mCustomContentHeight);
4638            }
4639            if (mGravity != DEFAULT_GRAVITY) {
4640                wearableBundle.putInt(KEY_GRAVITY, mGravity);
4641            }
4642            if (mHintScreenTimeout != 0) {
4643                wearableBundle.putInt(KEY_HINT_SCREEN_TIMEOUT, mHintScreenTimeout);
4644            }
4645
4646            builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle);
4647            return builder;
4648        }
4649
4650        @Override
4651        public WearableExtender clone() {
4652            WearableExtender that = new WearableExtender();
4653            that.mActions = new ArrayList<Action>(this.mActions);
4654            that.mFlags = this.mFlags;
4655            that.mDisplayIntent = this.mDisplayIntent;
4656            that.mPages = new ArrayList<Notification>(this.mPages);
4657            that.mBackground = this.mBackground;
4658            that.mContentIcon = this.mContentIcon;
4659            that.mContentIconGravity = this.mContentIconGravity;
4660            that.mContentActionIndex = this.mContentActionIndex;
4661            that.mCustomSizePreset = this.mCustomSizePreset;
4662            that.mCustomContentHeight = this.mCustomContentHeight;
4663            that.mGravity = this.mGravity;
4664            that.mHintScreenTimeout = this.mHintScreenTimeout;
4665            return that;
4666        }
4667
4668        /**
4669         * Add a wearable action to this notification.
4670         *
4671         * <p>When wearable actions are added using this method, the set of actions that
4672         * show on a wearable device splits from devices that only show actions added
4673         * using {@link android.app.Notification.Builder#addAction}. This allows for customization
4674         * of which actions display on different devices.
4675         *
4676         * @param action the action to add to this notification
4677         * @return this object for method chaining
4678         * @see android.app.Notification.Action
4679         */
4680        public WearableExtender addAction(Action action) {
4681            mActions.add(action);
4682            return this;
4683        }
4684
4685        /**
4686         * Adds wearable actions to this notification.
4687         *
4688         * <p>When wearable actions are added using this method, the set of actions that
4689         * show on a wearable device splits from devices that only show actions added
4690         * using {@link android.app.Notification.Builder#addAction}. This allows for customization
4691         * of which actions display on different devices.
4692         *
4693         * @param actions the actions to add to this notification
4694         * @return this object for method chaining
4695         * @see android.app.Notification.Action
4696         */
4697        public WearableExtender addActions(List<Action> actions) {
4698            mActions.addAll(actions);
4699            return this;
4700        }
4701
4702        /**
4703         * Clear all wearable actions present on this builder.
4704         * @return this object for method chaining.
4705         * @see #addAction
4706         */
4707        public WearableExtender clearActions() {
4708            mActions.clear();
4709            return this;
4710        }
4711
4712        /**
4713         * Get the wearable actions present on this notification.
4714         */
4715        public List<Action> getActions() {
4716            return mActions;
4717        }
4718
4719        /**
4720         * Set an intent to launch inside of an activity view when displaying
4721         * this notification. The {@link PendingIntent} provided should be for an activity.
4722         *
4723         * <pre class="prettyprint">
4724         * Intent displayIntent = new Intent(context, MyDisplayActivity.class);
4725         * PendingIntent displayPendingIntent = PendingIntent.getActivity(context,
4726         *         0, displayIntent, PendingIntent.FLAG_UPDATE_CURRENT);
4727         * Notification notif = new Notification.Builder(context)
4728         *         .extend(new Notification.WearableExtender()
4729         *                 .setDisplayIntent(displayPendingIntent)
4730         *                 .setCustomSizePreset(Notification.WearableExtender.SIZE_MEDIUM))
4731         *         .build();</pre>
4732         *
4733         * <p>The activity to launch needs to allow embedding, must be exported, and
4734         * should have an empty task affinity. It is also recommended to use the device
4735         * default light theme.
4736         *
4737         * <p>Example AndroidManifest.xml entry:
4738         * <pre class="prettyprint">
4739         * &lt;activity android:name=&quot;com.example.MyDisplayActivity&quot;
4740         *     android:exported=&quot;true&quot;
4741         *     android:allowEmbedded=&quot;true&quot;
4742         *     android:taskAffinity=&quot;&quot;
4743         *     android:theme=&quot;@android:style/Theme.DeviceDefault.Light&quot; /&gt;</pre>
4744         *
4745         * @param intent the {@link PendingIntent} for an activity
4746         * @return this object for method chaining
4747         * @see android.app.Notification.WearableExtender#getDisplayIntent
4748         */
4749        public WearableExtender setDisplayIntent(PendingIntent intent) {
4750            mDisplayIntent = intent;
4751            return this;
4752        }
4753
4754        /**
4755         * Get the intent to launch inside of an activity view when displaying this
4756         * notification. This {@code PendingIntent} should be for an activity.
4757         */
4758        public PendingIntent getDisplayIntent() {
4759            return mDisplayIntent;
4760        }
4761
4762        /**
4763         * Add an additional page of content to display with this notification. The current
4764         * notification forms the first page, and pages added using this function form
4765         * subsequent pages. This field can be used to separate a notification into multiple
4766         * sections.
4767         *
4768         * @param page the notification to add as another page
4769         * @return this object for method chaining
4770         * @see android.app.Notification.WearableExtender#getPages
4771         */
4772        public WearableExtender addPage(Notification page) {
4773            mPages.add(page);
4774            return this;
4775        }
4776
4777        /**
4778         * Add additional pages of content to display with this notification. The current
4779         * notification forms the first page, and pages added using this function form
4780         * subsequent pages. This field can be used to separate a notification into multiple
4781         * sections.
4782         *
4783         * @param pages a list of notifications
4784         * @return this object for method chaining
4785         * @see android.app.Notification.WearableExtender#getPages
4786         */
4787        public WearableExtender addPages(List<Notification> pages) {
4788            mPages.addAll(pages);
4789            return this;
4790        }
4791
4792        /**
4793         * Clear all additional pages present on this builder.
4794         * @return this object for method chaining.
4795         * @see #addPage
4796         */
4797        public WearableExtender clearPages() {
4798            mPages.clear();
4799            return this;
4800        }
4801
4802        /**
4803         * Get the array of additional pages of content for displaying this notification. The
4804         * current notification forms the first page, and elements within this array form
4805         * subsequent pages. This field can be used to separate a notification into multiple
4806         * sections.
4807         * @return the pages for this notification
4808         */
4809        public List<Notification> getPages() {
4810            return mPages;
4811        }
4812
4813        /**
4814         * Set a background image to be displayed behind the notification content.
4815         * Contrary to the {@link android.app.Notification.BigPictureStyle}, this background
4816         * will work with any notification style.
4817         *
4818         * @param background the background bitmap
4819         * @return this object for method chaining
4820         * @see android.app.Notification.WearableExtender#getBackground
4821         */
4822        public WearableExtender setBackground(Bitmap background) {
4823            mBackground = background;
4824            return this;
4825        }
4826
4827        /**
4828         * Get a background image to be displayed behind the notification content.
4829         * Contrary to the {@link android.app.Notification.BigPictureStyle}, this background
4830         * will work with any notification style.
4831         *
4832         * @return the background image
4833         * @see android.app.Notification.WearableExtender#setBackground
4834         */
4835        public Bitmap getBackground() {
4836            return mBackground;
4837        }
4838
4839        /**
4840         * Set an icon that goes with the content of this notification.
4841         */
4842        public WearableExtender setContentIcon(int icon) {
4843            mContentIcon = icon;
4844            return this;
4845        }
4846
4847        /**
4848         * Get an icon that goes with the content of this notification.
4849         */
4850        public int getContentIcon() {
4851            return mContentIcon;
4852        }
4853
4854        /**
4855         * Set the gravity that the content icon should have within the notification display.
4856         * Supported values include {@link android.view.Gravity#START} and
4857         * {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}.
4858         * @see #setContentIcon
4859         */
4860        public WearableExtender setContentIconGravity(int contentIconGravity) {
4861            mContentIconGravity = contentIconGravity;
4862            return this;
4863        }
4864
4865        /**
4866         * Get the gravity that the content icon should have within the notification display.
4867         * Supported values include {@link android.view.Gravity#START} and
4868         * {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}.
4869         * @see #getContentIcon
4870         */
4871        public int getContentIconGravity() {
4872            return mContentIconGravity;
4873        }
4874
4875        /**
4876         * Set an action from this notification's actions to be clickable with the content of
4877         * this notification. This action will no longer display separately from the
4878         * notification's content.
4879         *
4880         * <p>For notifications with multiple pages, child pages can also have content actions
4881         * set, although the list of available actions comes from the main notification and not
4882         * from the child page's notification.
4883         *
4884         * @param actionIndex The index of the action to hoist onto the current notification page.
4885         *                    If wearable actions were added to the main notification, this index
4886         *                    will apply to that list, otherwise it will apply to the regular
4887         *                    actions list.
4888         */
4889        public WearableExtender setContentAction(int actionIndex) {
4890            mContentActionIndex = actionIndex;
4891            return this;
4892        }
4893
4894        /**
4895         * Get the index of the notification action, if any, that was specified as being clickable
4896         * with the content of this notification. This action will no longer display separately
4897         * from the notification's content.
4898         *
4899         * <p>For notifications with multiple pages, child pages can also have content actions
4900         * set, although the list of available actions comes from the main notification and not
4901         * from the child page's notification.
4902         *
4903         * <p>If wearable specific actions were added to the main notification, this index will
4904         * apply to that list, otherwise it will apply to the regular actions list.
4905         *
4906         * @return the action index or {@link #UNSET_ACTION_INDEX} if no action was selected.
4907         */
4908        public int getContentAction() {
4909            return mContentActionIndex;
4910        }
4911
4912        /**
4913         * Set the gravity that this notification should have within the available viewport space.
4914         * Supported values include {@link android.view.Gravity#TOP},
4915         * {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}.
4916         * The default value is {@link android.view.Gravity#BOTTOM}.
4917         */
4918        public WearableExtender setGravity(int gravity) {
4919            mGravity = gravity;
4920            return this;
4921        }
4922
4923        /**
4924         * Get the gravity that this notification should have within the available viewport space.
4925         * Supported values include {@link android.view.Gravity#TOP},
4926         * {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}.
4927         * The default value is {@link android.view.Gravity#BOTTOM}.
4928         */
4929        public int getGravity() {
4930            return mGravity;
4931        }
4932
4933        /**
4934         * Set the custom size preset for the display of this notification out of the available
4935         * presets found in {@link android.app.Notification.WearableExtender}, e.g.
4936         * {@link #SIZE_LARGE}.
4937         * <p>Some custom size presets are only applicable for custom display notifications created
4938         * using {@link android.app.Notification.WearableExtender#setDisplayIntent}. Check the
4939         * documentation for the preset in question. See also
4940         * {@link #setCustomContentHeight} and {@link #getCustomSizePreset}.
4941         */
4942        public WearableExtender setCustomSizePreset(int sizePreset) {
4943            mCustomSizePreset = sizePreset;
4944            return this;
4945        }
4946
4947        /**
4948         * Get the custom size preset for the display of this notification out of the available
4949         * presets found in {@link android.app.Notification.WearableExtender}, e.g.
4950         * {@link #SIZE_LARGE}.
4951         * <p>Some custom size presets are only applicable for custom display notifications created
4952         * using {@link #setDisplayIntent}. Check the documentation for the preset in question.
4953         * See also {@link #setCustomContentHeight} and {@link #setCustomSizePreset}.
4954         */
4955        public int getCustomSizePreset() {
4956            return mCustomSizePreset;
4957        }
4958
4959        /**
4960         * Set the custom height in pixels for the display of this notification's content.
4961         * <p>This option is only available for custom display notifications created
4962         * using {@link android.app.Notification.WearableExtender#setDisplayIntent}. See also
4963         * {@link android.app.Notification.WearableExtender#setCustomSizePreset} and
4964         * {@link #getCustomContentHeight}.
4965         */
4966        public WearableExtender setCustomContentHeight(int height) {
4967            mCustomContentHeight = height;
4968            return this;
4969        }
4970
4971        /**
4972         * Get the custom height in pixels for the display of this notification's content.
4973         * <p>This option is only available for custom display notifications created
4974         * using {@link #setDisplayIntent}. See also {@link #setCustomSizePreset} and
4975         * {@link #setCustomContentHeight}.
4976         */
4977        public int getCustomContentHeight() {
4978            return mCustomContentHeight;
4979        }
4980
4981        /**
4982         * Set whether the scrolling position for the contents of this notification should start
4983         * at the bottom of the contents instead of the top when the contents are too long to
4984         * display within the screen.  Default is false (start scroll at the top).
4985         */
4986        public WearableExtender setStartScrollBottom(boolean startScrollBottom) {
4987            setFlag(FLAG_START_SCROLL_BOTTOM, startScrollBottom);
4988            return this;
4989        }
4990
4991        /**
4992         * Get whether the scrolling position for the contents of this notification should start
4993         * at the bottom of the contents instead of the top when the contents are too long to
4994         * display within the screen. Default is false (start scroll at the top).
4995         */
4996        public boolean getStartScrollBottom() {
4997            return (mFlags & FLAG_START_SCROLL_BOTTOM) != 0;
4998        }
4999
5000        /**
5001         * Set whether the content intent is available when the wearable device is not connected
5002         * to a companion device.  The user can still trigger this intent when the wearable device
5003         * is offline, but a visual hint will indicate that the content intent may not be available.
5004         * Defaults to true.
5005         */
5006        public WearableExtender setContentIntentAvailableOffline(
5007                boolean contentIntentAvailableOffline) {
5008            setFlag(FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE, contentIntentAvailableOffline);
5009            return this;
5010        }
5011
5012        /**
5013         * Get whether the content intent is available when the wearable device is not connected
5014         * to a companion device.  The user can still trigger this intent when the wearable device
5015         * is offline, but a visual hint will indicate that the content intent may not be available.
5016         * Defaults to true.
5017         */
5018        public boolean getContentIntentAvailableOffline() {
5019            return (mFlags & FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE) != 0;
5020        }
5021
5022        /**
5023         * Set a hint that this notification's icon should not be displayed.
5024         * @param hintHideIcon {@code true} to hide the icon, {@code false} otherwise.
5025         * @return this object for method chaining
5026         */
5027        public WearableExtender setHintHideIcon(boolean hintHideIcon) {
5028            setFlag(FLAG_HINT_HIDE_ICON, hintHideIcon);
5029            return this;
5030        }
5031
5032        /**
5033         * Get a hint that this notification's icon should not be displayed.
5034         * @return {@code true} if this icon should not be displayed, false otherwise.
5035         * The default value is {@code false} if this was never set.
5036         */
5037        public boolean getHintHideIcon() {
5038            return (mFlags & FLAG_HINT_HIDE_ICON) != 0;
5039        }
5040
5041        /**
5042         * Set a visual hint that only the background image of this notification should be
5043         * displayed, and other semantic content should be hidden. This hint is only applicable
5044         * to sub-pages added using {@link #addPage}.
5045         */
5046        public WearableExtender setHintShowBackgroundOnly(boolean hintShowBackgroundOnly) {
5047            setFlag(FLAG_HINT_SHOW_BACKGROUND_ONLY, hintShowBackgroundOnly);
5048            return this;
5049        }
5050
5051        /**
5052         * Get a visual hint that only the background image of this notification should be
5053         * displayed, and other semantic content should be hidden. This hint is only applicable
5054         * to sub-pages added using {@link android.app.Notification.WearableExtender#addPage}.
5055         */
5056        public boolean getHintShowBackgroundOnly() {
5057            return (mFlags & FLAG_HINT_SHOW_BACKGROUND_ONLY) != 0;
5058        }
5059
5060        /**
5061         * Set a hint that this notification's background should not be clipped if possible,
5062         * and should instead be resized to fully display on the screen, retaining the aspect
5063         * ratio of the image. This can be useful for images like barcodes or qr codes.
5064         * @param hintAvoidBackgroundClipping {@code true} to avoid clipping if possible.
5065         * @return this object for method chaining
5066         */
5067        public WearableExtender setHintAvoidBackgroundClipping(
5068                boolean hintAvoidBackgroundClipping) {
5069            setFlag(FLAG_HINT_AVOID_BACKGROUND_CLIPPING, hintAvoidBackgroundClipping);
5070            return this;
5071        }
5072
5073        /**
5074         * Get a hint that this notification's background should not be clipped if possible,
5075         * and should instead be resized to fully display on the screen, retaining the aspect
5076         * ratio of the image. This can be useful for images like barcodes or qr codes.
5077         * @return {@code true} if it's ok if the background is clipped on the screen, false
5078         * otherwise. The default value is {@code false} if this was never set.
5079         */
5080        public boolean getHintAvoidBackgroundClipping() {
5081            return (mFlags & FLAG_HINT_AVOID_BACKGROUND_CLIPPING) != 0;
5082        }
5083
5084        /**
5085         * Set a hint that the screen should remain on for at least this duration when
5086         * this notification is displayed on the screen.
5087         * @param timeout The requested screen timeout in milliseconds. Can also be either
5088         *     {@link #SCREEN_TIMEOUT_SHORT} or {@link #SCREEN_TIMEOUT_LONG}.
5089         * @return this object for method chaining
5090         */
5091        public WearableExtender setHintScreenTimeout(int timeout) {
5092            mHintScreenTimeout = timeout;
5093            return this;
5094        }
5095
5096        /**
5097         * Get the duration, in milliseconds, that the screen should remain on for
5098         * when this notification is displayed.
5099         * @return the duration in milliseconds if > 0, or either one of the sentinel values
5100         *     {@link #SCREEN_TIMEOUT_SHORT} or {@link #SCREEN_TIMEOUT_LONG}.
5101         */
5102        public int getHintScreenTimeout() {
5103            return mHintScreenTimeout;
5104        }
5105
5106        private void setFlag(int mask, boolean value) {
5107            if (value) {
5108                mFlags |= mask;
5109            } else {
5110                mFlags &= ~mask;
5111            }
5112        }
5113    }
5114
5115    /**
5116     * <p>Helper class to add Android Auto extensions to notifications. To create a notification
5117     * with car extensions:
5118     *
5119     * <ol>
5120     *  <li>Create an {@link Notification.Builder}, setting any desired
5121     *  properties.
5122     *  <li>Create a {@link CarExtender}.
5123     *  <li>Set car-specific properties using the {@code add} and {@code set} methods of
5124     *  {@link CarExtender}.
5125     *  <li>Call {@link Notification.Builder#extend(Notification.Extender)}
5126     *  to apply the extensions to a notification.
5127     * </ol>
5128     *
5129     * <pre class="prettyprint">
5130     * Notification notification = new Notification.Builder(context)
5131     *         ...
5132     *         .extend(new CarExtender()
5133     *                 .set*(...))
5134     *         .build();
5135     * </pre>
5136     *
5137     * <p>Car extensions can be accessed on an existing notification by using the
5138     * {@code CarExtender(Notification)} constructor, and then using the {@code get} methods
5139     * to access values.
5140     */
5141    public static final class CarExtender implements Extender {
5142        private static final String TAG = "CarExtender";
5143
5144        private static final String EXTRA_CAR_EXTENDER = "android.car.EXTENSIONS";
5145        private static final String EXTRA_LARGE_ICON = "large_icon";
5146        private static final String EXTRA_CONVERSATION = "car_conversation";
5147        private static final String EXTRA_COLOR = "app_color";
5148
5149        private Bitmap mLargeIcon;
5150        private UnreadConversation mUnreadConversation;
5151        private int mColor = Notification.COLOR_DEFAULT;
5152
5153        /**
5154         * Create a {@link CarExtender} with default options.
5155         */
5156        public CarExtender() {
5157        }
5158
5159        /**
5160         * Create a {@link CarExtender} from the CarExtender options of an existing Notification.
5161         *
5162         * @param notif The notification from which to copy options.
5163         */
5164        public CarExtender(Notification notif) {
5165            Bundle carBundle = notif.extras == null ?
5166                    null : notif.extras.getBundle(EXTRA_CAR_EXTENDER);
5167            if (carBundle != null) {
5168                mLargeIcon = carBundle.getParcelable(EXTRA_LARGE_ICON);
5169                mColor = carBundle.getInt(EXTRA_COLOR, Notification.COLOR_DEFAULT);
5170
5171                Bundle b = carBundle.getBundle(EXTRA_CONVERSATION);
5172                mUnreadConversation = UnreadConversation.getUnreadConversationFromBundle(b);
5173            }
5174        }
5175
5176        /**
5177         * Apply car extensions to a notification that is being built. This is typically called by
5178         * the {@link Notification.Builder#extend(Notification.Extender)}
5179         * method of {@link Notification.Builder}.
5180         */
5181        @Override
5182        public Notification.Builder extend(Notification.Builder builder) {
5183            Bundle carExtensions = new Bundle();
5184
5185            if (mLargeIcon != null) {
5186                carExtensions.putParcelable(EXTRA_LARGE_ICON, mLargeIcon);
5187            }
5188            if (mColor != Notification.COLOR_DEFAULT) {
5189                carExtensions.putInt(EXTRA_COLOR, mColor);
5190            }
5191
5192            if (mUnreadConversation != null) {
5193                Bundle b = mUnreadConversation.getBundleForUnreadConversation();
5194                carExtensions.putBundle(EXTRA_CONVERSATION, b);
5195            }
5196
5197            builder.getExtras().putBundle(EXTRA_CAR_EXTENDER, carExtensions);
5198            return builder;
5199        }
5200
5201        /**
5202         * Sets the accent color to use when Android Auto presents the notification.
5203         *
5204         * Android Auto uses the color set with {@link Notification.Builder#setColor(int)}
5205         * to accent the displayed notification. However, not all colors are acceptable in an
5206         * automotive setting. This method can be used to override the color provided in the
5207         * notification in such a situation.
5208         */
5209        public CarExtender setColor(@ColorInt int color) {
5210            mColor = color;
5211            return this;
5212        }
5213
5214        /**
5215         * Gets the accent color.
5216         *
5217         * @see #setColor
5218         */
5219        @ColorInt
5220        public int getColor() {
5221            return mColor;
5222        }
5223
5224        /**
5225         * Sets the large icon of the car notification.
5226         *
5227         * If no large icon is set in the extender, Android Auto will display the icon
5228         * specified by {@link Notification.Builder#setLargeIcon(android.graphics.Bitmap)}
5229         *
5230         * @param largeIcon The large icon to use in the car notification.
5231         * @return This object for method chaining.
5232         */
5233        public CarExtender setLargeIcon(Bitmap largeIcon) {
5234            mLargeIcon = largeIcon;
5235            return this;
5236        }
5237
5238        /**
5239         * Gets the large icon used in this car notification, or null if no icon has been set.
5240         *
5241         * @return The large icon for the car notification.
5242         * @see CarExtender#setLargeIcon
5243         */
5244        public Bitmap getLargeIcon() {
5245            return mLargeIcon;
5246        }
5247
5248        /**
5249         * Sets the unread conversation in a message notification.
5250         *
5251         * @param unreadConversation The unread part of the conversation this notification conveys.
5252         * @return This object for method chaining.
5253         */
5254        public CarExtender setUnreadConversation(UnreadConversation unreadConversation) {
5255            mUnreadConversation = unreadConversation;
5256            return this;
5257        }
5258
5259        /**
5260         * Returns the unread conversation conveyed by this notification.
5261         * @see #setUnreadConversation(UnreadConversation)
5262         */
5263        public UnreadConversation getUnreadConversation() {
5264            return mUnreadConversation;
5265        }
5266
5267        /**
5268         * A class which holds the unread messages from a conversation.
5269         */
5270        public static class UnreadConversation {
5271            private static final String KEY_AUTHOR = "author";
5272            private static final String KEY_TEXT = "text";
5273            private static final String KEY_MESSAGES = "messages";
5274            private static final String KEY_REMOTE_INPUT = "remote_input";
5275            private static final String KEY_ON_REPLY = "on_reply";
5276            private static final String KEY_ON_READ = "on_read";
5277            private static final String KEY_PARTICIPANTS = "participants";
5278            private static final String KEY_TIMESTAMP = "timestamp";
5279
5280            private final String[] mMessages;
5281            private final RemoteInput mRemoteInput;
5282            private final PendingIntent mReplyPendingIntent;
5283            private final PendingIntent mReadPendingIntent;
5284            private final String[] mParticipants;
5285            private final long mLatestTimestamp;
5286
5287            UnreadConversation(String[] messages, RemoteInput remoteInput,
5288                    PendingIntent replyPendingIntent, PendingIntent readPendingIntent,
5289                    String[] participants, long latestTimestamp) {
5290                mMessages = messages;
5291                mRemoteInput = remoteInput;
5292                mReadPendingIntent = readPendingIntent;
5293                mReplyPendingIntent = replyPendingIntent;
5294                mParticipants = participants;
5295                mLatestTimestamp = latestTimestamp;
5296            }
5297
5298            /**
5299             * Gets the list of messages conveyed by this notification.
5300             */
5301            public String[] getMessages() {
5302                return mMessages;
5303            }
5304
5305            /**
5306             * Gets the remote input that will be used to convey the response to a message list, or
5307             * null if no such remote input exists.
5308             */
5309            public RemoteInput getRemoteInput() {
5310                return mRemoteInput;
5311            }
5312
5313            /**
5314             * Gets the pending intent that will be triggered when the user replies to this
5315             * notification.
5316             */
5317            public PendingIntent getReplyPendingIntent() {
5318                return mReplyPendingIntent;
5319            }
5320
5321            /**
5322             * Gets the pending intent that Android Auto will send after it reads aloud all messages
5323             * in this object's message list.
5324             */
5325            public PendingIntent getReadPendingIntent() {
5326                return mReadPendingIntent;
5327            }
5328
5329            /**
5330             * Gets the participants in the conversation.
5331             */
5332            public String[] getParticipants() {
5333                return mParticipants;
5334            }
5335
5336            /**
5337             * Gets the firs participant in the conversation.
5338             */
5339            public String getParticipant() {
5340                return mParticipants.length > 0 ? mParticipants[0] : null;
5341            }
5342
5343            /**
5344             * Gets the timestamp of the conversation.
5345             */
5346            public long getLatestTimestamp() {
5347                return mLatestTimestamp;
5348            }
5349
5350            Bundle getBundleForUnreadConversation() {
5351                Bundle b = new Bundle();
5352                String author = null;
5353                if (mParticipants != null && mParticipants.length > 1) {
5354                    author = mParticipants[0];
5355                }
5356                Parcelable[] messages = new Parcelable[mMessages.length];
5357                for (int i = 0; i < messages.length; i++) {
5358                    Bundle m = new Bundle();
5359                    m.putString(KEY_TEXT, mMessages[i]);
5360                    m.putString(KEY_AUTHOR, author);
5361                    messages[i] = m;
5362                }
5363                b.putParcelableArray(KEY_MESSAGES, messages);
5364                if (mRemoteInput != null) {
5365                    b.putParcelable(KEY_REMOTE_INPUT, mRemoteInput);
5366                }
5367                b.putParcelable(KEY_ON_REPLY, mReplyPendingIntent);
5368                b.putParcelable(KEY_ON_READ, mReadPendingIntent);
5369                b.putStringArray(KEY_PARTICIPANTS, mParticipants);
5370                b.putLong(KEY_TIMESTAMP, mLatestTimestamp);
5371                return b;
5372            }
5373
5374            static UnreadConversation getUnreadConversationFromBundle(Bundle b) {
5375                if (b == null) {
5376                    return null;
5377                }
5378                Parcelable[] parcelableMessages = b.getParcelableArray(KEY_MESSAGES);
5379                String[] messages = null;
5380                if (parcelableMessages != null) {
5381                    String[] tmp = new String[parcelableMessages.length];
5382                    boolean success = true;
5383                    for (int i = 0; i < tmp.length; i++) {
5384                        if (!(parcelableMessages[i] instanceof Bundle)) {
5385                            success = false;
5386                            break;
5387                        }
5388                        tmp[i] = ((Bundle) parcelableMessages[i]).getString(KEY_TEXT);
5389                        if (tmp[i] == null) {
5390                            success = false;
5391                            break;
5392                        }
5393                    }
5394                    if (success) {
5395                        messages = tmp;
5396                    } else {
5397                        return null;
5398                    }
5399                }
5400
5401                PendingIntent onRead = b.getParcelable(KEY_ON_READ);
5402                PendingIntent onReply = b.getParcelable(KEY_ON_REPLY);
5403
5404                RemoteInput remoteInput = b.getParcelable(KEY_REMOTE_INPUT);
5405
5406                String[] participants = b.getStringArray(KEY_PARTICIPANTS);
5407                if (participants == null || participants.length != 1) {
5408                    return null;
5409                }
5410
5411                return new UnreadConversation(messages,
5412                        remoteInput,
5413                        onReply,
5414                        onRead,
5415                        participants, b.getLong(KEY_TIMESTAMP));
5416            }
5417        };
5418
5419        /**
5420         * Builder class for {@link CarExtender.UnreadConversation} objects.
5421         */
5422        public static class Builder {
5423            private final List<String> mMessages = new ArrayList<String>();
5424            private final String mParticipant;
5425            private RemoteInput mRemoteInput;
5426            private PendingIntent mReadPendingIntent;
5427            private PendingIntent mReplyPendingIntent;
5428            private long mLatestTimestamp;
5429
5430            /**
5431             * Constructs a new builder for {@link CarExtender.UnreadConversation}.
5432             *
5433             * @param name The name of the other participant in the conversation.
5434             */
5435            public Builder(String name) {
5436                mParticipant = name;
5437            }
5438
5439            /**
5440             * Appends a new unread message to the list of messages for this conversation.
5441             *
5442             * The messages should be added from oldest to newest.
5443             *
5444             * @param message The text of the new unread message.
5445             * @return This object for method chaining.
5446             */
5447            public Builder addMessage(String message) {
5448                mMessages.add(message);
5449                return this;
5450            }
5451
5452            /**
5453             * Sets the pending intent and remote input which will convey the reply to this
5454             * notification.
5455             *
5456             * @param pendingIntent The pending intent which will be triggered on a reply.
5457             * @param remoteInput The remote input parcelable which will carry the reply.
5458             * @return This object for method chaining.
5459             *
5460             * @see CarExtender.UnreadConversation#getRemoteInput
5461             * @see CarExtender.UnreadConversation#getReplyPendingIntent
5462             */
5463            public Builder setReplyAction(
5464                    PendingIntent pendingIntent, RemoteInput remoteInput) {
5465                mRemoteInput = remoteInput;
5466                mReplyPendingIntent = pendingIntent;
5467
5468                return this;
5469            }
5470
5471            /**
5472             * Sets the pending intent that will be sent once the messages in this notification
5473             * are read.
5474             *
5475             * @param pendingIntent The pending intent to use.
5476             * @return This object for method chaining.
5477             */
5478            public Builder setReadPendingIntent(PendingIntent pendingIntent) {
5479                mReadPendingIntent = pendingIntent;
5480                return this;
5481            }
5482
5483            /**
5484             * Sets the timestamp of the most recent message in an unread conversation.
5485             *
5486             * If a messaging notification has been posted by your application and has not
5487             * yet been cancelled, posting a later notification with the same id and tag
5488             * but without a newer timestamp may result in Android Auto not displaying a
5489             * heads up notification for the later notification.
5490             *
5491             * @param timestamp The timestamp of the most recent message in the conversation.
5492             * @return This object for method chaining.
5493             */
5494            public Builder setLatestTimestamp(long timestamp) {
5495                mLatestTimestamp = timestamp;
5496                return this;
5497            }
5498
5499            /**
5500             * Builds a new unread conversation object.
5501             *
5502             * @return The new unread conversation object.
5503             */
5504            public UnreadConversation build() {
5505                String[] messages = mMessages.toArray(new String[mMessages.size()]);
5506                String[] participants = { mParticipant };
5507                return new UnreadConversation(messages, mRemoteInput, mReplyPendingIntent,
5508                        mReadPendingIntent, participants, mLatestTimestamp);
5509            }
5510        }
5511    }
5512
5513    /**
5514     * Get an array of Notification objects from a parcelable array bundle field.
5515     * Update the bundle to have a typed array so fetches in the future don't need
5516     * to do an array copy.
5517     */
5518    private static Notification[] getNotificationArrayFromBundle(Bundle bundle, String key) {
5519        Parcelable[] array = bundle.getParcelableArray(key);
5520        if (array instanceof Notification[] || array == null) {
5521            return (Notification[]) array;
5522        }
5523        Notification[] typedArray = Arrays.copyOf(array, array.length,
5524                Notification[].class);
5525        bundle.putParcelableArray(key, typedArray);
5526        return typedArray;
5527    }
5528
5529    private static class BuilderRemoteViews extends RemoteViews {
5530        public BuilderRemoteViews(Parcel parcel) {
5531            super(parcel);
5532        }
5533
5534        public BuilderRemoteViews(ApplicationInfo appInfo, int layoutId) {
5535            super(appInfo, layoutId);
5536        }
5537
5538        @Override
5539        public BuilderRemoteViews clone() {
5540            Parcel p = Parcel.obtain();
5541            writeToParcel(p, 0);
5542            p.setDataPosition(0);
5543            BuilderRemoteViews brv = new BuilderRemoteViews(p);
5544            p.recycle();
5545            return brv;
5546        }
5547    }
5548}
5549