Notification.java revision 3cb07a462be293634e6a83ea6c82f3647cd17dad
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.IntDef;
20import android.content.Context;
21import android.content.Intent;
22import android.content.res.Resources;
23import android.graphics.Bitmap;
24import android.graphics.BitmapFactory;
25import android.graphics.Canvas;
26import android.graphics.PorterDuff;
27import android.graphics.drawable.Drawable;
28import android.media.AudioManager;
29import android.media.session.MediaSessionToken;
30import android.net.Uri;
31import android.os.BadParcelableException;
32import android.os.Build;
33import android.os.Bundle;
34import android.os.Parcel;
35import android.os.Parcelable;
36import android.os.SystemClock;
37import android.os.UserHandle;
38import android.os.UserManager;
39import android.text.TextUtils;
40import android.util.Log;
41import android.util.TypedValue;
42import android.view.Gravity;
43import android.view.View;
44import android.widget.ProgressBar;
45import android.widget.RemoteViews;
46
47import com.android.internal.R;
48import com.android.internal.util.NotificationColorUtil;
49
50import java.lang.annotation.Retention;
51import java.lang.annotation.RetentionPolicy;
52import java.text.NumberFormat;
53import java.util.ArrayList;
54import java.util.Arrays;
55import java.util.Collections;
56import java.util.List;
57
58/**
59 * A class that represents how a persistent notification is to be presented to
60 * the user using the {@link android.app.NotificationManager}.
61 *
62 * <p>The {@link Notification.Builder Notification.Builder} has been added to make it
63 * easier to construct Notifications.</p>
64 *
65 * <div class="special reference">
66 * <h3>Developer Guides</h3>
67 * <p>For a guide to creating notifications, read the
68 * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a>
69 * developer guide.</p>
70 * </div>
71 */
72public class Notification implements Parcelable
73{
74    private static final String TAG = "Notification";
75
76    /**
77     * Use all default values (where applicable).
78     */
79    public static final int DEFAULT_ALL = ~0;
80
81    /**
82     * Use the default notification sound. This will ignore any given
83     * {@link #sound}.
84     *
85
86     * @see #defaults
87     */
88
89    public static final int DEFAULT_SOUND = 1;
90
91    /**
92     * Use the default notification vibrate. This will ignore any given
93     * {@link #vibrate}. Using phone vibration requires the
94     * {@link android.Manifest.permission#VIBRATE VIBRATE} permission.
95     *
96     * @see #defaults
97     */
98
99    public static final int DEFAULT_VIBRATE = 2;
100
101    /**
102     * Use the default notification lights. This will ignore the
103     * {@link #FLAG_SHOW_LIGHTS} bit, and {@link #ledARGB}, {@link #ledOffMS}, or
104     * {@link #ledOnMS}.
105     *
106     * @see #defaults
107     */
108
109    public static final int DEFAULT_LIGHTS = 4;
110
111    /**
112     * A timestamp related to this notification, in milliseconds since the epoch.
113     *
114     * Default value: {@link System#currentTimeMillis() Now}.
115     *
116     * Choose a timestamp that will be most relevant to the user. For most finite events, this
117     * corresponds to the time the event happened (or will happen, in the case of events that have
118     * yet to occur but about which the user is being informed). Indefinite events should be
119     * timestamped according to when the activity began.
120     *
121     * Some examples:
122     *
123     * <ul>
124     *   <li>Notification of a new chat message should be stamped when the message was received.</li>
125     *   <li>Notification of an ongoing file download (with a progress bar, for example) should be stamped when the download started.</li>
126     *   <li>Notification of a completed file download should be stamped when the download finished.</li>
127     *   <li>Notification of an upcoming meeting should be stamped with the time the meeting will begin (that is, in the future).</li>
128     *   <li>Notification of an ongoing stopwatch (increasing timer) should be stamped with the watch's start time.
129     *   <li>Notification of an ongoing countdown timer should be stamped with the timer's end time.
130     * </ul>
131     *
132     */
133    public long when;
134
135    /**
136     * The resource id of a drawable to use as the icon in the status bar.
137     * This is required; notifications with an invalid icon resource will not be shown.
138     */
139    public int icon;
140
141    /**
142     * If the icon in the status bar is to have more than one level, you can set this.  Otherwise,
143     * leave it at its default value of 0.
144     *
145     * @see android.widget.ImageView#setImageLevel
146     * @see android.graphics.drawable.Drawable#setLevel
147     */
148    public int iconLevel;
149
150    /**
151     * The number of events that this notification represents. For example, in a new mail
152     * notification, this could be the number of unread messages.
153     *
154     * The system may or may not use this field to modify the appearance of the notification. For
155     * example, before {@link android.os.Build.VERSION_CODES#HONEYCOMB}, this number was
156     * superimposed over the icon in the status bar. Starting with
157     * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, the template used by
158     * {@link Notification.Builder} has displayed the number in the expanded notification view.
159     *
160     * If the number is 0 or negative, it is never shown.
161     */
162    public int number;
163
164    /**
165     * The intent to execute when the expanded status entry is clicked.  If
166     * this is an activity, it must include the
167     * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires
168     * that you take care of task management as described in the
169     * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back
170     * Stack</a> document.  In particular, make sure to read the notification section
171     * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html#HandlingNotifications">Handling
172     * Notifications</a> for the correct ways to launch an application from a
173     * notification.
174     */
175    public PendingIntent contentIntent;
176
177    /**
178     * The intent to execute when the notification is explicitly dismissed by the user, either with
179     * the "Clear All" button or by swiping it away individually.
180     *
181     * This probably shouldn't be launching an activity since several of those will be sent
182     * at the same time.
183     */
184    public PendingIntent deleteIntent;
185
186    /**
187     * An intent to launch instead of posting the notification to the status bar.
188     *
189     * @see Notification.Builder#setFullScreenIntent
190     */
191    public PendingIntent fullScreenIntent;
192
193    /**
194     * Text to scroll across the screen when this item is added to
195     * the status bar on large and smaller devices.
196     *
197     * @see #tickerView
198     */
199    public CharSequence tickerText;
200
201    /**
202     * The view to show as the ticker in the status bar when the notification
203     * is posted.
204     */
205    public RemoteViews tickerView;
206
207    /**
208     * The view that will represent this notification in the expanded status bar.
209     */
210    public RemoteViews contentView;
211
212    /**
213     * A large-format version of {@link #contentView}, giving the Notification an
214     * opportunity to show more detail. The system UI may choose to show this
215     * instead of the normal content view at its discretion.
216     */
217    public RemoteViews bigContentView;
218
219
220    /**
221     * @hide
222     * A medium-format version of {@link #contentView}, giving the Notification an
223     * opportunity to add action buttons to contentView. The system UI may
224     * choose to show this as a popup notification at its discretion.
225     */
226    public RemoteViews headsUpContentView;
227
228    /**
229     * The bitmap that may escape the bounds of the panel and bar.
230     */
231    public Bitmap largeIcon;
232
233    /**
234     * The sound to play.
235     *
236     * <p>
237     * To play the default notification sound, see {@link #defaults}.
238     * </p>
239     */
240    public Uri sound;
241
242    /**
243     * Use this constant as the value for audioStreamType to request that
244     * the default stream type for notifications be used.  Currently the
245     * default stream type is {@link AudioManager#STREAM_NOTIFICATION}.
246     */
247    public static final int STREAM_DEFAULT = -1;
248
249    /**
250     * The audio stream type to use when playing the sound.
251     * Should be one of the STREAM_ constants from
252     * {@link android.media.AudioManager}.
253     */
254    public int audioStreamType = STREAM_DEFAULT;
255
256    /**
257     * The pattern with which to vibrate.
258     *
259     * <p>
260     * To vibrate the default pattern, see {@link #defaults}.
261     * </p>
262     *
263     * @see android.os.Vibrator#vibrate(long[],int)
264     */
265    public long[] vibrate;
266
267    /**
268     * The color of the led.  The hardware will do its best approximation.
269     *
270     * @see #FLAG_SHOW_LIGHTS
271     * @see #flags
272     */
273    public int ledARGB;
274
275    /**
276     * The number of milliseconds for the LED to be on while it's flashing.
277     * The hardware will do its best approximation.
278     *
279     * @see #FLAG_SHOW_LIGHTS
280     * @see #flags
281     */
282    public int ledOnMS;
283
284    /**
285     * The number of milliseconds for the LED to be off while it's flashing.
286     * The hardware will do its best approximation.
287     *
288     * @see #FLAG_SHOW_LIGHTS
289     * @see #flags
290     */
291    public int ledOffMS;
292
293    /**
294     * Specifies which values should be taken from the defaults.
295     * <p>
296     * To set, OR the desired from {@link #DEFAULT_SOUND},
297     * {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}. For all default
298     * values, use {@link #DEFAULT_ALL}.
299     * </p>
300     */
301    public int defaults;
302
303    /**
304     * Bit to be bitwise-ored into the {@link #flags} field that should be
305     * set if you want the LED on for this notification.
306     * <ul>
307     * <li>To turn the LED off, pass 0 in the alpha channel for colorARGB
308     *      or 0 for both ledOnMS and ledOffMS.</li>
309     * <li>To turn the LED on, pass 1 for ledOnMS and 0 for ledOffMS.</li>
310     * <li>To flash the LED, pass the number of milliseconds that it should
311     *      be on and off to ledOnMS and ledOffMS.</li>
312     * </ul>
313     * <p>
314     * Since hardware varies, you are not guaranteed that any of the values
315     * you pass are honored exactly.  Use the system defaults (TODO) if possible
316     * because they will be set to values that work on any given hardware.
317     * <p>
318     * The alpha channel must be set for forward compatibility.
319     *
320     */
321    public static final int FLAG_SHOW_LIGHTS        = 0x00000001;
322
323    /**
324     * Bit to be bitwise-ored into the {@link #flags} field that should be
325     * set if this notification is in reference to something that is ongoing,
326     * like a phone call.  It should not be set if this notification is in
327     * reference to something that happened at a particular point in time,
328     * like a missed phone call.
329     */
330    public static final int FLAG_ONGOING_EVENT      = 0x00000002;
331
332    /**
333     * Bit to be bitwise-ored into the {@link #flags} field that if set,
334     * the audio will be repeated until the notification is
335     * cancelled or the notification window is opened.
336     */
337    public static final int FLAG_INSISTENT          = 0x00000004;
338
339    /**
340     * Bit to be bitwise-ored into the {@link #flags} field that should be
341     * set if you would only like the sound, vibrate and ticker to be played
342     * if the notification was not already showing.
343     */
344    public static final int FLAG_ONLY_ALERT_ONCE    = 0x00000008;
345
346    /**
347     * Bit to be bitwise-ored into the {@link #flags} field that should be
348     * set if the notification should be canceled when it is clicked by the
349     * user.
350
351     */
352    public static final int FLAG_AUTO_CANCEL        = 0x00000010;
353
354    /**
355     * Bit to be bitwise-ored into the {@link #flags} field that should be
356     * set if the notification should not be canceled when the user clicks
357     * the Clear all button.
358     */
359    public static final int FLAG_NO_CLEAR           = 0x00000020;
360
361    /**
362     * Bit to be bitwise-ored into the {@link #flags} field that should be
363     * set if this notification represents a currently running service.  This
364     * will normally be set for you by {@link Service#startForeground}.
365     */
366    public static final int FLAG_FOREGROUND_SERVICE = 0x00000040;
367
368    /**
369     * Obsolete flag indicating high-priority notifications; use the priority field instead.
370     *
371     * @deprecated Use {@link #priority} with a positive value.
372     */
373    public static final int FLAG_HIGH_PRIORITY      = 0x00000080;
374
375    /**
376     * Bit to be bitswise-ored into the {@link #flags} field that should be
377     * set if this notification is relevant to the current device only
378     * and it is not recommended that it bridge to other devices.
379     */
380    public static final int FLAG_LOCAL_ONLY         = 0x00000100;
381
382    /**
383     * Bit to be bitswise-ored into the {@link #flags} field that should be
384     * set if this notification is the group summary for a group of notifications.
385     * Grouped notifications may display in a cluster or stack on devices which
386     * support such rendering. Requires a group key also be set using {@link Builder#setGroup}.
387     */
388    public static final int FLAG_GROUP_SUMMARY      = 0x00000200;
389
390    public int flags;
391
392    /** @hide */
393    @IntDef({PRIORITY_DEFAULT,PRIORITY_LOW,PRIORITY_MIN,PRIORITY_HIGH,PRIORITY_MAX})
394    @Retention(RetentionPolicy.SOURCE)
395    public @interface Priority {}
396
397    /**
398     * Default notification {@link #priority}. If your application does not prioritize its own
399     * notifications, use this value for all notifications.
400     */
401    public static final int PRIORITY_DEFAULT = 0;
402
403    /**
404     * Lower {@link #priority}, for items that are less important. The UI may choose to show these
405     * items smaller, or at a different position in the list, compared with your app's
406     * {@link #PRIORITY_DEFAULT} items.
407     */
408    public static final int PRIORITY_LOW = -1;
409
410    /**
411     * Lowest {@link #priority}; these items might not be shown to the user except under special
412     * circumstances, such as detailed notification logs.
413     */
414    public static final int PRIORITY_MIN = -2;
415
416    /**
417     * Higher {@link #priority}, for more important notifications or alerts. The UI may choose to
418     * show these items larger, or at a different position in notification lists, compared with
419     * your app's {@link #PRIORITY_DEFAULT} items.
420     */
421    public static final int PRIORITY_HIGH = 1;
422
423    /**
424     * Highest {@link #priority}, for your application's most important items that require the
425     * user's prompt attention or input.
426     */
427    public static final int PRIORITY_MAX = 2;
428
429    /**
430     * Relative priority for this notification.
431     *
432     * Priority is an indication of how much of the user's valuable attention should be consumed by
433     * this notification. Low-priority notifications may be hidden from the user in certain
434     * situations, while the user might be interrupted for a higher-priority notification. The
435     * system will make a determination about how to interpret this priority when presenting
436     * the notification.
437     */
438    @Priority
439    public int priority;
440
441    /**
442     * Accent color (an ARGB integer like the constants in {@link android.graphics.Color})
443     * to be applied by the standard Style templates when presenting this notification.
444     *
445     * The current template design constructs a colorful header image by overlaying the
446     * {@link #icon} image (stenciled in white) atop a field of this color. Alpha components are
447     * ignored.
448     */
449    public int color = COLOR_DEFAULT;
450
451    /**
452     * Special value of {@link #color} telling the system not to decorate this notification with
453     * any special color but instead use default colors when presenting this notification.
454     */
455    public static final int COLOR_DEFAULT = 0; // AKA Color.TRANSPARENT
456
457    /**
458     * Sphere of visibility of this notification, which affects how and when the SystemUI reveals
459     * the notification's presence and contents in untrusted situations (namely, on the secure
460     * lockscreen).
461     *
462     * The default level, {@link #VISIBILITY_PRIVATE}, behaves exactly as notifications have always
463     * done on Android: The notification's {@link #icon} and {@link #tickerText} (if available) are
464     * shown in all situations, but the contents are only available if the device is unlocked for
465     * the appropriate user.
466     *
467     * A more permissive policy can be expressed by {@link #VISIBILITY_PUBLIC}; such a notification
468     * can be read even in an "insecure" context (that is, above a secure lockscreen).
469     * To modify the public version of this notification—for example, to redact some portions—see
470     * {@link Builder#setPublicVersion(Notification)}.
471     *
472     * Finally, a notification can be made {@link #VISIBILITY_SECRET}, which will suppress its icon
473     * and ticker until the user has bypassed the lockscreen.
474     */
475    public int visibility;
476
477    public static final int VISIBILITY_PUBLIC = 1;
478    public static final int VISIBILITY_PRIVATE = 0;
479    public static final int VISIBILITY_SECRET = -1;
480
481    /**
482     * Notification category: incoming call (voice or video) or similar synchronous communication request.
483     */
484    public static final String CATEGORY_CALL = "call";
485
486    /**
487     * Notification category: incoming direct message (SMS, instant message, etc.).
488     */
489    public static final String CATEGORY_MESSAGE = "msg";
490
491    /**
492     * Notification category: asynchronous bulk message (email).
493     */
494    public static final String CATEGORY_EMAIL = "email";
495
496    /**
497     * Notification category: calendar event.
498     */
499    public static final String CATEGORY_EVENT = "event";
500
501    /**
502     * Notification category: promotion or advertisement.
503     */
504    public static final String CATEGORY_PROMO = "promo";
505
506    /**
507     * Notification category: alarm or timer.
508     */
509    public static final String CATEGORY_ALARM = "alarm";
510
511    /**
512     * Notification category: progress of a long-running background operation.
513     */
514    public static final String CATEGORY_PROGRESS = "progress";
515
516    /**
517     * Notification category: social network or sharing update.
518     */
519    public static final String CATEGORY_SOCIAL = "social";
520
521    /**
522     * Notification category: error in background operation or authentication status.
523     */
524    public static final String CATEGORY_ERROR = "err";
525
526    /**
527     * Notification category: media transport control for playback.
528     */
529    public static final String CATEGORY_TRANSPORT = "transport";
530
531    /**
532     * Notification category: system or device status update.  Reserved for system use.
533     */
534    public static final String CATEGORY_SYSTEM = "sys";
535
536    /**
537     * Notification category: indication of running background service.
538     */
539    public static final String CATEGORY_SERVICE = "service";
540
541    /**
542     * Notification category: a specific, timely recommendation for a single thing.
543     * For example, a news app might want to recommend a news story it believes the user will
544     * want to read next.
545     */
546    public static final String CATEGORY_RECOMMENDATION = "recommendation";
547
548    /**
549     * Notification category: ongoing information about device or contextual status.
550     */
551    public static final String CATEGORY_STATUS = "status";
552
553    /**
554     * One of the predefined notification categories (see the <code>CATEGORY_*</code> constants)
555     * that best describes this Notification.  May be used by the system for ranking and filtering.
556     */
557    public String category;
558
559    private String mGroupKey;
560
561    /**
562     * Get the key used to group this notification into a cluster or stack
563     * with other notifications on devices which support such rendering.
564     */
565    public String getGroup() {
566        return mGroupKey;
567    }
568
569    private String mSortKey;
570
571    /**
572     * Get a sort key that orders this notification among other notifications from the
573     * same package. This can be useful if an external sort was already applied and an app
574     * would like to preserve this. Notifications will be sorted lexicographically using this
575     * value, although providing different priorities in addition to providing sort key may
576     * cause this value to be ignored.
577     *
578     * <p>This sort key can also be used to order members of a notification group. See
579     * {@link Builder#setGroup}.
580     *
581     * @see String#compareTo(String)
582     */
583    public String getSortKey() {
584        return mSortKey;
585    }
586
587    /**
588     * Additional semantic data to be carried around with this Notification.
589     * <p>
590     * The extras keys defined here are intended to capture the original inputs to {@link Builder}
591     * APIs, and are intended to be used by
592     * {@link android.service.notification.NotificationListenerService} implementations to extract
593     * detailed information from notification objects.
594     */
595    public Bundle extras = new Bundle();
596
597    /**
598     * {@link #extras} key: this is the title of the notification,
599     * as supplied to {@link Builder#setContentTitle(CharSequence)}.
600     */
601    public static final String EXTRA_TITLE = "android.title";
602
603    /**
604     * {@link #extras} key: this is the title of the notification when shown in expanded form,
605     * e.g. as supplied to {@link BigTextStyle#setBigContentTitle(CharSequence)}.
606     */
607    public static final String EXTRA_TITLE_BIG = EXTRA_TITLE + ".big";
608
609    /**
610     * {@link #extras} key: this is the main text payload, as supplied to
611     * {@link Builder#setContentText(CharSequence)}.
612     */
613    public static final String EXTRA_TEXT = "android.text";
614
615    /**
616     * {@link #extras} key: this is a third line of text, as supplied to
617     * {@link Builder#setSubText(CharSequence)}.
618     */
619    public static final String EXTRA_SUB_TEXT = "android.subText";
620
621    /**
622     * {@link #extras} key: this is a small piece of additional text as supplied to
623     * {@link Builder#setContentInfo(CharSequence)}.
624     */
625    public static final String EXTRA_INFO_TEXT = "android.infoText";
626
627    /**
628     * {@link #extras} key: this is a line of summary information intended to be shown
629     * alongside expanded notifications, as supplied to (e.g.)
630     * {@link BigTextStyle#setSummaryText(CharSequence)}.
631     */
632    public static final String EXTRA_SUMMARY_TEXT = "android.summaryText";
633
634    /**
635     * {@link #extras} key: this is the resource ID of the notification's main small icon, as
636     * supplied to {@link Builder#setSmallIcon(int)}.
637     */
638    public static final String EXTRA_SMALL_ICON = "android.icon";
639
640    /**
641     * {@link #extras} key: this is a bitmap to be used instead of the small icon when showing the
642     * notification payload, as
643     * supplied to {@link Builder#setLargeIcon(android.graphics.Bitmap)}.
644     */
645    public static final String EXTRA_LARGE_ICON = "android.largeIcon";
646
647    /**
648     * {@link #extras} key: this is a bitmap to be used instead of the one from
649     * {@link Builder#setLargeIcon(android.graphics.Bitmap)} when the notification is
650     * shown in its expanded form, as supplied to
651     * {@link BigPictureStyle#bigLargeIcon(android.graphics.Bitmap)}.
652     */
653    public static final String EXTRA_LARGE_ICON_BIG = EXTRA_LARGE_ICON + ".big";
654
655    /**
656     * {@link #extras} key: this is the progress value supplied to
657     * {@link Builder#setProgress(int, int, boolean)}.
658     */
659    public static final String EXTRA_PROGRESS = "android.progress";
660
661    /**
662     * {@link #extras} key: this is the maximum value supplied to
663     * {@link Builder#setProgress(int, int, boolean)}.
664     */
665    public static final String EXTRA_PROGRESS_MAX = "android.progressMax";
666
667    /**
668     * {@link #extras} key: whether the progress bar is indeterminate, supplied to
669     * {@link Builder#setProgress(int, int, boolean)}.
670     */
671    public static final String EXTRA_PROGRESS_INDETERMINATE = "android.progressIndeterminate";
672
673    /**
674     * {@link #extras} key: whether {@link #when} should be shown as a count-up timer (specifically
675     * a {@link android.widget.Chronometer}) instead of a timestamp, as supplied to
676     * {@link Builder#setUsesChronometer(boolean)}.
677     */
678    public static final String EXTRA_SHOW_CHRONOMETER = "android.showChronometer";
679
680    /**
681     * {@link #extras} key: whether {@link #when} should be shown,
682     * as supplied to {@link Builder#setShowWhen(boolean)}.
683     */
684    public static final String EXTRA_SHOW_WHEN = "android.showWhen";
685
686    /**
687     * {@link #extras} key: this is a bitmap to be shown in {@link BigPictureStyle} expanded
688     * notifications, supplied to {@link BigPictureStyle#bigPicture(android.graphics.Bitmap)}.
689     */
690    public static final String EXTRA_PICTURE = "android.picture";
691
692    /**
693     * {@link #extras} key: An array of CharSequences to show in {@link InboxStyle} expanded
694     * notifications, each of which was supplied to {@link InboxStyle#addLine(CharSequence)}.
695     */
696    public static final String EXTRA_TEXT_LINES = "android.textLines";
697
698    /**
699     * {@link #extras} key: A string representing the name of the specific
700     * {@link android.app.Notification.Style} used to create this notification.
701     */
702    public static final String EXTRA_TEMPLATE = "android.template";
703
704    /**
705     * {@link #extras} key: An array of people that this notification relates to, specified
706     * by contacts provider contact URI.
707     */
708    public static final String EXTRA_PEOPLE = "android.people";
709
710    /**
711     * @hide
712     * Extra added by NotificationManagerService to indicate whether
713     * the Notifications's score has been modified.
714     */
715    public static final String EXTRA_SCORE_MODIFIED = "android.scoreModified";
716
717    /**
718     * Not used.
719     * @hide
720     */
721    public static final String EXTRA_AS_HEADS_UP = "headsup";
722
723    /**
724     * Allow certain system-generated notifications to appear before the device is provisioned.
725     * Only available to notifications coming from the android package.
726     * @hide
727     */
728    public static final String EXTRA_ALLOW_DURING_SETUP = "android.allowDuringSetup";
729
730    /**
731     * {@link #extras} key: A
732     * {@link android.content.ContentUris content URI} pointing to an image that can be displayed
733     * in the background when the notification is selected. The URI must point to an image stream
734     * suitable for passing into
735     * {@link android.graphics.BitmapFactory#decodeStream(java.io.InputStream)
736     * BitmapFactory.decodeStream}; all other content types will be ignored. The content provider
737     * URI used for this purpose must require no permissions to read the image data.
738     */
739    public static final String EXTRA_BACKGROUND_IMAGE_URI = "android.backgroundImageUri";
740
741    /**
742     * {@link #extras} key: A
743     * {@link android.media.session.MediaSessionToken} associated with a
744     * {@link android.app.Notification.MediaStyle} notification.
745     */
746    public static final String EXTRA_MEDIA_SESSION = "android.mediaSession";
747
748    /**
749     * Value for {@link #EXTRA_AS_HEADS_UP}.
750     * @hide
751     */
752    public static final int HEADS_UP_NEVER = 0;
753
754    /**
755     * Default value for {@link #EXTRA_AS_HEADS_UP}.
756     * @hide
757     */
758    public static final int HEADS_UP_ALLOWED = 1;
759
760    /**
761     * Value for {@link #EXTRA_AS_HEADS_UP}.
762     * @hide
763     */
764    public static final int HEADS_UP_REQUESTED = 2;
765
766    /**
767     * Structure to encapsulate a named action that can be shown as part of this notification.
768     * It must include an icon, a label, and a {@link PendingIntent} to be fired when the action is
769     * selected by the user.
770     * <p>
771     * Apps should use {@link Notification.Builder#addAction(int, CharSequence, PendingIntent)}
772     * or {@link Notification.Builder#addAction(Notification.Action)}
773     * to attach actions.
774     */
775    public static class Action implements Parcelable {
776        private final Bundle mExtras;
777        private final RemoteInput[] mRemoteInputs;
778
779        /**
780         * Small icon representing the action.
781         */
782        public int icon;
783
784        /**
785         * Title of the action.
786         */
787        public CharSequence title;
788
789        /**
790         * Intent to send when the user invokes this action. May be null, in which case the action
791         * may be rendered in a disabled presentation by the system UI.
792         */
793        public PendingIntent actionIntent;
794
795        private Action(Parcel in) {
796            icon = in.readInt();
797            title = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
798            if (in.readInt() == 1) {
799                actionIntent = PendingIntent.CREATOR.createFromParcel(in);
800            }
801            mExtras = in.readBundle();
802            mRemoteInputs = in.createTypedArray(RemoteInput.CREATOR);
803        }
804
805        /**
806         * Use {@link Notification.Builder#addAction(int, CharSequence, PendingIntent)}.
807         */
808        public Action(int icon, CharSequence title, PendingIntent intent) {
809            this(icon, title, intent, new Bundle(), null);
810        }
811
812        private Action(int icon, CharSequence title, PendingIntent intent, Bundle extras,
813                RemoteInput[] remoteInputs) {
814            this.icon = icon;
815            this.title = title;
816            this.actionIntent = intent;
817            this.mExtras = extras != null ? extras : new Bundle();
818            this.mRemoteInputs = remoteInputs;
819        }
820
821        /**
822         * Get additional metadata carried around with this Action.
823         */
824        public Bundle getExtras() {
825            return mExtras;
826        }
827
828        /**
829         * Get the list of inputs to be collected from the user when this action is sent.
830         * May return null if no remote inputs were added.
831         */
832        public RemoteInput[] getRemoteInputs() {
833            return mRemoteInputs;
834        }
835
836        /**
837         * Builder class for {@link Action} objects.
838         */
839        public static final class Builder {
840            private final int mIcon;
841            private final CharSequence mTitle;
842            private final PendingIntent mIntent;
843            private final Bundle mExtras;
844            private ArrayList<RemoteInput> mRemoteInputs;
845
846            /**
847             * Construct a new builder for {@link Action} object.
848             * @param icon icon to show for this action
849             * @param title the title of the action
850             * @param intent the {@link PendingIntent} to fire when users trigger this action
851             */
852            public Builder(int icon, CharSequence title, PendingIntent intent) {
853                this(icon, title, intent, new Bundle(), null);
854            }
855
856            /**
857             * Construct a new builder for {@link Action} object using the fields from an
858             * {@link Action}.
859             * @param action the action to read fields from.
860             */
861            public Builder(Action action) {
862                this(action.icon, action.title, action.actionIntent, new Bundle(action.mExtras),
863                        action.getRemoteInputs());
864            }
865
866            private Builder(int icon, CharSequence title, PendingIntent intent, Bundle extras,
867                    RemoteInput[] remoteInputs) {
868                mIcon = icon;
869                mTitle = title;
870                mIntent = intent;
871                mExtras = extras;
872                if (remoteInputs != null) {
873                    mRemoteInputs = new ArrayList<RemoteInput>(remoteInputs.length);
874                    Collections.addAll(mRemoteInputs, remoteInputs);
875                }
876            }
877
878            /**
879             * Merge additional metadata into this builder.
880             *
881             * <p>Values within the Bundle will replace existing extras values in this Builder.
882             *
883             * @see Notification.Action#extras
884             */
885            public Builder addExtras(Bundle extras) {
886                if (extras != null) {
887                    mExtras.putAll(extras);
888                }
889                return this;
890            }
891
892            /**
893             * Get the metadata Bundle used by this Builder.
894             *
895             * <p>The returned Bundle is shared with this Builder.
896             */
897            public Bundle getExtras() {
898                return mExtras;
899            }
900
901            /**
902             * Add an input to be collected from the user when this action is sent.
903             * Response values can be retrieved from the fired intent by using the
904             * {@link RemoteInput#getResultsFromIntent} function.
905             * @param remoteInput a {@link RemoteInput} to add to the action
906             * @return this object for method chaining
907             */
908            public Builder addRemoteInput(RemoteInput remoteInput) {
909                if (mRemoteInputs == null) {
910                    mRemoteInputs = new ArrayList<RemoteInput>();
911                }
912                mRemoteInputs.add(remoteInput);
913                return this;
914            }
915
916            /**
917             * Apply an extender to this action builder. Extenders may be used to add
918             * metadata or change options on this builder.
919             */
920            public Builder extend(Extender extender) {
921                extender.extend(this);
922                return this;
923            }
924
925            /**
926             * Combine all of the options that have been set and return a new {@link Action}
927             * object.
928             * @return the built action
929             */
930            public Action build() {
931                RemoteInput[] remoteInputs = mRemoteInputs != null
932                        ? mRemoteInputs.toArray(new RemoteInput[mRemoteInputs.size()]) : null;
933                return new Action(mIcon, mTitle, mIntent, mExtras, remoteInputs);
934            }
935        }
936
937        @Override
938        public Action clone() {
939            return new Action(
940                    icon,
941                    title,
942                    actionIntent, // safe to alias
943                    new Bundle(mExtras),
944                    getRemoteInputs());
945        }
946        @Override
947        public int describeContents() {
948            return 0;
949        }
950        @Override
951        public void writeToParcel(Parcel out, int flags) {
952            out.writeInt(icon);
953            TextUtils.writeToParcel(title, out, flags);
954            if (actionIntent != null) {
955                out.writeInt(1);
956                actionIntent.writeToParcel(out, flags);
957            } else {
958                out.writeInt(0);
959            }
960            out.writeBundle(mExtras);
961            out.writeTypedArray(mRemoteInputs, flags);
962        }
963        public static final Parcelable.Creator<Action> CREATOR =
964                new Parcelable.Creator<Action>() {
965            public Action createFromParcel(Parcel in) {
966                return new Action(in);
967            }
968            public Action[] newArray(int size) {
969                return new Action[size];
970            }
971        };
972
973        /**
974         * Extender interface for use with {@link Builder#extend}. Extenders may be used to add
975         * metadata or change options on an action builder.
976         */
977        public interface Extender {
978            /**
979             * Apply this extender to a notification action builder.
980             * @param builder the builder to be modified.
981             * @return the build object for chaining.
982             */
983            public Builder extend(Builder builder);
984        }
985
986        /**
987         * Wearable extender for notification actions. To add extensions to an action,
988         * create a new {@link android.app.Notification.Action.WearableExtender} object using
989         * the {@code WearableExtender()} constructor and apply it to a
990         * {@link android.app.Notification.Action.Builder} using
991         * {@link android.app.Notification.Action.Builder#extend}.
992         *
993         * <pre class="prettyprint">
994         * Notification.Action action = new Notification.Action.Builder(
995         *         R.drawable.archive_all, "Archive all", actionIntent)
996         *         .extend(new Notification.Action.WearableExtender()
997         *                 .setAvailableOffline(false))
998         *         .build();</pre>
999         */
1000        public static final class WearableExtender implements Extender {
1001            /** Notification action extra which contains wearable extensions */
1002            private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS";
1003
1004            private static final String KEY_FLAGS = "flags";
1005
1006            // Flags bitwise-ored to mFlags
1007            private static final int FLAG_AVAILABLE_OFFLINE = 0x1;
1008
1009            // Default value for flags integer
1010            private static final int DEFAULT_FLAGS = FLAG_AVAILABLE_OFFLINE;
1011
1012            private int mFlags = DEFAULT_FLAGS;
1013
1014            /**
1015             * Create a {@link android.app.Notification.Action.WearableExtender} with default
1016             * options.
1017             */
1018            public WearableExtender() {
1019            }
1020
1021            /**
1022             * Create a {@link android.app.Notification.Action.WearableExtender} by reading
1023             * wearable options present in an existing notification action.
1024             * @param action the notification action to inspect.
1025             */
1026            public WearableExtender(Action action) {
1027                Bundle wearableBundle = action.getExtras().getBundle(EXTRA_WEARABLE_EXTENSIONS);
1028                if (wearableBundle != null) {
1029                    mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS);
1030                }
1031            }
1032
1033            /**
1034             * Apply wearable extensions to a notification action that is being built. This is
1035             * typically called by the {@link android.app.Notification.Action.Builder#extend}
1036             * method of {@link android.app.Notification.Action.Builder}.
1037             */
1038            @Override
1039            public Action.Builder extend(Action.Builder builder) {
1040                Bundle wearableBundle = new Bundle();
1041
1042                if (mFlags != DEFAULT_FLAGS) {
1043                    wearableBundle.putInt(KEY_FLAGS, mFlags);
1044                }
1045
1046                builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle);
1047                return builder;
1048            }
1049
1050            @Override
1051            public WearableExtender clone() {
1052                WearableExtender that = new WearableExtender();
1053                that.mFlags = this.mFlags;
1054                return that;
1055            }
1056
1057            /**
1058             * Set whether this action is available when the wearable device is not connected to
1059             * a companion device. The user can still trigger this action when the wearable device is
1060             * offline, but a visual hint will indicate that the action may not be available.
1061             * Defaults to true.
1062             */
1063            public WearableExtender setAvailableOffline(boolean availableOffline) {
1064                setFlag(FLAG_AVAILABLE_OFFLINE, availableOffline);
1065                return this;
1066            }
1067
1068            /**
1069             * Get whether this action is available when the wearable device is not connected to
1070             * a companion device. The user can still trigger this action when the wearable device is
1071             * offline, but a visual hint will indicate that the action may not be available.
1072             * Defaults to true.
1073             */
1074            public boolean isAvailableOffline() {
1075                return (mFlags & FLAG_AVAILABLE_OFFLINE) != 0;
1076            }
1077
1078            private void setFlag(int mask, boolean value) {
1079                if (value) {
1080                    mFlags |= mask;
1081                } else {
1082                    mFlags &= ~mask;
1083                }
1084            }
1085        }
1086    }
1087
1088    /**
1089     * Array of all {@link Action} structures attached to this notification by
1090     * {@link Builder#addAction(int, CharSequence, PendingIntent)}. Mostly useful for instances of
1091     * {@link android.service.notification.NotificationListenerService} that provide an alternative
1092     * interface for invoking actions.
1093     */
1094    public Action[] actions;
1095
1096    /**
1097     * Replacement version of this notification whose content will be shown
1098     * in an insecure context such as atop a secure keyguard. See {@link #visibility}
1099     * and {@link #VISIBILITY_PUBLIC}.
1100     */
1101    public Notification publicVersion;
1102
1103    /**
1104     * Constructs a Notification object with default values.
1105     * You might want to consider using {@link Builder} instead.
1106     */
1107    public Notification()
1108    {
1109        this.when = System.currentTimeMillis();
1110        this.priority = PRIORITY_DEFAULT;
1111    }
1112
1113    /**
1114     * @hide
1115     */
1116    public Notification(Context context, int icon, CharSequence tickerText, long when,
1117            CharSequence contentTitle, CharSequence contentText, Intent contentIntent)
1118    {
1119        this.when = when;
1120        this.icon = icon;
1121        this.tickerText = tickerText;
1122        setLatestEventInfo(context, contentTitle, contentText,
1123                PendingIntent.getActivity(context, 0, contentIntent, 0));
1124    }
1125
1126    /**
1127     * Constructs a Notification object with the information needed to
1128     * have a status bar icon without the standard expanded view.
1129     *
1130     * @param icon          The resource id of the icon to put in the status bar.
1131     * @param tickerText    The text that flows by in the status bar when the notification first
1132     *                      activates.
1133     * @param when          The time to show in the time field.  In the System.currentTimeMillis
1134     *                      timebase.
1135     *
1136     * @deprecated Use {@link Builder} instead.
1137     */
1138    @Deprecated
1139    public Notification(int icon, CharSequence tickerText, long when)
1140    {
1141        this.icon = icon;
1142        this.tickerText = tickerText;
1143        this.when = when;
1144    }
1145
1146    /**
1147     * Unflatten the notification from a parcel.
1148     */
1149    public Notification(Parcel parcel)
1150    {
1151        int version = parcel.readInt();
1152
1153        when = parcel.readLong();
1154        icon = parcel.readInt();
1155        number = parcel.readInt();
1156        if (parcel.readInt() != 0) {
1157            contentIntent = PendingIntent.CREATOR.createFromParcel(parcel);
1158        }
1159        if (parcel.readInt() != 0) {
1160            deleteIntent = PendingIntent.CREATOR.createFromParcel(parcel);
1161        }
1162        if (parcel.readInt() != 0) {
1163            tickerText = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(parcel);
1164        }
1165        if (parcel.readInt() != 0) {
1166            tickerView = RemoteViews.CREATOR.createFromParcel(parcel);
1167        }
1168        if (parcel.readInt() != 0) {
1169            contentView = RemoteViews.CREATOR.createFromParcel(parcel);
1170        }
1171        if (parcel.readInt() != 0) {
1172            largeIcon = Bitmap.CREATOR.createFromParcel(parcel);
1173        }
1174        defaults = parcel.readInt();
1175        flags = parcel.readInt();
1176        if (parcel.readInt() != 0) {
1177            sound = Uri.CREATOR.createFromParcel(parcel);
1178        }
1179
1180        audioStreamType = parcel.readInt();
1181        vibrate = parcel.createLongArray();
1182        ledARGB = parcel.readInt();
1183        ledOnMS = parcel.readInt();
1184        ledOffMS = parcel.readInt();
1185        iconLevel = parcel.readInt();
1186
1187        if (parcel.readInt() != 0) {
1188            fullScreenIntent = PendingIntent.CREATOR.createFromParcel(parcel);
1189        }
1190
1191        priority = parcel.readInt();
1192
1193        category = parcel.readString();
1194
1195        mGroupKey = parcel.readString();
1196
1197        mSortKey = parcel.readString();
1198
1199        extras = parcel.readBundle(); // may be null
1200
1201        actions = parcel.createTypedArray(Action.CREATOR); // may be null
1202
1203        if (parcel.readInt() != 0) {
1204            bigContentView = RemoteViews.CREATOR.createFromParcel(parcel);
1205        }
1206
1207        if (parcel.readInt() != 0) {
1208            headsUpContentView = RemoteViews.CREATOR.createFromParcel(parcel);
1209        }
1210
1211        visibility = parcel.readInt();
1212
1213        if (parcel.readInt() != 0) {
1214            publicVersion = Notification.CREATOR.createFromParcel(parcel);
1215        }
1216
1217        color = parcel.readInt();
1218    }
1219
1220    @Override
1221    public Notification clone() {
1222        Notification that = new Notification();
1223        cloneInto(that, true);
1224        return that;
1225    }
1226
1227    /**
1228     * Copy all (or if heavy is false, all except Bitmaps and RemoteViews) members
1229     * of this into that.
1230     * @hide
1231     */
1232    public void cloneInto(Notification that, boolean heavy) {
1233        that.when = this.when;
1234        that.icon = this.icon;
1235        that.number = this.number;
1236
1237        // PendingIntents are global, so there's no reason (or way) to clone them.
1238        that.contentIntent = this.contentIntent;
1239        that.deleteIntent = this.deleteIntent;
1240        that.fullScreenIntent = this.fullScreenIntent;
1241
1242        if (this.tickerText != null) {
1243            that.tickerText = this.tickerText.toString();
1244        }
1245        if (heavy && this.tickerView != null) {
1246            that.tickerView = this.tickerView.clone();
1247        }
1248        if (heavy && this.contentView != null) {
1249            that.contentView = this.contentView.clone();
1250        }
1251        if (heavy && this.largeIcon != null) {
1252            that.largeIcon = Bitmap.createBitmap(this.largeIcon);
1253        }
1254        that.iconLevel = this.iconLevel;
1255        that.sound = this.sound; // android.net.Uri is immutable
1256        that.audioStreamType = this.audioStreamType;
1257
1258        final long[] vibrate = this.vibrate;
1259        if (vibrate != null) {
1260            final int N = vibrate.length;
1261            final long[] vib = that.vibrate = new long[N];
1262            System.arraycopy(vibrate, 0, vib, 0, N);
1263        }
1264
1265        that.ledARGB = this.ledARGB;
1266        that.ledOnMS = this.ledOnMS;
1267        that.ledOffMS = this.ledOffMS;
1268        that.defaults = this.defaults;
1269
1270        that.flags = this.flags;
1271
1272        that.priority = this.priority;
1273
1274        that.category = this.category;
1275
1276        that.mGroupKey = this.mGroupKey;
1277
1278        that.mSortKey = this.mSortKey;
1279
1280        if (this.extras != null) {
1281            try {
1282                that.extras = new Bundle(this.extras);
1283                // will unparcel
1284                that.extras.size();
1285            } catch (BadParcelableException e) {
1286                Log.e(TAG, "could not unparcel extras from notification: " + this, e);
1287                that.extras = null;
1288            }
1289        }
1290
1291        if (this.actions != null) {
1292            that.actions = new Action[this.actions.length];
1293            for(int i=0; i<this.actions.length; i++) {
1294                that.actions[i] = this.actions[i].clone();
1295            }
1296        }
1297
1298        if (heavy && this.bigContentView != null) {
1299            that.bigContentView = this.bigContentView.clone();
1300        }
1301
1302        if (heavy && this.headsUpContentView != null) {
1303            that.headsUpContentView = this.headsUpContentView.clone();
1304        }
1305
1306        that.visibility = this.visibility;
1307
1308        if (this.publicVersion != null) {
1309            that.publicVersion = new Notification();
1310            this.publicVersion.cloneInto(that.publicVersion, heavy);
1311        }
1312
1313        that.color = this.color;
1314
1315        if (!heavy) {
1316            that.lightenPayload(); // will clean out extras
1317        }
1318    }
1319
1320    /**
1321     * Removes heavyweight parts of the Notification object for archival or for sending to
1322     * listeners when the full contents are not necessary.
1323     * @hide
1324     */
1325    public final void lightenPayload() {
1326        tickerView = null;
1327        contentView = null;
1328        bigContentView = null;
1329        headsUpContentView = null;
1330        largeIcon = null;
1331        if (extras != null) {
1332            extras.remove(Notification.EXTRA_LARGE_ICON);
1333            extras.remove(Notification.EXTRA_LARGE_ICON_BIG);
1334            extras.remove(Notification.EXTRA_PICTURE);
1335        }
1336    }
1337
1338    /**
1339     * Make sure this CharSequence is safe to put into a bundle, which basically
1340     * means it had better not be some custom Parcelable implementation.
1341     * @hide
1342     */
1343    public static CharSequence safeCharSequence(CharSequence cs) {
1344        if (cs instanceof Parcelable) {
1345            Log.e(TAG, "warning: " + cs.getClass().getCanonicalName()
1346                    + " instance is a custom Parcelable and not allowed in Notification");
1347            return cs.toString();
1348        }
1349
1350        return cs;
1351    }
1352
1353    public int describeContents() {
1354        return 0;
1355    }
1356
1357    /**
1358     * Flatten this notification from a parcel.
1359     */
1360    public void writeToParcel(Parcel parcel, int flags)
1361    {
1362        parcel.writeInt(1);
1363
1364        parcel.writeLong(when);
1365        parcel.writeInt(icon);
1366        parcel.writeInt(number);
1367        if (contentIntent != null) {
1368            parcel.writeInt(1);
1369            contentIntent.writeToParcel(parcel, 0);
1370        } else {
1371            parcel.writeInt(0);
1372        }
1373        if (deleteIntent != null) {
1374            parcel.writeInt(1);
1375            deleteIntent.writeToParcel(parcel, 0);
1376        } else {
1377            parcel.writeInt(0);
1378        }
1379        if (tickerText != null) {
1380            parcel.writeInt(1);
1381            TextUtils.writeToParcel(tickerText, parcel, flags);
1382        } else {
1383            parcel.writeInt(0);
1384        }
1385        if (tickerView != null) {
1386            parcel.writeInt(1);
1387            tickerView.writeToParcel(parcel, 0);
1388        } else {
1389            parcel.writeInt(0);
1390        }
1391        if (contentView != null) {
1392            parcel.writeInt(1);
1393            contentView.writeToParcel(parcel, 0);
1394        } else {
1395            parcel.writeInt(0);
1396        }
1397        if (largeIcon != null) {
1398            parcel.writeInt(1);
1399            largeIcon.writeToParcel(parcel, 0);
1400        } else {
1401            parcel.writeInt(0);
1402        }
1403
1404        parcel.writeInt(defaults);
1405        parcel.writeInt(this.flags);
1406
1407        if (sound != null) {
1408            parcel.writeInt(1);
1409            sound.writeToParcel(parcel, 0);
1410        } else {
1411            parcel.writeInt(0);
1412        }
1413        parcel.writeInt(audioStreamType);
1414        parcel.writeLongArray(vibrate);
1415        parcel.writeInt(ledARGB);
1416        parcel.writeInt(ledOnMS);
1417        parcel.writeInt(ledOffMS);
1418        parcel.writeInt(iconLevel);
1419
1420        if (fullScreenIntent != null) {
1421            parcel.writeInt(1);
1422            fullScreenIntent.writeToParcel(parcel, 0);
1423        } else {
1424            parcel.writeInt(0);
1425        }
1426
1427        parcel.writeInt(priority);
1428
1429        parcel.writeString(category);
1430
1431        parcel.writeString(mGroupKey);
1432
1433        parcel.writeString(mSortKey);
1434
1435        parcel.writeBundle(extras); // null ok
1436
1437        parcel.writeTypedArray(actions, 0); // null ok
1438
1439        if (bigContentView != null) {
1440            parcel.writeInt(1);
1441            bigContentView.writeToParcel(parcel, 0);
1442        } else {
1443            parcel.writeInt(0);
1444        }
1445
1446        if (headsUpContentView != null) {
1447            parcel.writeInt(1);
1448            headsUpContentView.writeToParcel(parcel, 0);
1449        } else {
1450            parcel.writeInt(0);
1451        }
1452
1453        parcel.writeInt(visibility);
1454
1455        if (publicVersion != null) {
1456            parcel.writeInt(1);
1457            publicVersion.writeToParcel(parcel, 0);
1458        } else {
1459            parcel.writeInt(0);
1460        }
1461
1462        parcel.writeInt(color);
1463    }
1464
1465    /**
1466     * Parcelable.Creator that instantiates Notification objects
1467     */
1468    public static final Parcelable.Creator<Notification> CREATOR
1469            = new Parcelable.Creator<Notification>()
1470    {
1471        public Notification createFromParcel(Parcel parcel)
1472        {
1473            return new Notification(parcel);
1474        }
1475
1476        public Notification[] newArray(int size)
1477        {
1478            return new Notification[size];
1479        }
1480    };
1481
1482    /**
1483     * Sets the {@link #contentView} field to be a view with the standard "Latest Event"
1484     * layout.
1485     *
1486     * <p>Uses the {@link #icon} and {@link #when} fields to set the icon and time fields
1487     * in the view.</p>
1488     * @param context       The context for your application / activity.
1489     * @param contentTitle The title that goes in the expanded entry.
1490     * @param contentText  The text that goes in the expanded entry.
1491     * @param contentIntent The intent to launch when the user clicks the expanded notification.
1492     * If this is an activity, it must include the
1493     * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires
1494     * that you take care of task management as described in the
1495     * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back
1496     * Stack</a> document.
1497     *
1498     * @deprecated Use {@link Builder} instead.
1499     */
1500    @Deprecated
1501    public void setLatestEventInfo(Context context,
1502            CharSequence contentTitle, CharSequence contentText, PendingIntent contentIntent) {
1503        Notification.Builder builder = new Notification.Builder(context);
1504
1505        // First, ensure that key pieces of information that may have been set directly
1506        // are preserved
1507        builder.setWhen(this.when);
1508        builder.setSmallIcon(this.icon);
1509        builder.setPriority(this.priority);
1510        builder.setTicker(this.tickerText);
1511        builder.setNumber(this.number);
1512        builder.mFlags = this.flags;
1513        builder.setSound(this.sound, this.audioStreamType);
1514        builder.setDefaults(this.defaults);
1515        builder.setVibrate(this.vibrate);
1516
1517        // now apply the latestEventInfo fields
1518        if (contentTitle != null) {
1519            builder.setContentTitle(contentTitle);
1520        }
1521        if (contentText != null) {
1522            builder.setContentText(contentText);
1523        }
1524        builder.setContentIntent(contentIntent);
1525        builder.buildInto(this);
1526    }
1527
1528    @Override
1529    public String toString() {
1530        StringBuilder sb = new StringBuilder();
1531        sb.append("Notification(pri=");
1532        sb.append(priority);
1533        sb.append(" contentView=");
1534        if (contentView != null) {
1535            sb.append(contentView.getPackage());
1536            sb.append("/0x");
1537            sb.append(Integer.toHexString(contentView.getLayoutId()));
1538        } else {
1539            sb.append("null");
1540        }
1541        // TODO(dsandler): defaults take precedence over local values, so reorder the branches below
1542        sb.append(" vibrate=");
1543        if ((this.defaults & DEFAULT_VIBRATE) != 0) {
1544            sb.append("default");
1545        } else if (this.vibrate != null) {
1546            int N = this.vibrate.length-1;
1547            sb.append("[");
1548            for (int i=0; i<N; i++) {
1549                sb.append(this.vibrate[i]);
1550                sb.append(',');
1551            }
1552            if (N != -1) {
1553                sb.append(this.vibrate[N]);
1554            }
1555            sb.append("]");
1556        } else {
1557            sb.append("null");
1558        }
1559        sb.append(" sound=");
1560        if ((this.defaults & DEFAULT_SOUND) != 0) {
1561            sb.append("default");
1562        } else if (this.sound != null) {
1563            sb.append(this.sound.toString());
1564        } else {
1565            sb.append("null");
1566        }
1567        sb.append(" defaults=0x");
1568        sb.append(Integer.toHexString(this.defaults));
1569        sb.append(" flags=0x");
1570        sb.append(Integer.toHexString(this.flags));
1571        sb.append(String.format(" color=0x%08x", this.color));
1572        if (this.category != null) {
1573            sb.append(" category=");
1574            sb.append(this.category);
1575        }
1576        if (this.mGroupKey != null) {
1577            sb.append(" groupKey=");
1578            sb.append(this.mGroupKey);
1579        }
1580        if (this.mSortKey != null) {
1581            sb.append(" sortKey=");
1582            sb.append(this.mSortKey);
1583        }
1584        if (actions != null) {
1585            sb.append(" ");
1586            sb.append(actions.length);
1587            sb.append(" action");
1588            if (actions.length > 1) sb.append("s");
1589        }
1590        sb.append(")");
1591        return sb.toString();
1592    }
1593
1594    /** {@hide} */
1595    public void setUser(UserHandle user) {
1596        if (user.getIdentifier() == UserHandle.USER_ALL) {
1597            user = UserHandle.OWNER;
1598        }
1599        if (tickerView != null) {
1600            tickerView.setUser(user);
1601        }
1602        if (contentView != null) {
1603            contentView.setUser(user);
1604        }
1605        if (bigContentView != null) {
1606            bigContentView.setUser(user);
1607        }
1608        if (headsUpContentView != null) {
1609            headsUpContentView.setUser(user);
1610        }
1611    }
1612
1613    /**
1614     * Builder class for {@link Notification} objects.
1615     *
1616     * Provides a convenient way to set the various fields of a {@link Notification} and generate
1617     * content views using the platform's notification layout template. If your app supports
1618     * versions of Android as old as API level 4, you can instead use
1619     * {@link android.support.v4.app.NotificationCompat.Builder NotificationCompat.Builder},
1620     * available in the <a href="{@docRoot}tools/extras/support-library.html">Android Support
1621     * library</a>.
1622     *
1623     * <p>Example:
1624     *
1625     * <pre class="prettyprint">
1626     * Notification noti = new Notification.Builder(mContext)
1627     *         .setContentTitle(&quot;New mail from &quot; + sender.toString())
1628     *         .setContentText(subject)
1629     *         .setSmallIcon(R.drawable.new_mail)
1630     *         .setLargeIcon(aBitmap)
1631     *         .build();
1632     * </pre>
1633     */
1634    public static class Builder {
1635        private static final int MAX_ACTION_BUTTONS = 3;
1636
1637        private Context mContext;
1638
1639        private long mWhen;
1640        private int mSmallIcon;
1641        private int mSmallIconLevel;
1642        private int mNumber;
1643        private CharSequence mContentTitle;
1644        private CharSequence mContentText;
1645        private CharSequence mContentInfo;
1646        private CharSequence mSubText;
1647        private PendingIntent mContentIntent;
1648        private RemoteViews mContentView;
1649        private PendingIntent mDeleteIntent;
1650        private PendingIntent mFullScreenIntent;
1651        private CharSequence mTickerText;
1652        private RemoteViews mTickerView;
1653        private Bitmap mLargeIcon;
1654        private Uri mSound;
1655        private int mAudioStreamType;
1656        private long[] mVibrate;
1657        private int mLedArgb;
1658        private int mLedOnMs;
1659        private int mLedOffMs;
1660        private int mDefaults;
1661        private int mFlags;
1662        private int mProgressMax;
1663        private int mProgress;
1664        private boolean mProgressIndeterminate;
1665        private String mCategory;
1666        private String mGroupKey;
1667        private String mSortKey;
1668        private Bundle mExtras;
1669        private int mPriority;
1670        private ArrayList<Action> mActions = new ArrayList<Action>(MAX_ACTION_BUTTONS);
1671        private boolean mUseChronometer;
1672        private Style mStyle;
1673        private boolean mShowWhen = true;
1674        private int mVisibility = VISIBILITY_PRIVATE;
1675        private Notification mPublicVersion = null;
1676        private final NotificationColorUtil mColorUtil;
1677        private ArrayList<String> mPeople;
1678        private int mColor = COLOR_DEFAULT;
1679
1680        /**
1681         * Constructs a new Builder with the defaults:
1682         *
1683
1684         * <table>
1685         * <tr><th align=right>priority</th>
1686         *     <td>{@link #PRIORITY_DEFAULT}</td></tr>
1687         * <tr><th align=right>when</th>
1688         *     <td>now ({@link System#currentTimeMillis()})</td></tr>
1689         * <tr><th align=right>audio stream</th>
1690         *     <td>{@link #STREAM_DEFAULT}</td></tr>
1691         * </table>
1692         *
1693
1694         * @param context
1695         *            A {@link Context} that will be used by the Builder to construct the
1696         *            RemoteViews. The Context will not be held past the lifetime of this Builder
1697         *            object.
1698         */
1699        public Builder(Context context) {
1700            /*
1701             * Important compatibility note!
1702             * Some apps out in the wild create a Notification.Builder in their Activity subclass
1703             * constructor for later use. At this point Activities - themselves subclasses of
1704             * ContextWrapper - do not have their inner Context populated yet. This means that
1705             * any calls to Context methods from within this constructor can cause NPEs in existing
1706             * apps. Any data populated from mContext should therefore be populated lazily to
1707             * preserve compatibility.
1708             */
1709            mContext = context;
1710
1711            // Set defaults to match the defaults of a Notification
1712            mWhen = System.currentTimeMillis();
1713            mAudioStreamType = STREAM_DEFAULT;
1714            mPriority = PRIORITY_DEFAULT;
1715            mPeople = new ArrayList<String>();
1716
1717            mColorUtil = NotificationColorUtil.getInstance();
1718        }
1719
1720        /**
1721         * Add a timestamp pertaining to the notification (usually the time the event occurred).
1722         * It will be shown in the notification content view by default; use
1723         * {@link #setShowWhen(boolean) setShowWhen} to control this.
1724         *
1725         * @see Notification#when
1726         */
1727        public Builder setWhen(long when) {
1728            mWhen = when;
1729            return this;
1730        }
1731
1732        /**
1733         * Control whether the timestamp set with {@link #setWhen(long) setWhen} is shown
1734         * in the content view.
1735         */
1736        public Builder setShowWhen(boolean show) {
1737            mShowWhen = show;
1738            return this;
1739        }
1740
1741        /**
1742         * Show the {@link Notification#when} field as a stopwatch.
1743         *
1744         * Instead of presenting <code>when</code> as a timestamp, the notification will show an
1745         * automatically updating display of the minutes and seconds since <code>when</code>.
1746         *
1747         * Useful when showing an elapsed time (like an ongoing phone call).
1748         *
1749         * @see android.widget.Chronometer
1750         * @see Notification#when
1751         */
1752        public Builder setUsesChronometer(boolean b) {
1753            mUseChronometer = b;
1754            return this;
1755        }
1756
1757        /**
1758         * Set the small icon resource, which will be used to represent the notification in the
1759         * status bar.
1760         *
1761
1762         * The platform template for the expanded view will draw this icon in the left, unless a
1763         * {@link #setLargeIcon(Bitmap) large icon} has also been specified, in which case the small
1764         * icon will be moved to the right-hand side.
1765         *
1766
1767         * @param icon
1768         *            A resource ID in the application's package of the drawable to use.
1769         * @see Notification#icon
1770         */
1771        public Builder setSmallIcon(int icon) {
1772            mSmallIcon = icon;
1773            return this;
1774        }
1775
1776        /**
1777         * A variant of {@link #setSmallIcon(int) setSmallIcon(int)} that takes an additional
1778         * level parameter for when the icon is a {@link android.graphics.drawable.LevelListDrawable
1779         * LevelListDrawable}.
1780         *
1781         * @param icon A resource ID in the application's package of the drawable to use.
1782         * @param level The level to use for the icon.
1783         *
1784         * @see Notification#icon
1785         * @see Notification#iconLevel
1786         */
1787        public Builder setSmallIcon(int icon, int level) {
1788            mSmallIcon = icon;
1789            mSmallIconLevel = level;
1790            return this;
1791        }
1792
1793        /**
1794         * Set the first line of text in the platform notification template.
1795         */
1796        public Builder setContentTitle(CharSequence title) {
1797            mContentTitle = safeCharSequence(title);
1798            return this;
1799        }
1800
1801        /**
1802         * Set the second line of text in the platform notification template.
1803         */
1804        public Builder setContentText(CharSequence text) {
1805            mContentText = safeCharSequence(text);
1806            return this;
1807        }
1808
1809        /**
1810         * Set the third line of text in the platform notification template.
1811         * Don't use if you're also using {@link #setProgress(int, int, boolean)}; they occupy the
1812         * same location in the standard template.
1813         */
1814        public Builder setSubText(CharSequence text) {
1815            mSubText = safeCharSequence(text);
1816            return this;
1817        }
1818
1819        /**
1820         * Set the large number at the right-hand side of the notification.  This is
1821         * equivalent to setContentInfo, although it might show the number in a different
1822         * font size for readability.
1823         */
1824        public Builder setNumber(int number) {
1825            mNumber = number;
1826            return this;
1827        }
1828
1829        /**
1830         * A small piece of additional information pertaining to this notification.
1831         *
1832         * The platform template will draw this on the last line of the notification, at the far
1833         * right (to the right of a smallIcon if it has been placed there).
1834         */
1835        public Builder setContentInfo(CharSequence info) {
1836            mContentInfo = safeCharSequence(info);
1837            return this;
1838        }
1839
1840        /**
1841         * Set the progress this notification represents.
1842         *
1843         * The platform template will represent this using a {@link ProgressBar}.
1844         */
1845        public Builder setProgress(int max, int progress, boolean indeterminate) {
1846            mProgressMax = max;
1847            mProgress = progress;
1848            mProgressIndeterminate = indeterminate;
1849            return this;
1850        }
1851
1852        /**
1853         * Supply a custom RemoteViews to use instead of the platform template.
1854         *
1855         * @see Notification#contentView
1856         */
1857        public Builder setContent(RemoteViews views) {
1858            mContentView = views;
1859            return this;
1860        }
1861
1862        /**
1863         * Supply a {@link PendingIntent} to be sent when the notification is clicked.
1864         *
1865         * As of {@link android.os.Build.VERSION_CODES#HONEYCOMB}, if this field is unset and you
1866         * have specified a custom RemoteViews with {@link #setContent(RemoteViews)}, you can use
1867         * {@link RemoteViews#setOnClickPendingIntent RemoteViews.setOnClickPendingIntent(int,PendingIntent)}
1868         * to assign PendingIntents to individual views in that custom layout (i.e., to create
1869         * clickable buttons inside the notification view).
1870         *
1871         * @see Notification#contentIntent Notification.contentIntent
1872         */
1873        public Builder setContentIntent(PendingIntent intent) {
1874            mContentIntent = intent;
1875            return this;
1876        }
1877
1878        /**
1879         * Supply a {@link PendingIntent} to send when the notification is cleared explicitly by the user.
1880         *
1881         * @see Notification#deleteIntent
1882         */
1883        public Builder setDeleteIntent(PendingIntent intent) {
1884            mDeleteIntent = intent;
1885            return this;
1886        }
1887
1888        /**
1889         * An intent to launch instead of posting the notification to the status bar.
1890         * Only for use with extremely high-priority notifications demanding the user's
1891         * <strong>immediate</strong> attention, such as an incoming phone call or
1892         * alarm clock that the user has explicitly set to a particular time.
1893         * If this facility is used for something else, please give the user an option
1894         * to turn it off and use a normal notification, as this can be extremely
1895         * disruptive.
1896         *
1897         * @param intent The pending intent to launch.
1898         * @param highPriority Passing true will cause this notification to be sent
1899         *          even if other notifications are suppressed.
1900         *
1901         * @see Notification#fullScreenIntent
1902         */
1903        public Builder setFullScreenIntent(PendingIntent intent, boolean highPriority) {
1904            mFullScreenIntent = intent;
1905            setFlag(FLAG_HIGH_PRIORITY, highPriority);
1906            return this;
1907        }
1908
1909        /**
1910         * Set the "ticker" text which is displayed in the status bar when the notification first
1911         * arrives.
1912         *
1913         * @see Notification#tickerText
1914         */
1915        public Builder setTicker(CharSequence tickerText) {
1916            mTickerText = safeCharSequence(tickerText);
1917            return this;
1918        }
1919
1920        /**
1921         * Set the text that is displayed in the status bar when the notification first
1922         * arrives, and also a RemoteViews object that may be displayed instead on some
1923         * devices.
1924         *
1925         * @see Notification#tickerText
1926         * @see Notification#tickerView
1927         */
1928        public Builder setTicker(CharSequence tickerText, RemoteViews views) {
1929            mTickerText = safeCharSequence(tickerText);
1930            mTickerView = views;
1931            return this;
1932        }
1933
1934        /**
1935         * Add a large icon to the notification (and the ticker on some devices).
1936         *
1937         * In the platform template, this image will be shown on the left of the notification view
1938         * in place of the {@link #setSmallIcon(int) small icon} (which will move to the right side).
1939         *
1940         * @see Notification#largeIcon
1941         */
1942        public Builder setLargeIcon(Bitmap icon) {
1943            mLargeIcon = icon;
1944            return this;
1945        }
1946
1947        /**
1948         * Set the sound to play.
1949         *
1950         * It will be played on the {@link #STREAM_DEFAULT default stream} for notifications.
1951         *
1952         * @see Notification#sound
1953         */
1954        public Builder setSound(Uri sound) {
1955            mSound = sound;
1956            mAudioStreamType = STREAM_DEFAULT;
1957            return this;
1958        }
1959
1960        /**
1961         * Set the sound to play, along with a specific stream on which to play it.
1962         *
1963         * See {@link android.media.AudioManager} for the <code>STREAM_</code> constants.
1964         *
1965         * @see Notification#sound
1966         */
1967        public Builder setSound(Uri sound, int streamType) {
1968            mSound = sound;
1969            mAudioStreamType = streamType;
1970            return this;
1971        }
1972
1973        /**
1974         * Set the vibration pattern to use.
1975         *
1976
1977         * See {@link android.os.Vibrator#vibrate(long[], int)} for a discussion of the
1978         * <code>pattern</code> parameter.
1979         *
1980
1981         * @see Notification#vibrate
1982         */
1983        public Builder setVibrate(long[] pattern) {
1984            mVibrate = pattern;
1985            return this;
1986        }
1987
1988        /**
1989         * Set the desired color for the indicator LED on the device, as well as the
1990         * blink duty cycle (specified in milliseconds).
1991         *
1992
1993         * Not all devices will honor all (or even any) of these values.
1994         *
1995
1996         * @see Notification#ledARGB
1997         * @see Notification#ledOnMS
1998         * @see Notification#ledOffMS
1999         */
2000        public Builder setLights(int argb, int onMs, int offMs) {
2001            mLedArgb = argb;
2002            mLedOnMs = onMs;
2003            mLedOffMs = offMs;
2004            return this;
2005        }
2006
2007        /**
2008         * Set whether this is an "ongoing" notification.
2009         *
2010
2011         * Ongoing notifications cannot be dismissed by the user, so your application or service
2012         * must take care of canceling them.
2013         *
2014
2015         * They are typically used to indicate a background task that the user is actively engaged
2016         * with (e.g., playing music) or is pending in some way and therefore occupying the device
2017         * (e.g., a file download, sync operation, active network connection).
2018         *
2019
2020         * @see Notification#FLAG_ONGOING_EVENT
2021         * @see Service#setForeground(boolean)
2022         */
2023        public Builder setOngoing(boolean ongoing) {
2024            setFlag(FLAG_ONGOING_EVENT, ongoing);
2025            return this;
2026        }
2027
2028        /**
2029         * Set this flag if you would only like the sound, vibrate
2030         * and ticker to be played if the notification is not already showing.
2031         *
2032         * @see Notification#FLAG_ONLY_ALERT_ONCE
2033         */
2034        public Builder setOnlyAlertOnce(boolean onlyAlertOnce) {
2035            setFlag(FLAG_ONLY_ALERT_ONCE, onlyAlertOnce);
2036            return this;
2037        }
2038
2039        /**
2040         * Make this notification automatically dismissed when the user touches it. The
2041         * PendingIntent set with {@link #setDeleteIntent} will be sent when this happens.
2042         *
2043         * @see Notification#FLAG_AUTO_CANCEL
2044         */
2045        public Builder setAutoCancel(boolean autoCancel) {
2046            setFlag(FLAG_AUTO_CANCEL, autoCancel);
2047            return this;
2048        }
2049
2050        /**
2051         * Set whether or not this notification should not bridge to other devices.
2052         *
2053         * <p>Some notifications can be bridged to other devices for remote display.
2054         * This hint can be set to recommend this notification not be bridged.
2055         */
2056        public Builder setLocalOnly(boolean localOnly) {
2057            setFlag(FLAG_LOCAL_ONLY, localOnly);
2058            return this;
2059        }
2060
2061        /**
2062         * Set which notification properties will be inherited from system defaults.
2063         * <p>
2064         * The value should be one or more of the following fields combined with
2065         * bitwise-or:
2066         * {@link #DEFAULT_SOUND}, {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}.
2067         * <p>
2068         * For all default values, use {@link #DEFAULT_ALL}.
2069         */
2070        public Builder setDefaults(int defaults) {
2071            mDefaults = defaults;
2072            return this;
2073        }
2074
2075        /**
2076         * Set the priority of this notification.
2077         *
2078         * @see Notification#priority
2079         */
2080        public Builder setPriority(@Priority int pri) {
2081            mPriority = pri;
2082            return this;
2083        }
2084
2085        /**
2086         * Set the notification category.
2087         *
2088         * @see Notification#category
2089         */
2090        public Builder setCategory(String category) {
2091            mCategory = category;
2092            return this;
2093        }
2094
2095        /**
2096         * Add a person that is relevant to this notification.
2097         *
2098         * @see Notification#EXTRA_PEOPLE
2099         */
2100        public Builder addPerson(String handle) {
2101            mPeople.add(handle);
2102            return this;
2103        }
2104
2105        /**
2106         * Set this notification to be part of a group of notifications sharing the same key.
2107         * Grouped notifications may display in a cluster or stack on devices which
2108         * support such rendering.
2109         *
2110         * <p>To make this notification the summary for its group, also call
2111         * {@link #setGroupSummary}. A sort order can be specified for group members by using
2112         * {@link #setSortKey}.
2113         * @param groupKey The group key of the group.
2114         * @return this object for method chaining
2115         */
2116        public Builder setGroup(String groupKey) {
2117            mGroupKey = groupKey;
2118            return this;
2119        }
2120
2121        /**
2122         * Set this notification to be the group summary for a group of notifications.
2123         * Grouped notifications may display in a cluster or stack on devices which
2124         * support such rendering. Requires a group key also be set using {@link #setGroup}.
2125         * @param isGroupSummary Whether this notification should be a group summary.
2126         * @return this object for method chaining
2127         */
2128        public Builder setGroupSummary(boolean isGroupSummary) {
2129            setFlag(FLAG_GROUP_SUMMARY, isGroupSummary);
2130            return this;
2131        }
2132
2133        /**
2134         * Set a sort key that orders this notification among other notifications from the
2135         * same package. This can be useful if an external sort was already applied and an app
2136         * would like to preserve this. Notifications will be sorted lexicographically using this
2137         * value, although providing different priorities in addition to providing sort key may
2138         * cause this value to be ignored.
2139         *
2140         * <p>This sort key can also be used to order members of a notification group. See
2141         * {@link #setGroup}.
2142         *
2143         * @see String#compareTo(String)
2144         */
2145        public Builder setSortKey(String sortKey) {
2146            mSortKey = sortKey;
2147            return this;
2148        }
2149
2150        /**
2151         * Merge additional metadata into this notification.
2152         *
2153         * <p>Values within the Bundle will replace existing extras values in this Builder.
2154         *
2155         * @see Notification#extras
2156         */
2157        public Builder addExtras(Bundle extras) {
2158            if (extras != null) {
2159                if (mExtras == null) {
2160                    mExtras = new Bundle(extras);
2161                } else {
2162                    mExtras.putAll(extras);
2163                }
2164            }
2165            return this;
2166        }
2167
2168        /**
2169         * Set metadata for this notification.
2170         *
2171         * <p>A reference to the Bundle is held for the lifetime of this Builder, and the Bundle's
2172         * current contents are copied into the Notification each time {@link #build()} is
2173         * called.
2174         *
2175         * <p>Replaces any existing extras values with those from the provided Bundle.
2176         * Use {@link #addExtras} to merge in metadata instead.
2177         *
2178         * @see Notification#extras
2179         */
2180        public Builder setExtras(Bundle extras) {
2181            mExtras = extras;
2182            return this;
2183        }
2184
2185        /**
2186         * Get the current metadata Bundle used by this notification Builder.
2187         *
2188         * <p>The returned Bundle is shared with this Builder.
2189         *
2190         * <p>The current contents of this Bundle are copied into the Notification each time
2191         * {@link #build()} is called.
2192         *
2193         * @see Notification#extras
2194         */
2195        public Bundle getExtras() {
2196            if (mExtras == null) {
2197                mExtras = new Bundle();
2198            }
2199            return mExtras;
2200        }
2201
2202        /**
2203         * Add an action to this notification. Actions are typically displayed by
2204         * the system as a button adjacent to the notification content.
2205         * <p>
2206         * Every action must have an icon (32dp square and matching the
2207         * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo
2208         * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}.
2209         * <p>
2210         * A notification in its expanded form can display up to 3 actions, from left to right in
2211         * the order they were added. Actions will not be displayed when the notification is
2212         * collapsed, however, so be sure that any essential functions may be accessed by the user
2213         * in some other way (for example, in the Activity pointed to by {@link #contentIntent}).
2214         *
2215         * @param icon Resource ID of a drawable that represents the action.
2216         * @param title Text describing the action.
2217         * @param intent PendingIntent to be fired when the action is invoked.
2218         */
2219        public Builder addAction(int icon, CharSequence title, PendingIntent intent) {
2220            mActions.add(new Action(icon, safeCharSequence(title), intent));
2221            return this;
2222        }
2223
2224        /**
2225         * Add an action to this notification. Actions are typically displayed by
2226         * the system as a button adjacent to the notification content.
2227         * <p>
2228         * Every action must have an icon (32dp square and matching the
2229         * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo
2230         * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}.
2231         * <p>
2232         * A notification in its expanded form can display up to 3 actions, from left to right in
2233         * the order they were added. Actions will not be displayed when the notification is
2234         * collapsed, however, so be sure that any essential functions may be accessed by the user
2235         * in some other way (for example, in the Activity pointed to by {@link #contentIntent}).
2236         *
2237         * @param action The action to add.
2238         */
2239        public Builder addAction(Action action) {
2240            mActions.add(action);
2241            return this;
2242        }
2243
2244        /**
2245         * Add a rich notification style to be applied at build time.
2246         *
2247         * @param style Object responsible for modifying the notification style.
2248         */
2249        public Builder setStyle(Style style) {
2250            if (mStyle != style) {
2251                mStyle = style;
2252                if (mStyle != null) {
2253                    mStyle.setBuilder(this);
2254                }
2255            }
2256            return this;
2257        }
2258
2259        /**
2260         * Specify the value of {@link #visibility}.
2261         *
2262         * @param visibility One of {@link #VISIBILITY_PRIVATE} (the default),
2263         * {@link #VISIBILITY_SECRET}, or {@link #VISIBILITY_PUBLIC}.
2264         *
2265         * @return The same Builder.
2266         */
2267        public Builder setVisibility(int visibility) {
2268            mVisibility = visibility;
2269            return this;
2270        }
2271
2272        /**
2273         * Supply a replacement Notification whose contents should be shown in insecure contexts
2274         * (i.e. atop the secure lockscreen). See {@link #visibility} and {@link #VISIBILITY_PUBLIC}.
2275         * @param n A replacement notification, presumably with some or all info redacted.
2276         * @return The same Builder.
2277         */
2278        public Builder setPublicVersion(Notification n) {
2279            mPublicVersion = n;
2280            return this;
2281        }
2282
2283        /**
2284         * Apply an extender to this notification builder. Extenders may be used to add
2285         * metadata or change options on this builder.
2286         */
2287        public Builder extend(Extender extender) {
2288            extender.extend(this);
2289            return this;
2290        }
2291
2292        private void setFlag(int mask, boolean value) {
2293            if (value) {
2294                mFlags |= mask;
2295            } else {
2296                mFlags &= ~mask;
2297            }
2298        }
2299
2300        /**
2301         * Sets {@link Notification#color}.
2302         *
2303         * @param argb The accent color to use
2304         *
2305         * @return The same Builder.
2306         */
2307        public Builder setColor(int argb) {
2308            mColor = argb;
2309            return this;
2310        }
2311
2312        private Bitmap getProfileBadge() {
2313            UserManager userManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
2314            Drawable badge = userManager.getBadgeForUser(android.os.Process.myUserHandle());
2315            if (badge == null) {
2316                return null;
2317            }
2318            final int width = badge.getIntrinsicWidth();
2319            final int height = badge.getIntrinsicHeight();
2320            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
2321            Canvas canvas = new Canvas(bitmap);
2322            badge.setBounds(0, 0, width, height);
2323            badge.draw(canvas);
2324            return bitmap;
2325        }
2326
2327        private RemoteViews applyStandardTemplate(int resId, boolean fitIn1U) {
2328            Bitmap profileIcon = getProfileBadge();
2329            RemoteViews contentView = new RemoteViews(mContext.getPackageName(), resId);
2330            boolean showLine3 = false;
2331            boolean showLine2 = false;
2332
2333            if (mPriority < PRIORITY_LOW) {
2334                // TODO: Low priority presentation
2335            }
2336            if (profileIcon != null) {
2337                contentView.setImageViewBitmap(R.id.profile_icon, profileIcon);
2338                contentView.setViewVisibility(R.id.profile_icon, View.VISIBLE);
2339            } else {
2340                contentView.setViewVisibility(R.id.profile_icon, View.GONE);
2341            }
2342            if (mLargeIcon != null) {
2343                contentView.setImageViewBitmap(R.id.icon, mLargeIcon);
2344                processLargeIcon(mLargeIcon, contentView);
2345                contentView.setImageViewResource(R.id.right_icon, mSmallIcon);
2346                contentView.setViewVisibility(R.id.right_icon, View.VISIBLE);
2347                processSmallRightIcon(mSmallIcon, contentView);
2348            } else { // small icon at left
2349                contentView.setImageViewResource(R.id.icon, mSmallIcon);
2350                contentView.setViewVisibility(R.id.icon, View.VISIBLE);
2351                processSmallIconAsLarge(mSmallIcon, contentView);
2352            }
2353            if (mContentTitle != null) {
2354                contentView.setTextViewText(R.id.title, processLegacyText(mContentTitle));
2355            }
2356            if (mContentText != null) {
2357                contentView.setTextViewText(R.id.text, processLegacyText(mContentText));
2358                showLine3 = true;
2359            }
2360            if (mContentInfo != null) {
2361                contentView.setTextViewText(R.id.info, processLegacyText(mContentInfo));
2362                contentView.setViewVisibility(R.id.info, View.VISIBLE);
2363                showLine3 = true;
2364            } else if (mNumber > 0) {
2365                final int tooBig = mContext.getResources().getInteger(
2366                        R.integer.status_bar_notification_info_maxnum);
2367                if (mNumber > tooBig) {
2368                    contentView.setTextViewText(R.id.info, processLegacyText(
2369                            mContext.getResources().getString(
2370                                    R.string.status_bar_notification_info_overflow)));
2371                } else {
2372                    NumberFormat f = NumberFormat.getIntegerInstance();
2373                    contentView.setTextViewText(R.id.info, processLegacyText(f.format(mNumber)));
2374                }
2375                contentView.setViewVisibility(R.id.info, View.VISIBLE);
2376                showLine3 = true;
2377            } else {
2378                contentView.setViewVisibility(R.id.info, View.GONE);
2379            }
2380
2381            // Need to show three lines?
2382            if (mSubText != null) {
2383                contentView.setTextViewText(R.id.text, processLegacyText(mSubText));
2384                if (mContentText != null) {
2385                    contentView.setTextViewText(R.id.text2, processLegacyText(mContentText));
2386                    contentView.setViewVisibility(R.id.text2, View.VISIBLE);
2387                    showLine2 = true;
2388                } else {
2389                    contentView.setViewVisibility(R.id.text2, View.GONE);
2390                }
2391            } else {
2392                contentView.setViewVisibility(R.id.text2, View.GONE);
2393                if (mProgressMax != 0 || mProgressIndeterminate) {
2394                    contentView.setProgressBar(
2395                            R.id.progress, mProgressMax, mProgress, mProgressIndeterminate);
2396                    contentView.setViewVisibility(R.id.progress, View.VISIBLE);
2397                    showLine2 = true;
2398                } else {
2399                    contentView.setViewVisibility(R.id.progress, View.GONE);
2400                }
2401            }
2402            if (showLine2) {
2403                if (fitIn1U) {
2404                    // need to shrink all the type to make sure everything fits
2405                    final Resources res = mContext.getResources();
2406                    final float subTextSize = res.getDimensionPixelSize(
2407                            R.dimen.notification_subtext_size);
2408                    contentView.setTextViewTextSize(R.id.text, TypedValue.COMPLEX_UNIT_PX, subTextSize);
2409                }
2410                // vertical centering
2411                contentView.setViewPadding(R.id.line1, 0, 0, 0, 0);
2412            }
2413
2414            if (mWhen != 0 && mShowWhen) {
2415                if (mUseChronometer) {
2416                    contentView.setViewVisibility(R.id.chronometer, View.VISIBLE);
2417                    contentView.setLong(R.id.chronometer, "setBase",
2418                            mWhen + (SystemClock.elapsedRealtime() - System.currentTimeMillis()));
2419                    contentView.setBoolean(R.id.chronometer, "setStarted", true);
2420                } else {
2421                    contentView.setViewVisibility(R.id.time, View.VISIBLE);
2422                    contentView.setLong(R.id.time, "setTime", mWhen);
2423                }
2424            } else {
2425                contentView.setViewVisibility(R.id.time, View.GONE);
2426            }
2427
2428            contentView.setViewVisibility(R.id.line3, showLine3 ? View.VISIBLE : View.GONE);
2429            contentView.setViewVisibility(R.id.overflow_divider, showLine3 ? View.VISIBLE : View.GONE);
2430            return contentView;
2431        }
2432
2433        private RemoteViews applyStandardTemplateWithActions(int layoutId) {
2434            RemoteViews big = applyStandardTemplate(layoutId, false);
2435
2436            int N = mActions.size();
2437            if (N > 0) {
2438                big.setViewVisibility(R.id.actions, View.VISIBLE);
2439                big.setViewVisibility(R.id.action_divider, View.VISIBLE);
2440                if (N>MAX_ACTION_BUTTONS) N=MAX_ACTION_BUTTONS;
2441                big.removeAllViews(R.id.actions);
2442                for (int i=0; i<N; i++) {
2443                    final RemoteViews button = generateActionButton(mActions.get(i));
2444                    big.addView(R.id.actions, button);
2445                }
2446            }
2447            return big;
2448        }
2449
2450        private RemoteViews makeContentView() {
2451            if (mContentView != null) {
2452                return mContentView;
2453            } else {
2454                return applyStandardTemplate(getBaseLayoutResource(), true); // no more special large_icon flavor
2455            }
2456        }
2457
2458        private RemoteViews makeTickerView() {
2459            if (mTickerView != null) {
2460                return mTickerView;
2461            } else {
2462                if (mContentView == null) {
2463                    return applyStandardTemplate(mLargeIcon == null
2464                            ? R.layout.status_bar_latest_event_ticker
2465                            : R.layout.status_bar_latest_event_ticker_large_icon, true);
2466                } else {
2467                    return null;
2468                }
2469            }
2470        }
2471
2472        private RemoteViews makeBigContentView() {
2473            if (mActions.size() == 0) return null;
2474
2475            return applyStandardTemplateWithActions(getBigBaseLayoutResource());
2476        }
2477
2478        private RemoteViews makeHeadsUpContentView() {
2479            if (mActions.size() == 0) return null;
2480
2481            return applyStandardTemplateWithActions(getBigBaseLayoutResource());
2482        }
2483
2484
2485        private RemoteViews generateActionButton(Action action) {
2486            final boolean tombstone = (action.actionIntent == null);
2487            RemoteViews button = new RemoteViews(mContext.getPackageName(),
2488                    tombstone ? getActionTombstoneLayoutResource()
2489                              : getActionLayoutResource());
2490            button.setTextViewCompoundDrawablesRelative(R.id.action0, action.icon, 0, 0, 0);
2491            button.setTextViewText(R.id.action0, processLegacyText(action.title));
2492            if (!tombstone) {
2493                button.setOnClickPendingIntent(R.id.action0, action.actionIntent);
2494            }
2495            button.setContentDescription(R.id.action0, action.title);
2496            processLegacyAction(action, button);
2497            return button;
2498        }
2499
2500        /**
2501         * @return Whether we are currently building a notification from a legacy (an app that
2502         *         doesn't create material notifications by itself) app.
2503         */
2504        private boolean isLegacy() {
2505            return mColorUtil != null;
2506        }
2507
2508        private void processLegacyAction(Action action, RemoteViews button) {
2509            if (isLegacy()) {
2510                if (mColorUtil.isGrayscale(mContext, action.icon)) {
2511                    button.setTextViewCompoundDrawablesRelativeColorFilter(R.id.action0, 0,
2512                            mContext.getResources().getColor(
2513                                    R.color.notification_action_legacy_color_filter),
2514                            PorterDuff.Mode.MULTIPLY);
2515                }
2516            }
2517        }
2518
2519        private CharSequence processLegacyText(CharSequence charSequence) {
2520            if (isLegacy()) {
2521                return mColorUtil.invertCharSequenceColors(charSequence);
2522            } else {
2523                return charSequence;
2524            }
2525        }
2526
2527        /**
2528         * Apply any necessary background to smallIcons being used in the largeIcon spot.
2529         */
2530        private void processSmallIconAsLarge(int largeIconId, RemoteViews contentView) {
2531            if (!isLegacy() || mColorUtil.isGrayscale(mContext, largeIconId)) {
2532                applyLargeIconBackground(contentView);
2533            }
2534        }
2535
2536        /**
2537         * Apply any necessary background to a largeIcon if it's a fake smallIcon (that is,
2538         * if it's grayscale).
2539         */
2540        // TODO: also check bounds, transparency, that sort of thing.
2541        private void processLargeIcon(Bitmap largeIcon, RemoteViews contentView) {
2542            if (!isLegacy() || mColorUtil.isGrayscale(largeIcon)) {
2543                applyLargeIconBackground(contentView);
2544            } else {
2545                removeLargeIconBackground(contentView);
2546            }
2547        }
2548
2549        /**
2550         * Add a colored circle behind the largeIcon slot.
2551         */
2552        private void applyLargeIconBackground(RemoteViews contentView) {
2553            contentView.setInt(R.id.icon, "setBackgroundResource",
2554                    R.drawable.notification_icon_legacy_bg_inset);
2555
2556            contentView.setDrawableParameters(
2557                    R.id.icon,
2558                    true,
2559                    -1,
2560                    mColor,
2561                    PorterDuff.Mode.SRC_ATOP,
2562                    -1);
2563        }
2564
2565        private void removeLargeIconBackground(RemoteViews contentView) {
2566            contentView.setInt(R.id.icon, "setBackgroundResource", 0);
2567        }
2568
2569        /**
2570         * Recolor small icons when used in the R.id.right_icon slot.
2571         */
2572        private void processSmallRightIcon(int smallIconDrawableId,
2573                RemoteViews contentView) {
2574            if (!isLegacy() || mColorUtil.isGrayscale(mContext, smallIconDrawableId)) {
2575                contentView.setDrawableParameters(R.id.right_icon, false, -1,
2576                        0xFFFFFFFF,
2577                        PorterDuff.Mode.SRC_ATOP, -1);
2578
2579                contentView.setInt(R.id.right_icon,
2580                        "setBackgroundResource",
2581                        R.drawable.notification_icon_legacy_bg);
2582
2583                contentView.setDrawableParameters(
2584                        R.id.right_icon,
2585                        true,
2586                        -1,
2587                        mColor,
2588                        PorterDuff.Mode.SRC_ATOP,
2589                        -1);
2590            }
2591        }
2592
2593        private int resolveColor() {
2594            if (mColor == COLOR_DEFAULT) {
2595                mColor = mContext.getResources().getColor(R.color.notification_icon_bg_color);
2596            } else {
2597                mColor |= 0xFF000000; // no alpha for custom colors
2598            }
2599            return mColor;
2600        }
2601
2602        /**
2603         * Apply the unstyled operations and return a new {@link Notification} object.
2604         * @hide
2605         */
2606        public Notification buildUnstyled() {
2607            Notification n = new Notification();
2608            n.when = mWhen;
2609            n.icon = mSmallIcon;
2610            n.iconLevel = mSmallIconLevel;
2611            n.number = mNumber;
2612
2613            n.color = resolveColor();
2614
2615            n.contentView = makeContentView();
2616            n.contentIntent = mContentIntent;
2617            n.deleteIntent = mDeleteIntent;
2618            n.fullScreenIntent = mFullScreenIntent;
2619            n.tickerText = mTickerText;
2620            n.tickerView = makeTickerView();
2621            n.largeIcon = mLargeIcon;
2622            n.sound = mSound;
2623            n.audioStreamType = mAudioStreamType;
2624            n.vibrate = mVibrate;
2625            n.ledARGB = mLedArgb;
2626            n.ledOnMS = mLedOnMs;
2627            n.ledOffMS = mLedOffMs;
2628            n.defaults = mDefaults;
2629            n.flags = mFlags;
2630            n.bigContentView = makeBigContentView();
2631            n.headsUpContentView = makeHeadsUpContentView();
2632            if (mLedOnMs != 0 || mLedOffMs != 0) {
2633                n.flags |= FLAG_SHOW_LIGHTS;
2634            }
2635            if ((mDefaults & DEFAULT_LIGHTS) != 0) {
2636                n.flags |= FLAG_SHOW_LIGHTS;
2637            }
2638            n.category = mCategory;
2639            n.mGroupKey = mGroupKey;
2640            n.mSortKey = mSortKey;
2641            n.priority = mPriority;
2642            if (mActions.size() > 0) {
2643                n.actions = new Action[mActions.size()];
2644                mActions.toArray(n.actions);
2645            }
2646            n.visibility = mVisibility;
2647
2648            if (mPublicVersion != null) {
2649                n.publicVersion = new Notification();
2650                mPublicVersion.cloneInto(n.publicVersion, true);
2651            }
2652
2653            return n;
2654        }
2655
2656        /**
2657         * Capture, in the provided bundle, semantic information used in the construction of
2658         * this Notification object.
2659         * @hide
2660         */
2661        public void populateExtras(Bundle extras) {
2662            // Store original information used in the construction of this object
2663            extras.putCharSequence(EXTRA_TITLE, mContentTitle);
2664            extras.putCharSequence(EXTRA_TEXT, mContentText);
2665            extras.putCharSequence(EXTRA_SUB_TEXT, mSubText);
2666            extras.putCharSequence(EXTRA_INFO_TEXT, mContentInfo);
2667            extras.putInt(EXTRA_SMALL_ICON, mSmallIcon);
2668            extras.putInt(EXTRA_PROGRESS, mProgress);
2669            extras.putInt(EXTRA_PROGRESS_MAX, mProgressMax);
2670            extras.putBoolean(EXTRA_PROGRESS_INDETERMINATE, mProgressIndeterminate);
2671            extras.putBoolean(EXTRA_SHOW_CHRONOMETER, mUseChronometer);
2672            extras.putBoolean(EXTRA_SHOW_WHEN, mShowWhen);
2673            if (mLargeIcon != null) {
2674                extras.putParcelable(EXTRA_LARGE_ICON, mLargeIcon);
2675            }
2676            if (!mPeople.isEmpty()) {
2677                extras.putStringArray(EXTRA_PEOPLE, mPeople.toArray(new String[mPeople.size()]));
2678            }
2679        }
2680
2681        /**
2682         * @deprecated Use {@link #build()} instead.
2683         */
2684        @Deprecated
2685        public Notification getNotification() {
2686            return build();
2687        }
2688
2689        /**
2690         * Combine all of the options that have been set and return a new {@link Notification}
2691         * object.
2692         */
2693        public Notification build() {
2694            Notification n = buildUnstyled();
2695
2696            if (mStyle != null) {
2697                n = mStyle.buildStyled(n);
2698            }
2699
2700            n.extras = mExtras != null ? new Bundle(mExtras) : new Bundle();
2701
2702            populateExtras(n.extras);
2703            if (mStyle != null) {
2704                mStyle.addExtras(n.extras);
2705            }
2706
2707            return n;
2708        }
2709
2710        /**
2711         * Apply this Builder to an existing {@link Notification} object.
2712         *
2713         * @hide
2714         */
2715        public Notification buildInto(Notification n) {
2716            build().cloneInto(n, true);
2717            return n;
2718        }
2719
2720
2721        private int getBaseLayoutResource() {
2722            return R.layout.notification_template_material_base;
2723        }
2724
2725        private int getBigBaseLayoutResource() {
2726            return R.layout.notification_template_material_big_base;
2727        }
2728
2729        private int getBigPictureLayoutResource() {
2730            return R.layout.notification_template_material_big_picture;
2731        }
2732
2733        private int getBigTextLayoutResource() {
2734            return R.layout.notification_template_material_big_text;
2735        }
2736
2737        private int getInboxLayoutResource() {
2738            return R.layout.notification_template_material_inbox;
2739        }
2740
2741        private int getActionLayoutResource() {
2742            return R.layout.notification_material_action;
2743        }
2744
2745        private int getActionTombstoneLayoutResource() {
2746            return R.layout.notification_material_action_tombstone;
2747        }
2748    }
2749
2750    /**
2751     * An object that can apply a rich notification style to a {@link Notification.Builder}
2752     * object.
2753     */
2754    public static abstract class Style {
2755        private CharSequence mBigContentTitle;
2756        private CharSequence mSummaryText = null;
2757        private boolean mSummaryTextSet = false;
2758
2759        protected Builder mBuilder;
2760
2761        /**
2762         * Overrides ContentTitle in the big form of the template.
2763         * This defaults to the value passed to setContentTitle().
2764         */
2765        protected void internalSetBigContentTitle(CharSequence title) {
2766            mBigContentTitle = title;
2767        }
2768
2769        /**
2770         * Set the first line of text after the detail section in the big form of the template.
2771         */
2772        protected void internalSetSummaryText(CharSequence cs) {
2773            mSummaryText = cs;
2774            mSummaryTextSet = true;
2775        }
2776
2777        public void setBuilder(Builder builder) {
2778            if (mBuilder != builder) {
2779                mBuilder = builder;
2780                if (mBuilder != null) {
2781                    mBuilder.setStyle(this);
2782                }
2783            }
2784        }
2785
2786        protected void checkBuilder() {
2787            if (mBuilder == null) {
2788                throw new IllegalArgumentException("Style requires a valid Builder object");
2789            }
2790        }
2791
2792        protected RemoteViews getStandardView(int layoutId) {
2793            checkBuilder();
2794
2795            if (mBigContentTitle != null) {
2796                mBuilder.setContentTitle(mBigContentTitle);
2797            }
2798
2799            RemoteViews contentView = mBuilder.applyStandardTemplateWithActions(layoutId);
2800
2801            if (mBigContentTitle != null && mBigContentTitle.equals("")) {
2802                contentView.setViewVisibility(R.id.line1, View.GONE);
2803            } else {
2804                contentView.setViewVisibility(R.id.line1, View.VISIBLE);
2805            }
2806
2807            // The last line defaults to the subtext, but can be replaced by mSummaryText
2808            final CharSequence overflowText =
2809                    mSummaryTextSet ? mSummaryText
2810                                    : mBuilder.mSubText;
2811            if (overflowText != null) {
2812                contentView.setTextViewText(R.id.text, mBuilder.processLegacyText(overflowText));
2813                contentView.setViewVisibility(R.id.overflow_divider, View.VISIBLE);
2814                contentView.setViewVisibility(R.id.line3, View.VISIBLE);
2815            } else {
2816                contentView.setViewVisibility(R.id.overflow_divider, View.GONE);
2817                contentView.setViewVisibility(R.id.line3, View.GONE);
2818            }
2819
2820            return contentView;
2821        }
2822
2823        /**
2824         * @hide
2825         */
2826        public void addExtras(Bundle extras) {
2827            if (mSummaryTextSet) {
2828                extras.putCharSequence(EXTRA_SUMMARY_TEXT, mSummaryText);
2829            }
2830            if (mBigContentTitle != null) {
2831                extras.putCharSequence(EXTRA_TITLE_BIG, mBigContentTitle);
2832            }
2833            extras.putString(EXTRA_TEMPLATE, this.getClass().getName());
2834        }
2835
2836        /**
2837         * @hide
2838         */
2839        public abstract Notification buildStyled(Notification wip);
2840
2841        /**
2842         * Calls {@link android.app.Notification.Builder#build()} on the Builder this Style is
2843         * attached to.
2844         *
2845         * @return the fully constructed Notification.
2846         */
2847        public Notification build() {
2848            checkBuilder();
2849            return mBuilder.build();
2850        }
2851    }
2852
2853    /**
2854     * Helper class for generating large-format notifications that include a large image attachment.
2855     *
2856     * This class is a "rebuilder": It consumes a Builder object and modifies its behavior, like so:
2857     * <pre class="prettyprint">
2858     * Notification noti = new Notification.BigPictureStyle(
2859     *      new Notification.Builder()
2860     *         .setContentTitle(&quot;New photo from &quot; + sender.toString())
2861     *         .setContentText(subject)
2862     *         .setSmallIcon(R.drawable.new_post)
2863     *         .setLargeIcon(aBitmap))
2864     *      .bigPicture(aBigBitmap)
2865     *      .build();
2866     * </pre>
2867     *
2868     * @see Notification#bigContentView
2869     */
2870    public static class BigPictureStyle extends Style {
2871        private Bitmap mPicture;
2872        private Bitmap mBigLargeIcon;
2873        private boolean mBigLargeIconSet = false;
2874
2875        public BigPictureStyle() {
2876        }
2877
2878        public BigPictureStyle(Builder builder) {
2879            setBuilder(builder);
2880        }
2881
2882        /**
2883         * Overrides ContentTitle in the big form of the template.
2884         * This defaults to the value passed to setContentTitle().
2885         */
2886        public BigPictureStyle setBigContentTitle(CharSequence title) {
2887            internalSetBigContentTitle(safeCharSequence(title));
2888            return this;
2889        }
2890
2891        /**
2892         * Set the first line of text after the detail section in the big form of the template.
2893         */
2894        public BigPictureStyle setSummaryText(CharSequence cs) {
2895            internalSetSummaryText(safeCharSequence(cs));
2896            return this;
2897        }
2898
2899        /**
2900         * Provide the bitmap to be used as the payload for the BigPicture notification.
2901         */
2902        public BigPictureStyle bigPicture(Bitmap b) {
2903            mPicture = b;
2904            return this;
2905        }
2906
2907        /**
2908         * Override the large icon when the big notification is shown.
2909         */
2910        public BigPictureStyle bigLargeIcon(Bitmap b) {
2911            mBigLargeIconSet = true;
2912            mBigLargeIcon = b;
2913            return this;
2914        }
2915
2916        private RemoteViews makeBigContentView() {
2917            RemoteViews contentView = getStandardView(mBuilder.getBigPictureLayoutResource());
2918
2919            contentView.setImageViewBitmap(R.id.big_picture, mPicture);
2920
2921            return contentView;
2922        }
2923
2924        /**
2925         * @hide
2926         */
2927        public void addExtras(Bundle extras) {
2928            super.addExtras(extras);
2929
2930            if (mBigLargeIconSet) {
2931                extras.putParcelable(EXTRA_LARGE_ICON_BIG, mBigLargeIcon);
2932            }
2933            extras.putParcelable(EXTRA_PICTURE, mPicture);
2934        }
2935
2936        /**
2937         * @hide
2938         */
2939        @Override
2940        public Notification buildStyled(Notification wip) {
2941            if (mBigLargeIconSet ) {
2942                mBuilder.mLargeIcon = mBigLargeIcon;
2943            }
2944            wip.bigContentView = makeBigContentView();
2945            return wip;
2946        }
2947    }
2948
2949    /**
2950     * Helper class for generating large-format notifications that include a lot of text.
2951     *
2952     * This class is a "rebuilder": It consumes a Builder object and modifies its behavior, like so:
2953     * <pre class="prettyprint">
2954     * Notification noti = new Notification.BigTextStyle(
2955     *      new Notification.Builder()
2956     *         .setContentTitle(&quot;New mail from &quot; + sender.toString())
2957     *         .setContentText(subject)
2958     *         .setSmallIcon(R.drawable.new_mail)
2959     *         .setLargeIcon(aBitmap))
2960     *      .bigText(aVeryLongString)
2961     *      .build();
2962     * </pre>
2963     *
2964     * @see Notification#bigContentView
2965     */
2966    public static class BigTextStyle extends Style {
2967        private CharSequence mBigText;
2968
2969        public BigTextStyle() {
2970        }
2971
2972        public BigTextStyle(Builder builder) {
2973            setBuilder(builder);
2974        }
2975
2976        /**
2977         * Overrides ContentTitle in the big form of the template.
2978         * This defaults to the value passed to setContentTitle().
2979         */
2980        public BigTextStyle setBigContentTitle(CharSequence title) {
2981            internalSetBigContentTitle(safeCharSequence(title));
2982            return this;
2983        }
2984
2985        /**
2986         * Set the first line of text after the detail section in the big form of the template.
2987         */
2988        public BigTextStyle setSummaryText(CharSequence cs) {
2989            internalSetSummaryText(safeCharSequence(cs));
2990            return this;
2991        }
2992
2993        /**
2994         * Provide the longer text to be displayed in the big form of the
2995         * template in place of the content text.
2996         */
2997        public BigTextStyle bigText(CharSequence cs) {
2998            mBigText = safeCharSequence(cs);
2999            return this;
3000        }
3001
3002        /**
3003         * @hide
3004         */
3005        public void addExtras(Bundle extras) {
3006            super.addExtras(extras);
3007
3008            extras.putCharSequence(EXTRA_TEXT, mBigText);
3009        }
3010
3011        private RemoteViews makeBigContentView() {
3012            // Remove the content text so line3 only shows if you have a summary
3013            final boolean hadThreeLines = (mBuilder.mContentText != null && mBuilder.mSubText != null);
3014            mBuilder.mContentText = null;
3015
3016            RemoteViews contentView = getStandardView(mBuilder.getBigTextLayoutResource());
3017
3018            if (hadThreeLines) {
3019                // vertical centering
3020                contentView.setViewPadding(R.id.line1, 0, 0, 0, 0);
3021            }
3022
3023            contentView.setTextViewText(R.id.big_text, mBuilder.processLegacyText(mBigText));
3024            contentView.setViewVisibility(R.id.big_text, View.VISIBLE);
3025            contentView.setViewVisibility(R.id.text2, View.GONE);
3026
3027            return contentView;
3028        }
3029
3030        /**
3031         * @hide
3032         */
3033        @Override
3034        public Notification buildStyled(Notification wip) {
3035            wip.bigContentView = makeBigContentView();
3036
3037            wip.extras.putCharSequence(EXTRA_TEXT, mBigText);
3038
3039            return wip;
3040        }
3041    }
3042
3043    /**
3044     * Helper class for generating large-format notifications that include a list of (up to 5) strings.
3045     *
3046     * This class is a "rebuilder": It consumes a Builder object and modifies its behavior, like so:
3047     * <pre class="prettyprint">
3048     * Notification noti = new Notification.InboxStyle(
3049     *      new Notification.Builder()
3050     *         .setContentTitle(&quot;5 New mails from &quot; + sender.toString())
3051     *         .setContentText(subject)
3052     *         .setSmallIcon(R.drawable.new_mail)
3053     *         .setLargeIcon(aBitmap))
3054     *      .addLine(str1)
3055     *      .addLine(str2)
3056     *      .setContentTitle("")
3057     *      .setSummaryText(&quot;+3 more&quot;)
3058     *      .build();
3059     * </pre>
3060     *
3061     * @see Notification#bigContentView
3062     */
3063    public static class InboxStyle extends Style {
3064        private ArrayList<CharSequence> mTexts = new ArrayList<CharSequence>(5);
3065
3066        public InboxStyle() {
3067        }
3068
3069        public InboxStyle(Builder builder) {
3070            setBuilder(builder);
3071        }
3072
3073        /**
3074         * Overrides ContentTitle in the big form of the template.
3075         * This defaults to the value passed to setContentTitle().
3076         */
3077        public InboxStyle setBigContentTitle(CharSequence title) {
3078            internalSetBigContentTitle(safeCharSequence(title));
3079            return this;
3080        }
3081
3082        /**
3083         * Set the first line of text after the detail section in the big form of the template.
3084         */
3085        public InboxStyle setSummaryText(CharSequence cs) {
3086            internalSetSummaryText(safeCharSequence(cs));
3087            return this;
3088        }
3089
3090        /**
3091         * Append a line to the digest section of the Inbox notification.
3092         */
3093        public InboxStyle addLine(CharSequence cs) {
3094            mTexts.add(safeCharSequence(cs));
3095            return this;
3096        }
3097
3098        /**
3099         * @hide
3100         */
3101        public void addExtras(Bundle extras) {
3102            super.addExtras(extras);
3103            CharSequence[] a = new CharSequence[mTexts.size()];
3104            extras.putCharSequenceArray(EXTRA_TEXT_LINES, mTexts.toArray(a));
3105        }
3106
3107        private RemoteViews makeBigContentView() {
3108            // Remove the content text so line3 disappears unless you have a summary
3109            mBuilder.mContentText = null;
3110            RemoteViews contentView = getStandardView(mBuilder.getInboxLayoutResource());
3111
3112            contentView.setViewVisibility(R.id.text2, View.GONE);
3113
3114            int[] rowIds = {R.id.inbox_text0, R.id.inbox_text1, R.id.inbox_text2, R.id.inbox_text3,
3115                    R.id.inbox_text4, R.id.inbox_text5, R.id.inbox_text6};
3116
3117            // Make sure all rows are gone in case we reuse a view.
3118            for (int rowId : rowIds) {
3119                contentView.setViewVisibility(rowId, View.GONE);
3120            }
3121
3122
3123            int i=0;
3124            while (i < mTexts.size() && i < rowIds.length) {
3125                CharSequence str = mTexts.get(i);
3126                if (str != null && !str.equals("")) {
3127                    contentView.setViewVisibility(rowIds[i], View.VISIBLE);
3128                    contentView.setTextViewText(rowIds[i], mBuilder.processLegacyText(str));
3129                }
3130                i++;
3131            }
3132
3133            contentView.setViewVisibility(R.id.inbox_end_pad,
3134                    mTexts.size() > 0 ? View.VISIBLE : View.GONE);
3135
3136            contentView.setViewVisibility(R.id.inbox_more,
3137                    mTexts.size() > rowIds.length ? View.VISIBLE : View.GONE);
3138
3139            return contentView;
3140        }
3141
3142        /**
3143         * @hide
3144         */
3145        @Override
3146        public Notification buildStyled(Notification wip) {
3147            wip.bigContentView = makeBigContentView();
3148
3149            return wip;
3150        }
3151    }
3152
3153    /**
3154     * Notification style for media playback notifications.
3155     *
3156     * In the expanded form, {@link Notification#bigContentView}, up to 5
3157     * {@link Notification.Action}s specified with
3158     * {@link Notification.Builder#addAction(int, CharSequence, PendingIntent) addAction} will be
3159     * shown as icon-only pushbuttons, suitable for transport controls. The Bitmap given to
3160     * {@link Notification.Builder#setLargeIcon(android.graphics.Bitmap) setLargeIcon()} will be
3161     * treated as album artwork.
3162     *
3163     * Unlike the other styles provided here, MediaStyle can also modify the standard-size
3164     * {@link Notification#contentView}; by providing action indices to
3165     * {@link #setShowActionsInCompactView(int...)} you can promote up to 2 actions to be displayed
3166     * in the standard view alongside the usual content.
3167     *
3168     * Finally, if you attach a {@link android.media.session.MediaSessionToken} using
3169     * {@link android.app.Notification.MediaStyle#setMediaSession(MediaSessionToken)},
3170     * the System UI can identify this as a notification representing an active media session
3171     * and respond accordingly (by showing album artwork in the lockscreen, for example).
3172     *
3173     * To use this style with your Notification, feed it to
3174     * {@link Notification.Builder#setStyle(android.app.Notification.Style)} like so:
3175     * <pre class="prettyprint">
3176     * Notification noti = new Notification.Builder()
3177     *     .setSmallIcon(R.drawable.ic_stat_player)
3178     *     .setContentTitle(&quot;Track title&quot;)     // these three lines are optional
3179     *     .setContentText(&quot;Artist - Album&quot;)   // if you use
3180     *     .setLargeIcon(albumArtBitmap))      // setMediaSession(token, true)
3181     *     .setMediaSession(mySession, true)
3182     *     .setStyle(<b>new Notification.MediaStyle()</b>)
3183     *     .build();
3184     * </pre>
3185     *
3186     * @see Notification#bigContentView
3187     */
3188    public static class MediaStyle extends Style {
3189        static final int MAX_MEDIA_BUTTONS_IN_COMPACT = 2;
3190        static final int MAX_MEDIA_BUTTONS = 5;
3191
3192        private int[] mActionsToShowInCompact = null;
3193        private MediaSessionToken mToken;
3194
3195        public MediaStyle() {
3196        }
3197
3198        public MediaStyle(Builder builder) {
3199            setBuilder(builder);
3200        }
3201
3202        /**
3203         * Request up to 2 actions (by index in the order of addition) to be shown in the compact
3204         * notification view.
3205         */
3206        public MediaStyle setShowActionsInCompactView(int...actions) {
3207            mActionsToShowInCompact = actions;
3208            return this;
3209        }
3210
3211        /**
3212         * Attach a {@link android.media.session.MediaSessionToken} to this Notification to provide
3213         * additional playback information and control to the SystemUI.
3214         */
3215        public MediaStyle setMediaSession(MediaSessionToken token) {
3216            mToken = token;
3217            return this;
3218        }
3219
3220        @Override
3221        public Notification buildStyled(Notification wip) {
3222            wip.contentView = makeMediaContentView();
3223            wip.bigContentView = makeMediaBigContentView();
3224
3225            return wip;
3226        }
3227
3228        /** @hide */
3229        @Override
3230        public void addExtras(Bundle extras) {
3231            super.addExtras(extras);
3232
3233            if (mToken != null) {
3234                extras.putParcelable(EXTRA_MEDIA_SESSION, mToken);
3235            }
3236        }
3237
3238        private RemoteViews generateMediaActionButton(Action action) {
3239            final boolean tombstone = (action.actionIntent == null);
3240            RemoteViews button = new RemoteViews(mBuilder.mContext.getPackageName(),
3241                    R.layout.notification_material_media_action);
3242            button.setImageViewResource(R.id.action0, action.icon);
3243            if (!tombstone) {
3244                button.setOnClickPendingIntent(R.id.action0, action.actionIntent);
3245            }
3246            button.setContentDescription(R.id.action0, action.title);
3247            return button;
3248        }
3249
3250        private RemoteViews makeMediaContentView() {
3251            RemoteViews view = mBuilder.applyStandardTemplate(
3252                    R.layout.notification_template_material_media, true /* 1U */);
3253
3254            final int numActions = mBuilder.mActions.size();
3255            final int N = mActionsToShowInCompact == null
3256                    ? 0
3257                    : Math.min(mActionsToShowInCompact.length, MAX_MEDIA_BUTTONS_IN_COMPACT);
3258            if (N > 0) {
3259                view.removeAllViews(R.id.actions);
3260                for (int i = 0; i < N; i++) {
3261                    if (i >= numActions) {
3262                        throw new IllegalArgumentException(String.format(
3263                                "setShowActionsInCompactView: action %d out of bounds (max %d)",
3264                                i, numActions - 1));
3265                    }
3266
3267                    final Action action = mBuilder.mActions.get(mActionsToShowInCompact[i]);
3268                    final RemoteViews button = generateMediaActionButton(action);
3269                    view.addView(R.id.actions, button);
3270                }
3271            }
3272            return view;
3273        }
3274
3275        private RemoteViews makeMediaBigContentView() {
3276            RemoteViews big = mBuilder.applyStandardTemplate(
3277                    R.layout.notification_template_material_big_media, false);
3278
3279            final int N = Math.min(mBuilder.mActions.size(), MAX_MEDIA_BUTTONS);
3280            if (N > 0) {
3281                big.removeAllViews(R.id.actions);
3282                for (int i=0; i<N; i++) {
3283                    final RemoteViews button = generateMediaActionButton(mBuilder.mActions.get(i));
3284                    big.addView(R.id.actions, button);
3285                }
3286            }
3287            return big;
3288        }
3289    }
3290
3291    /**
3292     * Extender interface for use with {@link Builder#extend}. Extenders may be used to add
3293     * metadata or change options on a notification builder.
3294     */
3295    public interface Extender {
3296        /**
3297         * Apply this extender to a notification builder.
3298         * @param builder the builder to be modified.
3299         * @return the build object for chaining.
3300         */
3301        public Builder extend(Builder builder);
3302    }
3303
3304    /**
3305     * Helper class to add wearable extensions to notifications.
3306     * <p class="note"> See
3307     * <a href="{@docRoot}wear/notifications/creating.html">Creating Notifications
3308     * for Android Wear</a> for more information on how to use this class.
3309     * <p>
3310     * To create a notification with wearable extensions:
3311     * <ol>
3312     *   <li>Create a {@link android.app.Notification.Builder}, setting any desired
3313     *   properties.
3314     *   <li>Create a {@link android.app.Notification.WearableExtender}.
3315     *   <li>Set wearable-specific properties using the
3316     *   {@code add} and {@code set} methods of {@link android.app.Notification.WearableExtender}.
3317     *   <li>Call {@link android.app.Notification.Builder#extend} to apply the extensions to a
3318     *   notification.
3319     *   <li>Post the notification to the notification system with the
3320     *   {@code NotificationManager.notify(...)} methods.
3321     * </ol>
3322     *
3323     * <pre class="prettyprint">
3324     * Notification notif = new Notification.Builder(mContext)
3325     *         .setContentTitle(&quot;New mail from &quot; + sender.toString())
3326     *         .setContentText(subject)
3327     *         .setSmallIcon(R.drawable.new_mail)
3328     *         .extend(new Notification.WearableExtender()
3329     *                 .setContentIcon(R.drawable.new_mail))
3330     *         .build();
3331     * NotificationManager notificationManger =
3332     *         (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
3333     * notificationManger.notify(0, notif);</pre>
3334     *
3335     * <p>Wearable extensions can be accessed on an existing notification by using the
3336     * {@code WearableExtender(Notification)} constructor,
3337     * and then using the {@code get} methods to access values.
3338     *
3339     * <pre class="prettyprint">
3340     * Notification.WearableExtender wearableExtender = new Notification.WearableExtender(
3341     *         notification);
3342     * List&lt;Notification&gt; pages = wearableExtender.getPages();</pre>
3343     */
3344    public static final class WearableExtender implements Extender {
3345        /**
3346         * Sentinel value for an action index that is unset.
3347         */
3348        public static final int UNSET_ACTION_INDEX = -1;
3349
3350        /**
3351         * Size value for use with {@link #setCustomSizePreset} to show this notification with
3352         * default sizing.
3353         * <p>For custom display notifications created using {@link #setDisplayIntent},
3354         * the default is {@link #SIZE_LARGE}. All other notifications size automatically based
3355         * on their content.
3356         */
3357        public static final int SIZE_DEFAULT = 0;
3358
3359        /**
3360         * Size value for use with {@link #setCustomSizePreset} to show this notification
3361         * with an extra small size.
3362         * <p>This value is only applicable for custom display notifications created using
3363         * {@link #setDisplayIntent}.
3364         */
3365        public static final int SIZE_XSMALL = 1;
3366
3367        /**
3368         * Size value for use with {@link #setCustomSizePreset} to show this notification
3369         * with a small size.
3370         * <p>This value is only applicable for custom display notifications created using
3371         * {@link #setDisplayIntent}.
3372         */
3373        public static final int SIZE_SMALL = 2;
3374
3375        /**
3376         * Size value for use with {@link #setCustomSizePreset} to show this notification
3377         * with a medium size.
3378         * <p>This value is only applicable for custom display notifications created using
3379         * {@link #setDisplayIntent}.
3380         */
3381        public static final int SIZE_MEDIUM = 3;
3382
3383        /**
3384         * Size value for use with {@link #setCustomSizePreset} to show this notification
3385         * with a large size.
3386         * <p>This value is only applicable for custom display notifications created using
3387         * {@link #setDisplayIntent}.
3388         */
3389        public static final int SIZE_LARGE = 4;
3390
3391        /**
3392         * Size value for use with {@link #setCustomSizePreset} to show this notification
3393         * full screen.
3394         * <p>This value is only applicable for custom display notifications created using
3395         * {@link #setDisplayIntent}.
3396         */
3397        public static final int SIZE_FULL_SCREEN = 5;
3398
3399        /** Notification extra which contains wearable extensions */
3400        private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS";
3401
3402        // Keys within EXTRA_WEARABLE_OPTIONS for wearable options.
3403        private static final String KEY_ACTIONS = "actions";
3404        private static final String KEY_FLAGS = "flags";
3405        private static final String KEY_DISPLAY_INTENT = "displayIntent";
3406        private static final String KEY_PAGES = "pages";
3407        private static final String KEY_BACKGROUND = "background";
3408        private static final String KEY_CONTENT_ICON = "contentIcon";
3409        private static final String KEY_CONTENT_ICON_GRAVITY = "contentIconGravity";
3410        private static final String KEY_CONTENT_ACTION_INDEX = "contentActionIndex";
3411        private static final String KEY_CUSTOM_SIZE_PRESET = "customSizePreset";
3412        private static final String KEY_CUSTOM_CONTENT_HEIGHT = "customContentHeight";
3413        private static final String KEY_GRAVITY = "gravity";
3414
3415        // Flags bitwise-ored to mFlags
3416        private static final int FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE = 0x1;
3417        private static final int FLAG_HINT_HIDE_ICON = 1 << 1;
3418        private static final int FLAG_HINT_SHOW_BACKGROUND_ONLY = 1 << 2;
3419        private static final int FLAG_START_SCROLL_BOTTOM = 1 << 3;
3420
3421        // Default value for flags integer
3422        private static final int DEFAULT_FLAGS = FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE;
3423
3424        private static final int DEFAULT_CONTENT_ICON_GRAVITY = Gravity.END;
3425        private static final int DEFAULT_GRAVITY = Gravity.BOTTOM;
3426
3427        private ArrayList<Action> mActions = new ArrayList<Action>();
3428        private int mFlags = DEFAULT_FLAGS;
3429        private PendingIntent mDisplayIntent;
3430        private ArrayList<Notification> mPages = new ArrayList<Notification>();
3431        private Bitmap mBackground;
3432        private int mContentIcon;
3433        private int mContentIconGravity = DEFAULT_CONTENT_ICON_GRAVITY;
3434        private int mContentActionIndex = UNSET_ACTION_INDEX;
3435        private int mCustomSizePreset = SIZE_DEFAULT;
3436        private int mCustomContentHeight;
3437        private int mGravity = DEFAULT_GRAVITY;
3438
3439        /**
3440         * Create a {@link android.app.Notification.WearableExtender} with default
3441         * options.
3442         */
3443        public WearableExtender() {
3444        }
3445
3446        public WearableExtender(Notification notif) {
3447            Bundle wearableBundle = notif.extras.getBundle(EXTRA_WEARABLE_EXTENSIONS);
3448            if (wearableBundle != null) {
3449                List<Action> actions = wearableBundle.getParcelableArrayList(KEY_ACTIONS);
3450                if (actions != null) {
3451                    mActions.addAll(actions);
3452                }
3453
3454                mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS);
3455                mDisplayIntent = wearableBundle.getParcelable(KEY_DISPLAY_INTENT);
3456
3457                Notification[] pages = getNotificationArrayFromBundle(
3458                        wearableBundle, KEY_PAGES);
3459                if (pages != null) {
3460                    Collections.addAll(mPages, pages);
3461                }
3462
3463                mBackground = wearableBundle.getParcelable(KEY_BACKGROUND);
3464                mContentIcon = wearableBundle.getInt(KEY_CONTENT_ICON);
3465                mContentIconGravity = wearableBundle.getInt(KEY_CONTENT_ICON_GRAVITY,
3466                        DEFAULT_CONTENT_ICON_GRAVITY);
3467                mContentActionIndex = wearableBundle.getInt(KEY_CONTENT_ACTION_INDEX,
3468                        UNSET_ACTION_INDEX);
3469                mCustomSizePreset = wearableBundle.getInt(KEY_CUSTOM_SIZE_PRESET,
3470                        SIZE_DEFAULT);
3471                mCustomContentHeight = wearableBundle.getInt(KEY_CUSTOM_CONTENT_HEIGHT);
3472                mGravity = wearableBundle.getInt(KEY_GRAVITY, DEFAULT_GRAVITY);
3473            }
3474        }
3475
3476        /**
3477         * Apply wearable extensions to a notification that is being built. This is typically
3478         * called by the {@link android.app.Notification.Builder#extend} method of
3479         * {@link android.app.Notification.Builder}.
3480         */
3481        @Override
3482        public Notification.Builder extend(Notification.Builder builder) {
3483            Bundle wearableBundle = new Bundle();
3484
3485            if (!mActions.isEmpty()) {
3486                wearableBundle.putParcelableArrayList(KEY_ACTIONS, mActions);
3487            }
3488            if (mFlags != DEFAULT_FLAGS) {
3489                wearableBundle.putInt(KEY_FLAGS, mFlags);
3490            }
3491            if (mDisplayIntent != null) {
3492                wearableBundle.putParcelable(KEY_DISPLAY_INTENT, mDisplayIntent);
3493            }
3494            if (!mPages.isEmpty()) {
3495                wearableBundle.putParcelableArray(KEY_PAGES, mPages.toArray(
3496                        new Notification[mPages.size()]));
3497            }
3498            if (mBackground != null) {
3499                wearableBundle.putParcelable(KEY_BACKGROUND, mBackground);
3500            }
3501            if (mContentIcon != 0) {
3502                wearableBundle.putInt(KEY_CONTENT_ICON, mContentIcon);
3503            }
3504            if (mContentIconGravity != DEFAULT_CONTENT_ICON_GRAVITY) {
3505                wearableBundle.putInt(KEY_CONTENT_ICON_GRAVITY, mContentIconGravity);
3506            }
3507            if (mContentActionIndex != UNSET_ACTION_INDEX) {
3508                wearableBundle.putInt(KEY_CONTENT_ACTION_INDEX,
3509                        mContentActionIndex);
3510            }
3511            if (mCustomSizePreset != SIZE_DEFAULT) {
3512                wearableBundle.putInt(KEY_CUSTOM_SIZE_PRESET, mCustomSizePreset);
3513            }
3514            if (mCustomContentHeight != 0) {
3515                wearableBundle.putInt(KEY_CUSTOM_CONTENT_HEIGHT, mCustomContentHeight);
3516            }
3517            if (mGravity != DEFAULT_GRAVITY) {
3518                wearableBundle.putInt(KEY_GRAVITY, mGravity);
3519            }
3520
3521            builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle);
3522            return builder;
3523        }
3524
3525        @Override
3526        public WearableExtender clone() {
3527            WearableExtender that = new WearableExtender();
3528            that.mActions = new ArrayList<Action>(this.mActions);
3529            that.mFlags = this.mFlags;
3530            that.mDisplayIntent = this.mDisplayIntent;
3531            that.mPages = new ArrayList<Notification>(this.mPages);
3532            that.mBackground = this.mBackground;
3533            that.mContentIcon = this.mContentIcon;
3534            that.mContentIconGravity = this.mContentIconGravity;
3535            that.mContentActionIndex = this.mContentActionIndex;
3536            that.mCustomSizePreset = this.mCustomSizePreset;
3537            that.mCustomContentHeight = this.mCustomContentHeight;
3538            that.mGravity = this.mGravity;
3539            return that;
3540        }
3541
3542        /**
3543         * Add a wearable action to this notification.
3544         *
3545         * <p>When wearable actions are added using this method, the set of actions that
3546         * show on a wearable device splits from devices that only show actions added
3547         * using {@link android.app.Notification.Builder#addAction}. This allows for customization
3548         * of which actions display on different devices.
3549         *
3550         * @param action the action to add to this notification
3551         * @return this object for method chaining
3552         * @see android.app.Notification.Action
3553         */
3554        public WearableExtender addAction(Action action) {
3555            mActions.add(action);
3556            return this;
3557        }
3558
3559        /**
3560         * Adds wearable actions to this notification.
3561         *
3562         * <p>When wearable actions are added using this method, the set of actions that
3563         * show on a wearable device splits from devices that only show actions added
3564         * using {@link android.app.Notification.Builder#addAction}. This allows for customization
3565         * of which actions display on different devices.
3566         *
3567         * @param actions the actions to add to this notification
3568         * @return this object for method chaining
3569         * @see android.app.Notification.Action
3570         */
3571        public WearableExtender addActions(List<Action> actions) {
3572            mActions.addAll(actions);
3573            return this;
3574        }
3575
3576        /**
3577         * Clear all wearable actions present on this builder.
3578         * @return this object for method chaining.
3579         * @see #addAction
3580         */
3581        public WearableExtender clearActions() {
3582            mActions.clear();
3583            return this;
3584        }
3585
3586        /**
3587         * Get the wearable actions present on this notification.
3588         */
3589        public List<Action> getActions() {
3590            return mActions;
3591        }
3592
3593        /**
3594         * Set an intent to launch inside of an activity view when displaying
3595         * this notification. The {@link PendingIntent} provided should be for an activity.
3596         *
3597         * <pre class="prettyprint">
3598         * Intent displayIntent = new Intent(context, MyDisplayActivity.class);
3599         * PendingIntent displayPendingIntent = PendingIntent.getActivity(context,
3600         *         0, displayIntent, PendingIntent.FLAG_UPDATE_CURRENT);
3601         * Notification notif = new Notification.Builder(context)
3602         *         .extend(new Notification.WearableExtender()
3603         *                 .setDisplayIntent(displayPendingIntent)
3604         *                 .setCustomSizePreset(Notification.WearableExtender.SIZE_MEDIUM))
3605         *         .build();</pre>
3606         *
3607         * <p>The activity to launch needs to allow embedding, must be exported, and
3608         * should have an empty task affinity.
3609         *
3610         * <p>Example AndroidManifest.xml entry:
3611         * <pre class="prettyprint">
3612         * &lt;activity android:name=&quot;com.example.MyDisplayActivity&quot;
3613         *     android:exported=&quot;true&quot;
3614         *     android:allowEmbedded=&quot;true&quot;
3615         *     android:taskAffinity=&quot;&quot; /&gt;</pre>
3616         *
3617         * @param intent the {@link PendingIntent} for an activity
3618         * @return this object for method chaining
3619         * @see android.app.Notification.WearableExtender#getDisplayIntent
3620         */
3621        public WearableExtender setDisplayIntent(PendingIntent intent) {
3622            mDisplayIntent = intent;
3623            return this;
3624        }
3625
3626        /**
3627         * Get the intent to launch inside of an activity view when displaying this
3628         * notification. This {@code PendingIntent} should be for an activity.
3629         */
3630        public PendingIntent getDisplayIntent() {
3631            return mDisplayIntent;
3632        }
3633
3634        /**
3635         * Add an additional page of content to display with this notification. The current
3636         * notification forms the first page, and pages added using this function form
3637         * subsequent pages. This field can be used to separate a notification into multiple
3638         * sections.
3639         *
3640         * @param page the notification to add as another page
3641         * @return this object for method chaining
3642         * @see android.app.Notification.WearableExtender#getPages
3643         */
3644        public WearableExtender addPage(Notification page) {
3645            mPages.add(page);
3646            return this;
3647        }
3648
3649        /**
3650         * Add additional pages of content to display with this notification. The current
3651         * notification forms the first page, and pages added using this function form
3652         * subsequent pages. This field can be used to separate a notification into multiple
3653         * sections.
3654         *
3655         * @param pages a list of notifications
3656         * @return this object for method chaining
3657         * @see android.app.Notification.WearableExtender#getPages
3658         */
3659        public WearableExtender addPages(List<Notification> pages) {
3660            mPages.addAll(pages);
3661            return this;
3662        }
3663
3664        /**
3665         * Clear all additional pages present on this builder.
3666         * @return this object for method chaining.
3667         * @see #addPage
3668         */
3669        public WearableExtender clearPages() {
3670            mPages.clear();
3671            return this;
3672        }
3673
3674        /**
3675         * Get the array of additional pages of content for displaying this notification. The
3676         * current notification forms the first page, and elements within this array form
3677         * subsequent pages. This field can be used to separate a notification into multiple
3678         * sections.
3679         * @return the pages for this notification
3680         */
3681        public List<Notification> getPages() {
3682            return mPages;
3683        }
3684
3685        /**
3686         * Set a background image to be displayed behind the notification content.
3687         * Contrary to the {@link android.app.Notification.BigPictureStyle}, this background
3688         * will work with any notification style.
3689         *
3690         * @param background the background bitmap
3691         * @return this object for method chaining
3692         * @see android.app.Notification.WearableExtender#getBackground
3693         */
3694        public WearableExtender setBackground(Bitmap background) {
3695            mBackground = background;
3696            return this;
3697        }
3698
3699        /**
3700         * Get a background image to be displayed behind the notification content.
3701         * Contrary to the {@link android.app.Notification.BigPictureStyle}, this background
3702         * will work with any notification style.
3703         *
3704         * @return the background image
3705         * @see android.app.Notification.WearableExtender#setBackground
3706         */
3707        public Bitmap getBackground() {
3708            return mBackground;
3709        }
3710
3711        /**
3712         * Set an icon that goes with the content of this notification.
3713         */
3714        public WearableExtender setContentIcon(int icon) {
3715            mContentIcon = icon;
3716            return this;
3717        }
3718
3719        /**
3720         * Get an icon that goes with the content of this notification.
3721         */
3722        public int getContentIcon() {
3723            return mContentIcon;
3724        }
3725
3726        /**
3727         * Set the gravity that the content icon should have within the notification display.
3728         * Supported values include {@link android.view.Gravity#START} and
3729         * {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}.
3730         * @see #setContentIcon
3731         */
3732        public WearableExtender setContentIconGravity(int contentIconGravity) {
3733            mContentIconGravity = contentIconGravity;
3734            return this;
3735        }
3736
3737        /**
3738         * Get the gravity that the content icon should have within the notification display.
3739         * Supported values include {@link android.view.Gravity#START} and
3740         * {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}.
3741         * @see #getContentIcon
3742         */
3743        public int getContentIconGravity() {
3744            return mContentIconGravity;
3745        }
3746
3747        /**
3748         * Set an action from this notification's actions to be clickable with the content of
3749         * this notification. This action will no longer display separately from the
3750         * notification's content.
3751         *
3752         * <p>For notifications with multiple pages, child pages can also have content actions
3753         * set, although the list of available actions comes from the main notification and not
3754         * from the child page's notification.
3755         *
3756         * @param actionIndex The index of the action to hoist onto the current notification page.
3757         *                    If wearable actions were added to the main notification, this index
3758         *                    will apply to that list, otherwise it will apply to the regular
3759         *                    actions list.
3760         */
3761        public WearableExtender setContentAction(int actionIndex) {
3762            mContentActionIndex = actionIndex;
3763            return this;
3764        }
3765
3766        /**
3767         * Get the index of the notification action, if any, that was specified as being clickable
3768         * with the content of this notification. This action will no longer display separately
3769         * from the notification's content.
3770         *
3771         * <p>For notifications with multiple pages, child pages can also have content actions
3772         * set, although the list of available actions comes from the main notification and not
3773         * from the child page's notification.
3774         *
3775         * <p>If wearable specific actions were added to the main notification, this index will
3776         * apply to that list, otherwise it will apply to the regular actions list.
3777         *
3778         * @return the action index or {@link #UNSET_ACTION_INDEX} if no action was selected.
3779         */
3780        public int getContentAction() {
3781            return mContentActionIndex;
3782        }
3783
3784        /**
3785         * Set the gravity that this notification should have within the available viewport space.
3786         * Supported values include {@link android.view.Gravity#TOP},
3787         * {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}.
3788         * The default value is {@link android.view.Gravity#BOTTOM}.
3789         */
3790        public WearableExtender setGravity(int gravity) {
3791            mGravity = gravity;
3792            return this;
3793        }
3794
3795        /**
3796         * Get the gravity that this notification should have within the available viewport space.
3797         * Supported values include {@link android.view.Gravity#TOP},
3798         * {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}.
3799         * The default value is {@link android.view.Gravity#BOTTOM}.
3800         */
3801        public int getGravity() {
3802            return mGravity;
3803        }
3804
3805        /**
3806         * Set the custom size preset for the display of this notification out of the available
3807         * presets found in {@link android.app.Notification.WearableExtender}, e.g.
3808         * {@link #SIZE_LARGE}.
3809         * <p>Some custom size presets are only applicable for custom display notifications created
3810         * using {@link android.app.Notification.WearableExtender#setDisplayIntent}. Check the
3811         * documentation for the preset in question. See also
3812         * {@link #setCustomContentHeight} and {@link #getCustomSizePreset}.
3813         */
3814        public WearableExtender setCustomSizePreset(int sizePreset) {
3815            mCustomSizePreset = sizePreset;
3816            return this;
3817        }
3818
3819        /**
3820         * Get the custom size preset for the display of this notification out of the available
3821         * presets found in {@link android.app.Notification.WearableExtender}, e.g.
3822         * {@link #SIZE_LARGE}.
3823         * <p>Some custom size presets are only applicable for custom display notifications created
3824         * using {@link #setDisplayIntent}. Check the documentation for the preset in question.
3825         * See also {@link #setCustomContentHeight} and {@link #setCustomSizePreset}.
3826         */
3827        public int getCustomSizePreset() {
3828            return mCustomSizePreset;
3829        }
3830
3831        /**
3832         * Set the custom height in pixels for the display of this notification's content.
3833         * <p>This option is only available for custom display notifications created
3834         * using {@link android.app.Notification.WearableExtender#setDisplayIntent}. See also
3835         * {@link android.app.Notification.WearableExtender#setCustomSizePreset} and
3836         * {@link #getCustomContentHeight}.
3837         */
3838        public WearableExtender setCustomContentHeight(int height) {
3839            mCustomContentHeight = height;
3840            return this;
3841        }
3842
3843        /**
3844         * Get the custom height in pixels for the display of this notification's content.
3845         * <p>This option is only available for custom display notifications created
3846         * using {@link #setDisplayIntent}. See also {@link #setCustomSizePreset} and
3847         * {@link #setCustomContentHeight}.
3848         */
3849        public int getCustomContentHeight() {
3850            return mCustomContentHeight;
3851        }
3852
3853        /**
3854         * Set whether the scrolling position for the contents of this notification should start
3855         * at the bottom of the contents instead of the top when the contents are too long to
3856         * display within the screen.  Default is false (start scroll at the top).
3857         */
3858        public WearableExtender setStartScrollBottom(boolean startScrollBottom) {
3859            setFlag(FLAG_START_SCROLL_BOTTOM, startScrollBottom);
3860            return this;
3861        }
3862
3863        /**
3864         * Get whether the scrolling position for the contents of this notification should start
3865         * at the bottom of the contents instead of the top when the contents are too long to
3866         * display within the screen. Default is false (start scroll at the top).
3867         */
3868        public boolean getStartScrollBottom() {
3869            return (mFlags & FLAG_START_SCROLL_BOTTOM) != 0;
3870        }
3871
3872        /**
3873         * Set whether the content intent is available when the wearable device is not connected
3874         * to a companion device.  The user can still trigger this intent when the wearable device
3875         * is offline, but a visual hint will indicate that the content intent may not be available.
3876         * Defaults to true.
3877         */
3878        public WearableExtender setContentIntentAvailableOffline(
3879                boolean contentIntentAvailableOffline) {
3880            setFlag(FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE, contentIntentAvailableOffline);
3881            return this;
3882        }
3883
3884        /**
3885         * Get whether the content intent is available when the wearable device is not connected
3886         * to a companion device.  The user can still trigger this intent when the wearable device
3887         * is offline, but a visual hint will indicate that the content intent may not be available.
3888         * Defaults to true.
3889         */
3890        public boolean getContentIntentAvailableOffline() {
3891            return (mFlags & FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE) != 0;
3892        }
3893
3894        /**
3895         * Set a hint that this notification's icon should not be displayed.
3896         * @param hintHideIcon {@code true} to hide the icon, {@code false} otherwise.
3897         * @return this object for method chaining
3898         */
3899        public WearableExtender setHintHideIcon(boolean hintHideIcon) {
3900            setFlag(FLAG_HINT_HIDE_ICON, hintHideIcon);
3901            return this;
3902        }
3903
3904        /**
3905         * Get a hint that this notification's icon should not be displayed.
3906         * @return {@code true} if this icon should not be displayed, false otherwise.
3907         * The default value is {@code false} if this was never set.
3908         */
3909        public boolean getHintHideIcon() {
3910            return (mFlags & FLAG_HINT_HIDE_ICON) != 0;
3911        }
3912
3913        /**
3914         * Set a visual hint that only the background image of this notification should be
3915         * displayed, and other semantic content should be hidden. This hint is only applicable
3916         * to sub-pages added using {@link #addPage}.
3917         */
3918        public WearableExtender setHintShowBackgroundOnly(boolean hintShowBackgroundOnly) {
3919            setFlag(FLAG_HINT_SHOW_BACKGROUND_ONLY, hintShowBackgroundOnly);
3920            return this;
3921        }
3922
3923        /**
3924         * Get a visual hint that only the background image of this notification should be
3925         * displayed, and other semantic content should be hidden. This hint is only applicable
3926         * to sub-pages added using {@link android.app.Notification.WearableExtender#addPage}.
3927         */
3928        public boolean getHintShowBackgroundOnly() {
3929            return (mFlags & FLAG_HINT_SHOW_BACKGROUND_ONLY) != 0;
3930        }
3931
3932        private void setFlag(int mask, boolean value) {
3933            if (value) {
3934                mFlags |= mask;
3935            } else {
3936                mFlags &= ~mask;
3937            }
3938        }
3939    }
3940
3941    /**
3942     * Get an array of Notification objects from a parcelable array bundle field.
3943     * Update the bundle to have a typed array so fetches in the future don't need
3944     * to do an array copy.
3945     */
3946    private static Notification[] getNotificationArrayFromBundle(Bundle bundle, String key) {
3947        Parcelable[] array = bundle.getParcelableArray(key);
3948        if (array instanceof Notification[] || array == null) {
3949            return (Notification[]) array;
3950        }
3951        Notification[] typedArray = Arrays.copyOf(array, array.length,
3952                Notification[].class);
3953        bundle.putParcelableArray(key, typedArray);
3954        return typedArray;
3955    }
3956}
3957