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