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