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