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