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