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