Notification.java revision 5c2d84675b239bc04ae98c75526e5b81897ee183
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 com.android.internal.R;
20import com.android.internal.util.LegacyNotificationUtil;
21
22import android.annotation.IntDef;
23import android.content.Context;
24import android.content.Intent;
25import android.content.res.Resources;
26import android.graphics.Bitmap;
27import android.graphics.PorterDuff;
28import android.media.AudioManager;
29import android.net.Uri;
30import android.os.BadParcelableException;
31import android.os.Bundle;
32import android.os.Parcel;
33import android.os.Parcelable;
34import android.os.SystemClock;
35import android.os.UserHandle;
36import android.text.TextUtils;
37import android.util.Log;
38import android.util.TypedValue;
39import android.view.View;
40import android.widget.ProgressBar;
41import android.widget.RemoteViews;
42
43import java.lang.annotation.Retention;
44import java.lang.annotation.RetentionPolicy;
45import java.text.NumberFormat;
46import java.util.ArrayList;
47
48/**
49 * A class that represents how a persistent notification is to be presented to
50 * the user using the {@link android.app.NotificationManager}.
51 *
52 * <p>The {@link Notification.Builder Notification.Builder} has been added to make it
53 * easier to construct Notifications.</p>
54 *
55 * <div class="special reference">
56 * <h3>Developer Guides</h3>
57 * <p>For a guide to creating notifications, read the
58 * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a>
59 * developer guide.</p>
60 * </div>
61 */
62public class Notification implements Parcelable
63{
64    private static final String TAG = "Notification";
65
66    /**
67     * Use all default values (where applicable).
68     */
69    public static final int DEFAULT_ALL = ~0;
70
71    /**
72     * Use the default notification sound. This will ignore any given
73     * {@link #sound}.
74     *
75
76     * @see #defaults
77     */
78
79    public static final int DEFAULT_SOUND = 1;
80
81    /**
82     * Use the default notification vibrate. This will ignore any given
83     * {@link #vibrate}. Using phone vibration requires the
84     * {@link android.Manifest.permission#VIBRATE VIBRATE} permission.
85     *
86     * @see #defaults
87     */
88
89    public static final int DEFAULT_VIBRATE = 2;
90
91    /**
92     * Use the default notification lights. This will ignore the
93     * {@link #FLAG_SHOW_LIGHTS} bit, and {@link #ledARGB}, {@link #ledOffMS}, or
94     * {@link #ledOnMS}.
95     *
96     * @see #defaults
97     */
98
99    public static final int DEFAULT_LIGHTS = 4;
100
101    /**
102     * A timestamp related to this notification, in milliseconds since the epoch.
103     *
104     * Default value: {@link System#currentTimeMillis() Now}.
105     *
106     * Choose a timestamp that will be most relevant to the user. For most finite events, this
107     * corresponds to the time the event happened (or will happen, in the case of events that have
108     * yet to occur but about which the user is being informed). Indefinite events should be
109     * timestamped according to when the activity began.
110     *
111     * Some examples:
112     *
113     * <ul>
114     *   <li>Notification of a new chat message should be stamped when the message was received.</li>
115     *   <li>Notification of an ongoing file download (with a progress bar, for example) should be stamped when the download started.</li>
116     *   <li>Notification of a completed file download should be stamped when the download finished.</li>
117     *   <li>Notification of an upcoming meeting should be stamped with the time the meeting will begin (that is, in the future).</li>
118     *   <li>Notification of an ongoing stopwatch (increasing timer) should be stamped with the watch's start time.
119     *   <li>Notification of an ongoing countdown timer should be stamped with the timer's end time.
120     * </ul>
121     *
122     */
123    public long when;
124
125    /**
126     * The resource id of a drawable to use as the icon in the status bar.
127     * This is required; notifications with an invalid icon resource will not be shown.
128     */
129    public int icon;
130
131    /**
132     * If the icon in the status bar is to have more than one level, you can set this.  Otherwise,
133     * leave it at its default value of 0.
134     *
135     * @see android.widget.ImageView#setImageLevel
136     * @see android.graphics.drawable#setLevel
137     */
138    public int iconLevel;
139
140    /**
141     * The number of events that this notification represents. For example, in a new mail
142     * notification, this could be the number of unread messages.
143     *
144     * The system may or may not use this field to modify the appearance of the notification. For
145     * example, before {@link android.os.Build.VERSION_CODES#HONEYCOMB}, this number was
146     * superimposed over the icon in the status bar. Starting with
147     * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, the template used by
148     * {@link Notification.Builder} has displayed the number in the expanded notification view.
149     *
150     * If the number is 0 or negative, it is never shown.
151     */
152    public int number;
153
154    /**
155     * The intent to execute when the expanded status entry is clicked.  If
156     * this is an activity, it must include the
157     * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires
158     * that you take care of task management as described in the
159     * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back
160     * Stack</a> document.  In particular, make sure to read the notification section
161     * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html#HandlingNotifications">Handling
162     * Notifications</a> for the correct ways to launch an application from a
163     * notification.
164     */
165    public PendingIntent contentIntent;
166
167    /**
168     * The intent to execute when the notification is explicitly dismissed by the user, either with
169     * the "Clear All" button or by swiping it away individually.
170     *
171     * This probably shouldn't be launching an activity since several of those will be sent
172     * at the same time.
173     */
174    public PendingIntent deleteIntent;
175
176    /**
177     * An intent to launch instead of posting the notification to the status bar.
178     *
179     * @see Notification.Builder#setFullScreenIntent
180     */
181    public PendingIntent fullScreenIntent;
182
183    /**
184     * Text to scroll across the screen when this item is added to
185     * the status bar on large and smaller devices.
186     *
187     * @see #tickerView
188     */
189    public CharSequence tickerText;
190
191    /**
192     * The view to show as the ticker in the status bar when the notification
193     * is posted.
194     */
195    public RemoteViews tickerView;
196
197    /**
198     * The view that will represent this notification in the expanded status bar.
199     */
200    public RemoteViews contentView;
201
202    /**
203     * A large-format version of {@link #contentView}, giving the Notification an
204     * opportunity to show more detail. The system UI may choose to show this
205     * instead of the normal content view at its discretion.
206     */
207    public RemoteViews bigContentView;
208
209
210    /**
211     * @hide
212     * A medium-format version of {@link #contentView}, giving the Notification an
213     * opportunity to add action buttons to contentView. The system UI may
214     * choose to show this as a popup notification at its discretion.
215     */
216    public RemoteViews headsUpContentView;
217
218    /**
219     * The bitmap that may escape the bounds of the panel and bar.
220     */
221    public Bitmap largeIcon;
222
223    /**
224     * The sound to play.
225     *
226     * <p>
227     * To play the default notification sound, see {@link #defaults}.
228     * </p>
229     */
230    public Uri sound;
231
232    /**
233     * Use this constant as the value for audioStreamType to request that
234     * the default stream type for notifications be used.  Currently the
235     * default stream type is {@link AudioManager#STREAM_NOTIFICATION}.
236     */
237    public static final int STREAM_DEFAULT = -1;
238
239    /**
240     * The audio stream type to use when playing the sound.
241     * Should be one of the STREAM_ constants from
242     * {@link android.media.AudioManager}.
243     */
244    public int audioStreamType = STREAM_DEFAULT;
245
246    /**
247     * The pattern with which to vibrate.
248     *
249     * <p>
250     * To vibrate the default pattern, see {@link #defaults}.
251     * </p>
252     *
253     * @see android.os.Vibrator#vibrate(long[],int)
254     */
255    public long[] vibrate;
256
257    /**
258     * The color of the led.  The hardware will do its best approximation.
259     *
260     * @see #FLAG_SHOW_LIGHTS
261     * @see #flags
262     */
263    public int ledARGB;
264
265    /**
266     * The number of milliseconds for the LED to be on while it's flashing.
267     * The hardware will do its best approximation.
268     *
269     * @see #FLAG_SHOW_LIGHTS
270     * @see #flags
271     */
272    public int ledOnMS;
273
274    /**
275     * The number of milliseconds for the LED to be off while it's flashing.
276     * The hardware will do its best approximation.
277     *
278     * @see #FLAG_SHOW_LIGHTS
279     * @see #flags
280     */
281    public int ledOffMS;
282
283    /**
284     * Specifies which values should be taken from the defaults.
285     * <p>
286     * To set, OR the desired from {@link #DEFAULT_SOUND},
287     * {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}. For all default
288     * values, use {@link #DEFAULT_ALL}.
289     * </p>
290     */
291    public int defaults;
292
293    /**
294     * Bit to be bitwise-ored into the {@link #flags} field that should be
295     * set if you want the LED on for this notification.
296     * <ul>
297     * <li>To turn the LED off, pass 0 in the alpha channel for colorARGB
298     *      or 0 for both ledOnMS and ledOffMS.</li>
299     * <li>To turn the LED on, pass 1 for ledOnMS and 0 for ledOffMS.</li>
300     * <li>To flash the LED, pass the number of milliseconds that it should
301     *      be on and off to ledOnMS and ledOffMS.</li>
302     * </ul>
303     * <p>
304     * Since hardware varies, you are not guaranteed that any of the values
305     * you pass are honored exactly.  Use the system defaults (TODO) if possible
306     * because they will be set to values that work on any given hardware.
307     * <p>
308     * The alpha channel must be set for forward compatibility.
309     *
310     */
311    public static final int FLAG_SHOW_LIGHTS        = 0x00000001;
312
313    /**
314     * Bit to be bitwise-ored into the {@link #flags} field that should be
315     * set if this notification is in reference to something that is ongoing,
316     * like a phone call.  It should not be set if this notification is in
317     * reference to something that happened at a particular point in time,
318     * like a missed phone call.
319     */
320    public static final int FLAG_ONGOING_EVENT      = 0x00000002;
321
322    /**
323     * Bit to be bitwise-ored into the {@link #flags} field that if set,
324     * the audio will be repeated until the notification is
325     * cancelled or the notification window is opened.
326     */
327    public static final int FLAG_INSISTENT          = 0x00000004;
328
329    /**
330     * Bit to be bitwise-ored into the {@link #flags} field that should be
331     * set if you want the sound and/or vibration play each time the
332     * notification is sent, even if it has not been canceled before that.
333     */
334    public static final int FLAG_ONLY_ALERT_ONCE    = 0x00000008;
335
336    /**
337     * Bit to be bitwise-ored into the {@link #flags} field that should be
338     * set if the notification should be canceled when it is clicked by the
339     * user.
340
341     */
342    public static final int FLAG_AUTO_CANCEL        = 0x00000010;
343
344    /**
345     * Bit to be bitwise-ored into the {@link #flags} field that should be
346     * set if the notification should not be canceled when the user clicks
347     * the Clear all button.
348     */
349    public static final int FLAG_NO_CLEAR           = 0x00000020;
350
351    /**
352     * Bit to be bitwise-ored into the {@link #flags} field that should be
353     * set if this notification represents a currently running service.  This
354     * will normally be set for you by {@link Service#startForeground}.
355     */
356    public static final int FLAG_FOREGROUND_SERVICE = 0x00000040;
357
358    /**
359     * Obsolete flag indicating high-priority notifications; use the priority field instead.
360     *
361     * @deprecated Use {@link #priority} with a positive value.
362     */
363    public static final int FLAG_HIGH_PRIORITY      = 0x00000080;
364
365    /**
366     * Bit to be bitswise-ored into the {@link #flags} field that should be
367     * set if this notification is relevant to the current device only
368     * and it is not recommended that it bridge to other devices.
369     */
370    public static final int FLAG_LOCAL_ONLY         = 0x00000100;
371
372    public int flags;
373
374    /** @hide */
375    @IntDef({PRIORITY_DEFAULT,PRIORITY_LOW,PRIORITY_MIN,PRIORITY_HIGH,PRIORITY_MAX})
376    @Retention(RetentionPolicy.SOURCE)
377    public @interface Priority {}
378
379    /**
380     * Default notification {@link #priority}. If your application does not prioritize its own
381     * notifications, use this value for all notifications.
382     */
383    public static final int PRIORITY_DEFAULT = 0;
384
385    /**
386     * Lower {@link #priority}, for items that are less important. The UI may choose to show these
387     * items smaller, or at a different position in the list, compared with your app's
388     * {@link #PRIORITY_DEFAULT} items.
389     */
390    public static final int PRIORITY_LOW = -1;
391
392    /**
393     * Lowest {@link #priority}; these items might not be shown to the user except under special
394     * circumstances, such as detailed notification logs.
395     */
396    public static final int PRIORITY_MIN = -2;
397
398    /**
399     * Higher {@link #priority}, for more important notifications or alerts. The UI may choose to
400     * show these items larger, or at a different position in notification lists, compared with
401     * your app's {@link #PRIORITY_DEFAULT} items.
402     */
403    public static final int PRIORITY_HIGH = 1;
404
405    /**
406     * Highest {@link #priority}, for your application's most important items that require the
407     * user's prompt attention or input.
408     */
409    public static final int PRIORITY_MAX = 2;
410
411    /**
412     * Relative priority for this notification.
413     *
414     * Priority is an indication of how much of the user's valuable attention should be consumed by
415     * this notification. Low-priority notifications may be hidden from the user in certain
416     * situations, while the user might be interrupted for a higher-priority notification. The
417     * system will make a determination about how to interpret this priority when presenting
418     * the notification.
419     */
420    @Priority
421    public int priority;
422
423
424    /**
425     * Sphere of visibility of this notification, which affects how and when the SystemUI reveals
426     * the notification's presence and contents in untrusted situations (namely, on the secure
427     * lockscreen).
428     *
429     * The default level, {@link #VISIBILITY_PRIVATE}, behaves exactly as notifications have always
430     * done on Android: The notification's {@link #icon} and {@link #tickerText} (if available) are
431     * shown in all situations, but the contents are only available if the device is unlocked for
432     * the appropriate user.
433     *
434     * A more permissive policy can be expressed by {@link #VISIBILITY_PUBLIC}; such a notification
435     * can be read even in an "insecure" context (that is, above a secure lockscreen).
436     * To modify the public version of this notification—for example, to redact some portions—see
437     * {@link Builder#setPublicVersion(Notification)}.
438     *
439     * Finally, a notification can be made {@link #VISIBILITY_SECRET}, which will suppress its icon
440     * and ticker until the user has bypassed the lockscreen.
441     */
442    public int visibility;
443
444    public static final int VISIBILITY_PUBLIC = 1;
445    public static final int VISIBILITY_PRIVATE = 0;
446    public static final int VISIBILITY_SECRET = -1;
447
448    /**
449     * Notification category: incoming call (voice or video) or similar synchronous communication request.
450     */
451    public static final String CATEGORY_CALL = "call";
452
453    /**
454     * Notification category: incoming direct message (SMS, instant message, etc.).
455     */
456    public static final String CATEGORY_MESSAGE = "msg";
457
458    /**
459     * Notification category: asynchronous bulk message (email).
460     */
461    public static final String CATEGORY_EMAIL = "email";
462
463    /**
464     * Notification category: calendar event.
465     */
466    public static final String CATEGORY_EVENT = "event";
467
468    /**
469     * Notification category: promotion or advertisement.
470     */
471    public static final String CATEGORY_PROMO = "promo";
472
473    /**
474     * Notification category: alarm or timer.
475     */
476    public static final String CATEGORY_ALARM = "alarm";
477
478    /**
479     * Notification category: progress of a long-running background operation.
480     */
481    public static final String CATEGORY_PROGRESS = "progress";
482
483    /**
484     * Notification category: social network or sharing update.
485     */
486    public static final String CATEGORY_SOCIAL = "social";
487
488    /**
489     * Notification category: error in background operation or authentication status.
490     */
491    public static final String CATEGORY_ERROR = "err";
492
493    /**
494     * Notification category: media transport control for playback.
495     */
496    public static final String CATEGORY_TRANSPORT = "transport";
497
498    /**
499     * Notification category: system or device status update.  Reserved for system use.
500     */
501    public static final String CATEGORY_SYSTEM = "sys";
502
503    /**
504     * Notification category: indication of running background service.
505     */
506    public static final String CATEGORY_SERVICE = "service";
507
508    /**
509     * Notification category: a specific, timely recommendation for a single thing.
510     * For example, a news app might want to recommend a news story it believes the user will
511     * want to read next.
512     */
513    public static final String CATEGORY_RECOMMENDATION = "recommendation";
514
515    /**
516     * Notification category: ongoing information about device or contextual status.
517     */
518    public static final String CATEGORY_STATUS = "status";
519
520    /**
521     * One of the predefined notification categories (see the <code>CATEGORY_*</code> constants)
522     * that best describes this Notification.  May be used by the system for ranking and filtering.
523     */
524    public String category;
525
526    /**
527     * Additional semantic data to be carried around with this Notification.
528     * <p>
529     * The extras keys defined here are intended to capture the original inputs to {@link Builder}
530     * APIs, and are intended to be used by
531     * {@link android.service.notification.NotificationListenerService} implementations to extract
532     * detailed information from notification objects.
533     */
534    public Bundle extras = new Bundle();
535
536    /**
537     * {@link #extras} key: this is the title of the notification,
538     * as supplied to {@link Builder#setContentTitle(CharSequence)}.
539     */
540    public static final String EXTRA_TITLE = "android.title";
541
542    /**
543     * {@link #extras} key: this is the title of the notification when shown in expanded form,
544     * e.g. as supplied to {@link BigTextStyle#setBigContentTitle(CharSequence)}.
545     */
546    public static final String EXTRA_TITLE_BIG = EXTRA_TITLE + ".big";
547
548    /**
549     * {@link #extras} key: this is the main text payload, as supplied to
550     * {@link Builder#setContentText(CharSequence)}.
551     */
552    public static final String EXTRA_TEXT = "android.text";
553
554    /**
555     * {@link #extras} key: this is a third line of text, as supplied to
556     * {@link Builder#setSubText(CharSequence)}.
557     */
558    public static final String EXTRA_SUB_TEXT = "android.subText";
559
560    /**
561     * {@link #extras} key: this is a small piece of additional text as supplied to
562     * {@link Builder#setContentInfo(CharSequence)}.
563     */
564    public static final String EXTRA_INFO_TEXT = "android.infoText";
565
566    /**
567     * {@link #extras} key: this is a line of summary information intended to be shown
568     * alongside expanded notifications, as supplied to (e.g.)
569     * {@link BigTextStyle#setSummaryText(CharSequence)}.
570     */
571    public static final String EXTRA_SUMMARY_TEXT = "android.summaryText";
572
573    /**
574     * {@link #extras} key: this is the resource ID of the notification's main small icon, as
575     * supplied to {@link Builder#setSmallIcon(int)}.
576     */
577    public static final String EXTRA_SMALL_ICON = "android.icon";
578
579    /**
580     * {@link #extras} key: this is a bitmap to be used instead of the small icon when showing the
581     * notification payload, as
582     * supplied to {@link Builder#setLargeIcon(android.graphics.Bitmap)}.
583     */
584    public static final String EXTRA_LARGE_ICON = "android.largeIcon";
585
586    /**
587     * {@link #extras} key: this is a bitmap to be used instead of the one from
588     * {@link Builder#setLargeIcon(android.graphics.Bitmap)} when the notification is
589     * shown in its expanded form, as supplied to
590     * {@link BigPictureStyle#bigLargeIcon(android.graphics.Bitmap)}.
591     */
592    public static final String EXTRA_LARGE_ICON_BIG = EXTRA_LARGE_ICON + ".big";
593
594    /**
595     * {@link #extras} key: this is the progress value supplied to
596     * {@link Builder#setProgress(int, int, boolean)}.
597     */
598    public static final String EXTRA_PROGRESS = "android.progress";
599
600    /**
601     * {@link #extras} key: this is the maximum value supplied to
602     * {@link Builder#setProgress(int, int, boolean)}.
603     */
604    public static final String EXTRA_PROGRESS_MAX = "android.progressMax";
605
606    /**
607     * {@link #extras} key: whether the progress bar is indeterminate, supplied to
608     * {@link Builder#setProgress(int, int, boolean)}.
609     */
610    public static final String EXTRA_PROGRESS_INDETERMINATE = "android.progressIndeterminate";
611
612    /**
613     * {@link #extras} key: whether {@link #when} should be shown as a count-up timer (specifically
614     * a {@link android.widget.Chronometer}) instead of a timestamp, as supplied to
615     * {@link Builder#setUsesChronometer(boolean)}.
616     */
617    public static final String EXTRA_SHOW_CHRONOMETER = "android.showChronometer";
618
619    /**
620     * {@link #extras} key: whether {@link #when} should be shown,
621     * as supplied to {@link Builder#setShowWhen(boolean)}.
622     */
623    public static final String EXTRA_SHOW_WHEN = "android.showWhen";
624
625    /**
626     * {@link #extras} key: this is a bitmap to be shown in {@link BigPictureStyle} expanded
627     * notifications, supplied to {@link BigPictureStyle#bigPicture(android.graphics.Bitmap)}.
628     */
629    public static final String EXTRA_PICTURE = "android.picture";
630
631    /**
632     * {@link #extras} key: An array of CharSequences to show in {@link InboxStyle} expanded
633     * notifications, each of which was supplied to {@link InboxStyle#addLine(CharSequence)}.
634     */
635    public static final String EXTRA_TEXT_LINES = "android.textLines";
636    public static final String EXTRA_TEMPLATE = "android.template";
637
638    /**
639     * {@link #extras} key: An array of people that this notification relates to, specified
640     * by contacts provider contact URI.
641     */
642    public static final String EXTRA_PEOPLE = "android.people";
643
644    /**
645     * @hide
646     * Extra added by NotificationManagerService to indicate whether a NotificationScorer
647     * modified the Notifications's score.
648     */
649    public static final String EXTRA_SCORE_MODIFIED = "android.scoreModified";
650
651    /**
652     * Not used.
653     * @hide
654     */
655    public static final String EXTRA_AS_HEADS_UP = "headsup";
656
657    /**
658     * Allow certain system-generated notifications to appear before the device is provisioned.
659     * Only available to notifications coming from the android package.
660     * @hide
661     */
662    public static final String EXTRA_ALLOW_DURING_SETUP = "android.allowDuringSetup";
663
664    /**
665     * Value for {@link #EXTRA_AS_HEADS_UP}.
666     * @hide
667     */
668    public static final int HEADS_UP_NEVER = 0;
669
670    /**
671     * Default value for {@link #EXTRA_AS_HEADS_UP}.
672     * @hide
673     */
674    public static final int HEADS_UP_ALLOWED = 1;
675
676    /**
677     * Value for {@link #EXTRA_AS_HEADS_UP}.
678     * @hide
679     */
680    public static final int HEADS_UP_REQUESTED = 2;
681
682    /**
683     * Structure to encapsulate a named action that can be shown as part of this notification.
684     * It must include an icon, a label, and a {@link PendingIntent} to be fired when the action is
685     * selected by the user.
686     * <p>
687     * Apps should use {@link Builder#addAction(int, CharSequence, PendingIntent)} to create and
688     * attach actions.
689     */
690    public static class Action implements Parcelable {
691        /**
692         * Small icon representing the action.
693         */
694        public int icon;
695        /**
696         * Title of the action.
697         */
698        public CharSequence title;
699        /**
700         * Intent to send when the user invokes this action. May be null, in which case the action
701         * may be rendered in a disabled presentation by the system UI.
702         */
703        public PendingIntent actionIntent;
704
705        private Action() { }
706        private Action(Parcel in) {
707            icon = in.readInt();
708            title = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
709            if (in.readInt() == 1) {
710                actionIntent = PendingIntent.CREATOR.createFromParcel(in);
711            }
712        }
713        /**
714         * Use {@link Builder#addAction(int, CharSequence, PendingIntent)}.
715         */
716        public Action(int icon, CharSequence title, PendingIntent intent) {
717            this.icon = icon;
718            this.title = title;
719            this.actionIntent = intent;
720        }
721
722        @Override
723        public Action clone() {
724            return new Action(
725                this.icon,
726                this.title,
727                this.actionIntent // safe to alias
728            );
729        }
730        @Override
731        public int describeContents() {
732            return 0;
733        }
734        @Override
735        public void writeToParcel(Parcel out, int flags) {
736            out.writeInt(icon);
737            TextUtils.writeToParcel(title, out, flags);
738            if (actionIntent != null) {
739                out.writeInt(1);
740                actionIntent.writeToParcel(out, flags);
741            } else {
742                out.writeInt(0);
743            }
744        }
745        public static final Parcelable.Creator<Action> CREATOR
746        = new Parcelable.Creator<Action>() {
747            public Action createFromParcel(Parcel in) {
748                return new Action(in);
749            }
750            public Action[] newArray(int size) {
751                return new Action[size];
752            }
753        };
754    }
755
756    /**
757     * Array of all {@link Action} structures attached to this notification by
758     * {@link Builder#addAction(int, CharSequence, PendingIntent)}. Mostly useful for instances of
759     * {@link android.service.notification.NotificationListenerService} that provide an alternative
760     * interface for invoking actions.
761     */
762    public Action[] actions;
763
764    /**
765     * Replacement version of this notification whose content will be shown
766     * in an insecure context such as atop a secure keyguard. See {@link #visibility}
767     * and {@link #VISIBILITY_PUBLIC}.
768     */
769    public Notification publicVersion;
770
771    /**
772     * Constructs a Notification object with default values.
773     * You might want to consider using {@link Builder} instead.
774     */
775    public Notification()
776    {
777        this.when = System.currentTimeMillis();
778        this.priority = PRIORITY_DEFAULT;
779    }
780
781    /**
782     * @hide
783     */
784    public Notification(Context context, int icon, CharSequence tickerText, long when,
785            CharSequence contentTitle, CharSequence contentText, Intent contentIntent)
786    {
787        this.when = when;
788        this.icon = icon;
789        this.tickerText = tickerText;
790        setLatestEventInfo(context, contentTitle, contentText,
791                PendingIntent.getActivity(context, 0, contentIntent, 0));
792    }
793
794    /**
795     * Constructs a Notification object with the information needed to
796     * have a status bar icon without the standard expanded view.
797     *
798     * @param icon          The resource id of the icon to put in the status bar.
799     * @param tickerText    The text that flows by in the status bar when the notification first
800     *                      activates.
801     * @param when          The time to show in the time field.  In the System.currentTimeMillis
802     *                      timebase.
803     *
804     * @deprecated Use {@link Builder} instead.
805     */
806    @Deprecated
807    public Notification(int icon, CharSequence tickerText, long when)
808    {
809        this.icon = icon;
810        this.tickerText = tickerText;
811        this.when = when;
812    }
813
814    /**
815     * Unflatten the notification from a parcel.
816     */
817    public Notification(Parcel parcel)
818    {
819        int version = parcel.readInt();
820
821        when = parcel.readLong();
822        icon = parcel.readInt();
823        number = parcel.readInt();
824        if (parcel.readInt() != 0) {
825            contentIntent = PendingIntent.CREATOR.createFromParcel(parcel);
826        }
827        if (parcel.readInt() != 0) {
828            deleteIntent = PendingIntent.CREATOR.createFromParcel(parcel);
829        }
830        if (parcel.readInt() != 0) {
831            tickerText = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(parcel);
832        }
833        if (parcel.readInt() != 0) {
834            tickerView = RemoteViews.CREATOR.createFromParcel(parcel);
835        }
836        if (parcel.readInt() != 0) {
837            contentView = RemoteViews.CREATOR.createFromParcel(parcel);
838        }
839        if (parcel.readInt() != 0) {
840            largeIcon = Bitmap.CREATOR.createFromParcel(parcel);
841        }
842        defaults = parcel.readInt();
843        flags = parcel.readInt();
844        if (parcel.readInt() != 0) {
845            sound = Uri.CREATOR.createFromParcel(parcel);
846        }
847
848        audioStreamType = parcel.readInt();
849        vibrate = parcel.createLongArray();
850        ledARGB = parcel.readInt();
851        ledOnMS = parcel.readInt();
852        ledOffMS = parcel.readInt();
853        iconLevel = parcel.readInt();
854
855        if (parcel.readInt() != 0) {
856            fullScreenIntent = PendingIntent.CREATOR.createFromParcel(parcel);
857        }
858
859        priority = parcel.readInt();
860
861        category = parcel.readString();
862
863        extras = parcel.readBundle(); // may be null
864
865        actions = parcel.createTypedArray(Action.CREATOR); // may be null
866
867        if (parcel.readInt() != 0) {
868            bigContentView = RemoteViews.CREATOR.createFromParcel(parcel);
869        }
870
871        if (parcel.readInt() != 0) {
872            headsUpContentView = RemoteViews.CREATOR.createFromParcel(parcel);
873        }
874
875        visibility = parcel.readInt();
876
877        if (parcel.readInt() != 0) {
878            publicVersion = Notification.CREATOR.createFromParcel(parcel);
879        }
880    }
881
882    @Override
883    public Notification clone() {
884        Notification that = new Notification();
885        cloneInto(that, true);
886        return that;
887    }
888
889    /**
890     * Copy all (or if heavy is false, all except Bitmaps and RemoteViews) members
891     * of this into that.
892     * @hide
893     */
894    public void cloneInto(Notification that, boolean heavy) {
895        that.when = this.when;
896        that.icon = this.icon;
897        that.number = this.number;
898
899        // PendingIntents are global, so there's no reason (or way) to clone them.
900        that.contentIntent = this.contentIntent;
901        that.deleteIntent = this.deleteIntent;
902        that.fullScreenIntent = this.fullScreenIntent;
903
904        if (this.tickerText != null) {
905            that.tickerText = this.tickerText.toString();
906        }
907        if (heavy && this.tickerView != null) {
908            that.tickerView = this.tickerView.clone();
909        }
910        if (heavy && this.contentView != null) {
911            that.contentView = this.contentView.clone();
912        }
913        if (heavy && this.largeIcon != null) {
914            that.largeIcon = Bitmap.createBitmap(this.largeIcon);
915        }
916        that.iconLevel = this.iconLevel;
917        that.sound = this.sound; // android.net.Uri is immutable
918        that.audioStreamType = this.audioStreamType;
919
920        final long[] vibrate = this.vibrate;
921        if (vibrate != null) {
922            final int N = vibrate.length;
923            final long[] vib = that.vibrate = new long[N];
924            System.arraycopy(vibrate, 0, vib, 0, N);
925        }
926
927        that.ledARGB = this.ledARGB;
928        that.ledOnMS = this.ledOnMS;
929        that.ledOffMS = this.ledOffMS;
930        that.defaults = this.defaults;
931
932        that.flags = this.flags;
933
934        that.priority = this.priority;
935
936        that.category = this.category;
937
938        if (this.extras != null) {
939            try {
940                that.extras = new Bundle(this.extras);
941                // will unparcel
942                that.extras.size();
943            } catch (BadParcelableException e) {
944                Log.e(TAG, "could not unparcel extras from notification: " + this, e);
945                that.extras = null;
946            }
947        }
948
949        if (this.actions != null) {
950            that.actions = new Action[this.actions.length];
951            for(int i=0; i<this.actions.length; i++) {
952                that.actions[i] = this.actions[i].clone();
953            }
954        }
955
956        if (heavy && this.bigContentView != null) {
957            that.bigContentView = this.bigContentView.clone();
958        }
959
960        if (heavy && this.headsUpContentView != null) {
961            that.headsUpContentView = this.headsUpContentView.clone();
962        }
963
964        that.visibility = this.visibility;
965
966        if (this.publicVersion != null) {
967            that.publicVersion = new Notification();
968            this.publicVersion.cloneInto(that.publicVersion, heavy);
969        }
970
971        if (!heavy) {
972            that.lightenPayload(); // will clean out extras
973        }
974    }
975
976    /**
977     * Removes heavyweight parts of the Notification object for archival or for sending to
978     * listeners when the full contents are not necessary.
979     * @hide
980     */
981    public final void lightenPayload() {
982        tickerView = null;
983        contentView = null;
984        bigContentView = null;
985        headsUpContentView = null;
986        largeIcon = null;
987        if (extras != null) {
988            extras.remove(Notification.EXTRA_LARGE_ICON);
989            extras.remove(Notification.EXTRA_LARGE_ICON_BIG);
990            extras.remove(Notification.EXTRA_PICTURE);
991        }
992    }
993
994    /**
995     * Make sure this CharSequence is safe to put into a bundle, which basically
996     * means it had better not be some custom Parcelable implementation.
997     * @hide
998     */
999    public static CharSequence safeCharSequence(CharSequence cs) {
1000        if (cs instanceof Parcelable) {
1001            Log.e(TAG, "warning: " + cs.getClass().getCanonicalName()
1002                    + " instance is a custom Parcelable and not allowed in Notification");
1003            return cs.toString();
1004        }
1005
1006        return cs;
1007    }
1008
1009    public int describeContents() {
1010        return 0;
1011    }
1012
1013    /**
1014     * Flatten this notification from a parcel.
1015     */
1016    public void writeToParcel(Parcel parcel, int flags)
1017    {
1018        parcel.writeInt(1);
1019
1020        parcel.writeLong(when);
1021        parcel.writeInt(icon);
1022        parcel.writeInt(number);
1023        if (contentIntent != null) {
1024            parcel.writeInt(1);
1025            contentIntent.writeToParcel(parcel, 0);
1026        } else {
1027            parcel.writeInt(0);
1028        }
1029        if (deleteIntent != null) {
1030            parcel.writeInt(1);
1031            deleteIntent.writeToParcel(parcel, 0);
1032        } else {
1033            parcel.writeInt(0);
1034        }
1035        if (tickerText != null) {
1036            parcel.writeInt(1);
1037            TextUtils.writeToParcel(tickerText, parcel, flags);
1038        } else {
1039            parcel.writeInt(0);
1040        }
1041        if (tickerView != null) {
1042            parcel.writeInt(1);
1043            tickerView.writeToParcel(parcel, 0);
1044        } else {
1045            parcel.writeInt(0);
1046        }
1047        if (contentView != null) {
1048            parcel.writeInt(1);
1049            contentView.writeToParcel(parcel, 0);
1050        } else {
1051            parcel.writeInt(0);
1052        }
1053        if (largeIcon != null) {
1054            parcel.writeInt(1);
1055            largeIcon.writeToParcel(parcel, 0);
1056        } else {
1057            parcel.writeInt(0);
1058        }
1059
1060        parcel.writeInt(defaults);
1061        parcel.writeInt(this.flags);
1062
1063        if (sound != null) {
1064            parcel.writeInt(1);
1065            sound.writeToParcel(parcel, 0);
1066        } else {
1067            parcel.writeInt(0);
1068        }
1069        parcel.writeInt(audioStreamType);
1070        parcel.writeLongArray(vibrate);
1071        parcel.writeInt(ledARGB);
1072        parcel.writeInt(ledOnMS);
1073        parcel.writeInt(ledOffMS);
1074        parcel.writeInt(iconLevel);
1075
1076        if (fullScreenIntent != null) {
1077            parcel.writeInt(1);
1078            fullScreenIntent.writeToParcel(parcel, 0);
1079        } else {
1080            parcel.writeInt(0);
1081        }
1082
1083        parcel.writeInt(priority);
1084
1085        parcel.writeString(category);
1086
1087        parcel.writeBundle(extras); // null ok
1088
1089        parcel.writeTypedArray(actions, 0); // null ok
1090
1091        if (bigContentView != null) {
1092            parcel.writeInt(1);
1093            bigContentView.writeToParcel(parcel, 0);
1094        } else {
1095            parcel.writeInt(0);
1096        }
1097
1098        if (headsUpContentView != null) {
1099            parcel.writeInt(1);
1100            headsUpContentView.writeToParcel(parcel, 0);
1101        } else {
1102            parcel.writeInt(0);
1103        }
1104
1105        parcel.writeInt(visibility);
1106
1107        if (publicVersion != null) {
1108            parcel.writeInt(1);
1109            publicVersion.writeToParcel(parcel, 0);
1110        } else {
1111            parcel.writeInt(0);
1112        }
1113    }
1114
1115    /**
1116     * Parcelable.Creator that instantiates Notification objects
1117     */
1118    public static final Parcelable.Creator<Notification> CREATOR
1119            = new Parcelable.Creator<Notification>()
1120    {
1121        public Notification createFromParcel(Parcel parcel)
1122        {
1123            return new Notification(parcel);
1124        }
1125
1126        public Notification[] newArray(int size)
1127        {
1128            return new Notification[size];
1129        }
1130    };
1131
1132    /**
1133     * Sets the {@link #contentView} field to be a view with the standard "Latest Event"
1134     * layout.
1135     *
1136     * <p>Uses the {@link #icon} and {@link #when} fields to set the icon and time fields
1137     * in the view.</p>
1138     * @param context       The context for your application / activity.
1139     * @param contentTitle The title that goes in the expanded entry.
1140     * @param contentText  The text that goes in the expanded entry.
1141     * @param contentIntent The intent to launch when the user clicks the expanded notification.
1142     * If this is an activity, it must include the
1143     * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires
1144     * that you take care of task management as described in the
1145     * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back
1146     * Stack</a> document.
1147     *
1148     * @deprecated Use {@link Builder} instead.
1149     */
1150    @Deprecated
1151    public void setLatestEventInfo(Context context,
1152            CharSequence contentTitle, CharSequence contentText, PendingIntent contentIntent) {
1153        Notification.Builder builder = new Notification.Builder(context);
1154
1155        // First, ensure that key pieces of information that may have been set directly
1156        // are preserved
1157        builder.setWhen(this.when);
1158        builder.setSmallIcon(this.icon);
1159        builder.setPriority(this.priority);
1160        builder.setTicker(this.tickerText);
1161        builder.setNumber(this.number);
1162        builder.mFlags = this.flags;
1163        builder.setSound(this.sound, this.audioStreamType);
1164        builder.setDefaults(this.defaults);
1165        builder.setVibrate(this.vibrate);
1166
1167        // now apply the latestEventInfo fields
1168        if (contentTitle != null) {
1169            builder.setContentTitle(contentTitle);
1170        }
1171        if (contentText != null) {
1172            builder.setContentText(contentText);
1173        }
1174        builder.setContentIntent(contentIntent);
1175        builder.buildInto(this);
1176    }
1177
1178    @Override
1179    public String toString() {
1180        StringBuilder sb = new StringBuilder();
1181        sb.append("Notification(pri=");
1182        sb.append(priority);
1183        sb.append(" contentView=");
1184        if (contentView != null) {
1185            sb.append(contentView.getPackage());
1186            sb.append("/0x");
1187            sb.append(Integer.toHexString(contentView.getLayoutId()));
1188        } else {
1189            sb.append("null");
1190        }
1191        // TODO(dsandler): defaults take precedence over local values, so reorder the branches below
1192        sb.append(" vibrate=");
1193        if ((this.defaults & DEFAULT_VIBRATE) != 0) {
1194            sb.append("default");
1195        } else if (this.vibrate != null) {
1196            int N = this.vibrate.length-1;
1197            sb.append("[");
1198            for (int i=0; i<N; i++) {
1199                sb.append(this.vibrate[i]);
1200                sb.append(',');
1201            }
1202            if (N != -1) {
1203                sb.append(this.vibrate[N]);
1204            }
1205            sb.append("]");
1206        } else {
1207            sb.append("null");
1208        }
1209        sb.append(" sound=");
1210        if ((this.defaults & DEFAULT_SOUND) != 0) {
1211            sb.append("default");
1212        } else if (this.sound != null) {
1213            sb.append(this.sound.toString());
1214        } else {
1215            sb.append("null");
1216        }
1217        sb.append(" defaults=0x");
1218        sb.append(Integer.toHexString(this.defaults));
1219        sb.append(" flags=0x");
1220        sb.append(Integer.toHexString(this.flags));
1221        sb.append(" category="); sb.append(this.category);
1222        if (actions != null) {
1223            sb.append(" ");
1224            sb.append(actions.length);
1225            sb.append(" action");
1226            if (actions.length > 1) sb.append("s");
1227        }
1228        sb.append(")");
1229        return sb.toString();
1230    }
1231
1232    /** {@hide} */
1233    public void setUser(UserHandle user) {
1234        if (user.getIdentifier() == UserHandle.USER_ALL) {
1235            user = UserHandle.OWNER;
1236        }
1237        if (tickerView != null) {
1238            tickerView.setUser(user);
1239        }
1240        if (contentView != null) {
1241            contentView.setUser(user);
1242        }
1243        if (bigContentView != null) {
1244            bigContentView.setUser(user);
1245        }
1246        if (headsUpContentView != null) {
1247            headsUpContentView.setUser(user);
1248        }
1249    }
1250
1251    /**
1252     * Builder class for {@link Notification} objects.
1253     *
1254     * Provides a convenient way to set the various fields of a {@link Notification} and generate
1255     * content views using the platform's notification layout template. If your app supports
1256     * versions of Android as old as API level 4, you can instead use
1257     * {@link android.support.v4.app.NotificationCompat.Builder NotificationCompat.Builder},
1258     * available in the <a href="{@docRoot}tools/extras/support-library.html">Android Support
1259     * library</a>.
1260     *
1261     * <p>Example:
1262     *
1263     * <pre class="prettyprint">
1264     * Notification noti = new Notification.Builder(mContext)
1265     *         .setContentTitle(&quot;New mail from &quot; + sender.toString())
1266     *         .setContentText(subject)
1267     *         .setSmallIcon(R.drawable.new_mail)
1268     *         .setLargeIcon(aBitmap)
1269     *         .build();
1270     * </pre>
1271     */
1272    public static class Builder {
1273        private static final int MAX_ACTION_BUTTONS = 3;
1274
1275        private Context mContext;
1276
1277        private long mWhen;
1278        private int mSmallIcon;
1279        private int mSmallIconLevel;
1280        private int mNumber;
1281        private CharSequence mContentTitle;
1282        private CharSequence mContentText;
1283        private CharSequence mContentInfo;
1284        private CharSequence mSubText;
1285        private PendingIntent mContentIntent;
1286        private RemoteViews mContentView;
1287        private PendingIntent mDeleteIntent;
1288        private PendingIntent mFullScreenIntent;
1289        private CharSequence mTickerText;
1290        private RemoteViews mTickerView;
1291        private Bitmap mLargeIcon;
1292        private Uri mSound;
1293        private int mAudioStreamType;
1294        private long[] mVibrate;
1295        private int mLedArgb;
1296        private int mLedOnMs;
1297        private int mLedOffMs;
1298        private int mDefaults;
1299        private int mFlags;
1300        private int mProgressMax;
1301        private int mProgress;
1302        private boolean mProgressIndeterminate;
1303        private String mCategory;
1304        private Bundle mExtras;
1305        private int mPriority;
1306        private ArrayList<Action> mActions = new ArrayList<Action>(MAX_ACTION_BUTTONS);
1307        private boolean mUseChronometer;
1308        private Style mStyle;
1309        private boolean mShowWhen = true;
1310        private int mVisibility = VISIBILITY_PRIVATE;
1311        private Notification mPublicVersion = null;
1312        private boolean mQuantumTheme;
1313        private final LegacyNotificationUtil mLegacyNotificationUtil;
1314
1315        /**
1316         * Constructs a new Builder with the defaults:
1317         *
1318
1319         * <table>
1320         * <tr><th align=right>priority</th>
1321         *     <td>{@link #PRIORITY_DEFAULT}</td></tr>
1322         * <tr><th align=right>when</th>
1323         *     <td>now ({@link System#currentTimeMillis()})</td></tr>
1324         * <tr><th align=right>audio stream</th>
1325         *     <td>{@link #STREAM_DEFAULT}</td></tr>
1326         * </table>
1327         *
1328
1329         * @param context
1330         *            A {@link Context} that will be used by the Builder to construct the
1331         *            RemoteViews. The Context will not be held past the lifetime of this Builder
1332         *            object.
1333         */
1334        public Builder(Context context) {
1335            mContext = context;
1336
1337            // Set defaults to match the defaults of a Notification
1338            mWhen = System.currentTimeMillis();
1339            mAudioStreamType = STREAM_DEFAULT;
1340            mPriority = PRIORITY_DEFAULT;
1341
1342            // TODO: Decide on targetSdk from calling app whether to use quantum theme.
1343            mQuantumTheme = true;
1344
1345            // TODO: Decide on targetSdk from calling app whether to instantiate the processor at
1346            // all.
1347            mLegacyNotificationUtil = LegacyNotificationUtil.getInstance();
1348        }
1349
1350        /**
1351         * Add a timestamp pertaining to the notification (usually the time the event occurred).
1352         * It will be shown in the notification content view by default; use
1353         * {@link Builder#setShowWhen(boolean) setShowWhen} to control this.
1354         *
1355         * @see Notification#when
1356         */
1357        public Builder setWhen(long when) {
1358            mWhen = when;
1359            return this;
1360        }
1361
1362        /**
1363         * Control whether the timestamp set with {@link Builder#setWhen(long) setWhen} is shown
1364         * in the content view.
1365         */
1366        public Builder setShowWhen(boolean show) {
1367            mShowWhen = show;
1368            return this;
1369        }
1370
1371        /**
1372         * Show the {@link Notification#when} field as a stopwatch.
1373         *
1374         * Instead of presenting <code>when</code> as a timestamp, the notification will show an
1375         * automatically updating display of the minutes and seconds since <code>when</code>.
1376         *
1377         * Useful when showing an elapsed time (like an ongoing phone call).
1378         *
1379         * @see android.widget.Chronometer
1380         * @see Notification#when
1381         */
1382        public Builder setUsesChronometer(boolean b) {
1383            mUseChronometer = b;
1384            return this;
1385        }
1386
1387        /**
1388         * Set the small icon resource, which will be used to represent the notification in the
1389         * status bar.
1390         *
1391
1392         * The platform template for the expanded view will draw this icon in the left, unless a
1393         * {@link #setLargeIcon(Bitmap) large icon} has also been specified, in which case the small
1394         * icon will be moved to the right-hand side.
1395         *
1396
1397         * @param icon
1398         *            A resource ID in the application's package of the drawable to use.
1399         * @see Notification#icon
1400         */
1401        public Builder setSmallIcon(int icon) {
1402            mSmallIcon = icon;
1403            return this;
1404        }
1405
1406        /**
1407         * A variant of {@link #setSmallIcon(int) setSmallIcon(int)} that takes an additional
1408         * level parameter for when the icon is a {@link android.graphics.drawable.LevelListDrawable
1409         * LevelListDrawable}.
1410         *
1411         * @param icon A resource ID in the application's package of the drawable to use.
1412         * @param level The level to use for the icon.
1413         *
1414         * @see Notification#icon
1415         * @see Notification#iconLevel
1416         */
1417        public Builder setSmallIcon(int icon, int level) {
1418            mSmallIcon = icon;
1419            mSmallIconLevel = level;
1420            return this;
1421        }
1422
1423        /**
1424         * Set the first line of text in the platform notification template.
1425         */
1426        public Builder setContentTitle(CharSequence title) {
1427            mContentTitle = safeCharSequence(title);
1428            return this;
1429        }
1430
1431        /**
1432         * Set the second line of text in the platform notification template.
1433         */
1434        public Builder setContentText(CharSequence text) {
1435            mContentText = safeCharSequence(text);
1436            return this;
1437        }
1438
1439        /**
1440         * Set the third line of text in the platform notification template.
1441         * Don't use if you're also using {@link #setProgress(int, int, boolean)}; they occupy the
1442         * same location in the standard template.
1443         */
1444        public Builder setSubText(CharSequence text) {
1445            mSubText = safeCharSequence(text);
1446            return this;
1447        }
1448
1449        /**
1450         * Set the large number at the right-hand side of the notification.  This is
1451         * equivalent to setContentInfo, although it might show the number in a different
1452         * font size for readability.
1453         */
1454        public Builder setNumber(int number) {
1455            mNumber = number;
1456            return this;
1457        }
1458
1459        /**
1460         * A small piece of additional information pertaining to this notification.
1461         *
1462         * The platform template will draw this on the last line of the notification, at the far
1463         * right (to the right of a smallIcon if it has been placed there).
1464         */
1465        public Builder setContentInfo(CharSequence info) {
1466            mContentInfo = safeCharSequence(info);
1467            return this;
1468        }
1469
1470        /**
1471         * Set the progress this notification represents.
1472         *
1473         * The platform template will represent this using a {@link ProgressBar}.
1474         */
1475        public Builder setProgress(int max, int progress, boolean indeterminate) {
1476            mProgressMax = max;
1477            mProgress = progress;
1478            mProgressIndeterminate = indeterminate;
1479            return this;
1480        }
1481
1482        /**
1483         * Supply a custom RemoteViews to use instead of the platform template.
1484         *
1485         * @see Notification#contentView
1486         */
1487        public Builder setContent(RemoteViews views) {
1488            mContentView = views;
1489            return this;
1490        }
1491
1492        /**
1493         * Supply a {@link PendingIntent} to be sent when the notification is clicked.
1494         *
1495         * As of {@link android.os.Build.VERSION_CODES#HONEYCOMB}, if this field is unset and you
1496         * have specified a custom RemoteViews with {@link #setContent(RemoteViews)}, you can use
1497         * {@link RemoteViews#setOnClickPendingIntent RemoteViews.setOnClickPendingIntent(int,PendingIntent)}
1498         * to assign PendingIntents to individual views in that custom layout (i.e., to create
1499         * clickable buttons inside the notification view).
1500         *
1501         * @see Notification#contentIntent Notification.contentIntent
1502         */
1503        public Builder setContentIntent(PendingIntent intent) {
1504            mContentIntent = intent;
1505            return this;
1506        }
1507
1508        /**
1509         * Supply a {@link PendingIntent} to send when the notification is cleared explicitly by the user.
1510         *
1511         * @see Notification#deleteIntent
1512         */
1513        public Builder setDeleteIntent(PendingIntent intent) {
1514            mDeleteIntent = intent;
1515            return this;
1516        }
1517
1518        /**
1519         * An intent to launch instead of posting the notification to the status bar.
1520         * Only for use with extremely high-priority notifications demanding the user's
1521         * <strong>immediate</strong> attention, such as an incoming phone call or
1522         * alarm clock that the user has explicitly set to a particular time.
1523         * If this facility is used for something else, please give the user an option
1524         * to turn it off and use a normal notification, as this can be extremely
1525         * disruptive.
1526         *
1527         * @param intent The pending intent to launch.
1528         * @param highPriority Passing true will cause this notification to be sent
1529         *          even if other notifications are suppressed.
1530         *
1531         * @see Notification#fullScreenIntent
1532         */
1533        public Builder setFullScreenIntent(PendingIntent intent, boolean highPriority) {
1534            mFullScreenIntent = intent;
1535            setFlag(FLAG_HIGH_PRIORITY, highPriority);
1536            return this;
1537        }
1538
1539        /**
1540         * Set the "ticker" text which is displayed in the status bar when the notification first
1541         * arrives.
1542         *
1543         * @see Notification#tickerText
1544         */
1545        public Builder setTicker(CharSequence tickerText) {
1546            mTickerText = safeCharSequence(tickerText);
1547            return this;
1548        }
1549
1550        /**
1551         * Set the text that is displayed in the status bar when the notification first
1552         * arrives, and also a RemoteViews object that may be displayed instead on some
1553         * devices.
1554         *
1555         * @see Notification#tickerText
1556         * @see Notification#tickerView
1557         */
1558        public Builder setTicker(CharSequence tickerText, RemoteViews views) {
1559            mTickerText = safeCharSequence(tickerText);
1560            mTickerView = views;
1561            return this;
1562        }
1563
1564        /**
1565         * Add a large icon to the notification (and the ticker on some devices).
1566         *
1567         * In the platform template, this image will be shown on the left of the notification view
1568         * in place of the {@link #setSmallIcon(int) small icon} (which will move to the right side).
1569         *
1570         * @see Notification#largeIcon
1571         */
1572        public Builder setLargeIcon(Bitmap icon) {
1573            mLargeIcon = icon;
1574            return this;
1575        }
1576
1577        /**
1578         * Set the sound to play.
1579         *
1580         * It will be played on the {@link #STREAM_DEFAULT default stream} for notifications.
1581         *
1582         * @see Notification#sound
1583         */
1584        public Builder setSound(Uri sound) {
1585            mSound = sound;
1586            mAudioStreamType = STREAM_DEFAULT;
1587            return this;
1588        }
1589
1590        /**
1591         * Set the sound to play, along with a specific stream on which to play it.
1592         *
1593         * See {@link android.media.AudioManager} for the <code>STREAM_</code> constants.
1594         *
1595         * @see Notification#sound
1596         */
1597        public Builder setSound(Uri sound, int streamType) {
1598            mSound = sound;
1599            mAudioStreamType = streamType;
1600            return this;
1601        }
1602
1603        /**
1604         * Set the vibration pattern to use.
1605         *
1606
1607         * See {@link android.os.Vibrator#vibrate(long[], int)} for a discussion of the
1608         * <code>pattern</code> parameter.
1609         *
1610
1611         * @see Notification#vibrate
1612         */
1613        public Builder setVibrate(long[] pattern) {
1614            mVibrate = pattern;
1615            return this;
1616        }
1617
1618        /**
1619         * Set the desired color for the indicator LED on the device, as well as the
1620         * blink duty cycle (specified in milliseconds).
1621         *
1622
1623         * Not all devices will honor all (or even any) of these values.
1624         *
1625
1626         * @see Notification#ledARGB
1627         * @see Notification#ledOnMS
1628         * @see Notification#ledOffMS
1629         */
1630        public Builder setLights(int argb, int onMs, int offMs) {
1631            mLedArgb = argb;
1632            mLedOnMs = onMs;
1633            mLedOffMs = offMs;
1634            return this;
1635        }
1636
1637        /**
1638         * Set whether this is an "ongoing" notification.
1639         *
1640
1641         * Ongoing notifications cannot be dismissed by the user, so your application or service
1642         * must take care of canceling them.
1643         *
1644
1645         * They are typically used to indicate a background task that the user is actively engaged
1646         * with (e.g., playing music) or is pending in some way and therefore occupying the device
1647         * (e.g., a file download, sync operation, active network connection).
1648         *
1649
1650         * @see Notification#FLAG_ONGOING_EVENT
1651         * @see Service#setForeground(boolean)
1652         */
1653        public Builder setOngoing(boolean ongoing) {
1654            setFlag(FLAG_ONGOING_EVENT, ongoing);
1655            return this;
1656        }
1657
1658        /**
1659         * Set this flag if you would only like the sound, vibrate
1660         * and ticker to be played if the notification is not already showing.
1661         *
1662         * @see Notification#FLAG_ONLY_ALERT_ONCE
1663         */
1664        public Builder setOnlyAlertOnce(boolean onlyAlertOnce) {
1665            setFlag(FLAG_ONLY_ALERT_ONCE, onlyAlertOnce);
1666            return this;
1667        }
1668
1669        /**
1670         * Make this notification automatically dismissed when the user touches it. The
1671         * PendingIntent set with {@link #setDeleteIntent} will be sent when this happens.
1672         *
1673         * @see Notification#FLAG_AUTO_CANCEL
1674         */
1675        public Builder setAutoCancel(boolean autoCancel) {
1676            setFlag(FLAG_AUTO_CANCEL, autoCancel);
1677            return this;
1678        }
1679
1680        /**
1681         * Set whether or not this notification should not bridge to other devices.
1682         *
1683         * <p>Some notifications can be bridged to other devices for remote display.
1684         * This hint can be set to recommend this notification not be bridged.
1685         */
1686        public Builder setLocalOnly(boolean localOnly) {
1687            setFlag(FLAG_LOCAL_ONLY, localOnly);
1688            return this;
1689        }
1690
1691        /**
1692         * Set which notification properties will be inherited from system defaults.
1693         * <p>
1694         * The value should be one or more of the following fields combined with
1695         * bitwise-or:
1696         * {@link #DEFAULT_SOUND}, {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}.
1697         * <p>
1698         * For all default values, use {@link #DEFAULT_ALL}.
1699         */
1700        public Builder setDefaults(int defaults) {
1701            mDefaults = defaults;
1702            return this;
1703        }
1704
1705        /**
1706         * Set the priority of this notification.
1707         *
1708         * @see Notification#priority
1709         */
1710        public Builder setPriority(@Priority int pri) {
1711            mPriority = pri;
1712            return this;
1713        }
1714
1715        /**
1716         * Set the notification category.
1717         *
1718         * @see Notification#category
1719         */
1720        public Builder setCategory(String category) {
1721            mCategory = category;
1722            return this;
1723        }
1724
1725        /**
1726         * Merge additional metadata into this notification.
1727         *
1728         * <p>Values within the Bundle will replace existing extras values in this Builder.
1729         *
1730         * @see Notification#extras
1731         */
1732        public Builder addExtras(Bundle bag) {
1733            if (mExtras == null) {
1734                mExtras = new Bundle(bag);
1735            } else {
1736                mExtras.putAll(bag);
1737            }
1738            return this;
1739        }
1740
1741        /**
1742         * Set metadata for this notification.
1743         *
1744         * <p>A reference to the Bundle is held for the lifetime of this Builder, and the Bundle's
1745         * current contents are copied into the Notification each time {@link #build()} is
1746         * called.
1747         *
1748         * <p>Replaces any existing extras values with those from the provided Bundle.
1749         * Use {@link #addExtras} to merge in metadata instead.
1750         *
1751         * @see Notification#extras
1752         */
1753        public Builder setExtras(Bundle bag) {
1754            mExtras = bag;
1755            return this;
1756        }
1757
1758        /**
1759         * Get the current metadata Bundle used by this notification Builder.
1760         *
1761         * <p>The returned Bundle is shared with this Builder.
1762         *
1763         * <p>The current contents of this Bundle are copied into the Notification each time
1764         * {@link #build()} is called.
1765         *
1766         * @see Notification#extras
1767         */
1768        public Bundle getExtras() {
1769            if (mExtras == null) {
1770                mExtras = new Bundle();
1771            }
1772            return mExtras;
1773        }
1774
1775        /**
1776         * Add an action to this notification. Actions are typically displayed by
1777         * the system as a button adjacent to the notification content.
1778         * <p>
1779         * Every action must have an icon (32dp square and matching the
1780         * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo
1781         * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}.
1782         * <p>
1783         * A notification in its expanded form can display up to 3 actions, from left to right in
1784         * the order they were added. Actions will not be displayed when the notification is
1785         * collapsed, however, so be sure that any essential functions may be accessed by the user
1786         * in some other way (for example, in the Activity pointed to by {@link #contentIntent}).
1787         *
1788         * @param icon Resource ID of a drawable that represents the action.
1789         * @param title Text describing the action.
1790         * @param intent PendingIntent to be fired when the action is invoked.
1791         */
1792        public Builder addAction(int icon, CharSequence title, PendingIntent intent) {
1793            mActions.add(new Action(icon, safeCharSequence(title), intent));
1794            return this;
1795        }
1796
1797        /**
1798         * Add a rich notification style to be applied at build time.
1799         *
1800         * @param style Object responsible for modifying the notification style.
1801         */
1802        public Builder setStyle(Style style) {
1803            if (mStyle != style) {
1804                mStyle = style;
1805                if (mStyle != null) {
1806                    mStyle.setBuilder(this);
1807                }
1808            }
1809            return this;
1810        }
1811
1812        /**
1813         * Specify the value of {@link #visibility}.
1814
1815         * @param visibility One of {@link #VISIBILITY_PRIVATE} (the default),
1816         * {@link #VISIBILITY_SECRET}, or {@link #VISIBILITY_PUBLIC}.
1817         *
1818         * @return The same Builder.
1819         */
1820        public Builder setVisibility(int visibility) {
1821            mVisibility = visibility;
1822            return this;
1823        }
1824
1825        /**
1826         * Supply a replacement Notification whose contents should be shown in insecure contexts
1827         * (i.e. atop the secure lockscreen). See {@link #visibility} and {@link #VISIBILITY_PUBLIC}.
1828         * @param n A replacement notification, presumably with some or all info redacted.
1829         * @return The same Builder.
1830         */
1831        public Builder setPublicVersion(Notification n) {
1832            mPublicVersion = n;
1833            return this;
1834        }
1835
1836        private void setFlag(int mask, boolean value) {
1837            if (value) {
1838                mFlags |= mask;
1839            } else {
1840                mFlags &= ~mask;
1841            }
1842        }
1843
1844        private RemoteViews applyStandardTemplate(int resId, boolean fitIn1U) {
1845            RemoteViews contentView = new RemoteViews(mContext.getPackageName(), resId);
1846            boolean showLine3 = false;
1847            boolean showLine2 = false;
1848            int smallIconImageViewId = R.id.icon;
1849            if (!mQuantumTheme && mPriority < PRIORITY_LOW) {
1850                contentView.setInt(R.id.icon,
1851                        "setBackgroundResource", R.drawable.notification_template_icon_low_bg);
1852                contentView.setInt(R.id.status_bar_latest_event_content,
1853                        "setBackgroundResource", R.drawable.notification_bg_low);
1854            }
1855            if (mLargeIcon != null) {
1856                contentView.setImageViewBitmap(R.id.icon, mLargeIcon);
1857                processLegacyLargeIcon(mLargeIcon, contentView);
1858                smallIconImageViewId = R.id.right_icon;
1859            }
1860            if (mSmallIcon != 0) {
1861                contentView.setImageViewResource(smallIconImageViewId, mSmallIcon);
1862                contentView.setViewVisibility(smallIconImageViewId, View.VISIBLE);
1863                if (mLargeIcon != null) {
1864                    processLegacySmallIcon(mSmallIcon, smallIconImageViewId, contentView);
1865                } else {
1866                    processLegacyLargeIcon(mSmallIcon, contentView);
1867                }
1868
1869            } else {
1870                contentView.setViewVisibility(smallIconImageViewId, View.GONE);
1871            }
1872            if (mContentTitle != null) {
1873                contentView.setTextViewText(R.id.title, processLegacyText(mContentTitle));
1874            }
1875            if (mContentText != null) {
1876                contentView.setTextViewText(R.id.text, processLegacyText(mContentText));
1877                showLine3 = true;
1878            }
1879            if (mContentInfo != null) {
1880                contentView.setTextViewText(R.id.info, processLegacyText(mContentInfo));
1881                contentView.setViewVisibility(R.id.info, View.VISIBLE);
1882                showLine3 = true;
1883            } else if (mNumber > 0) {
1884                final int tooBig = mContext.getResources().getInteger(
1885                        R.integer.status_bar_notification_info_maxnum);
1886                if (mNumber > tooBig) {
1887                    contentView.setTextViewText(R.id.info, processLegacyText(
1888                            mContext.getResources().getString(
1889                                    R.string.status_bar_notification_info_overflow)));
1890                } else {
1891                    NumberFormat f = NumberFormat.getIntegerInstance();
1892                    contentView.setTextViewText(R.id.info, processLegacyText(f.format(mNumber)));
1893                }
1894                contentView.setViewVisibility(R.id.info, View.VISIBLE);
1895                showLine3 = true;
1896            } else {
1897                contentView.setViewVisibility(R.id.info, View.GONE);
1898            }
1899
1900            // Need to show three lines?
1901            if (mSubText != null) {
1902                contentView.setTextViewText(R.id.text, processLegacyText(mSubText));
1903                if (mContentText != null) {
1904                    contentView.setTextViewText(R.id.text2, processLegacyText(mContentText));
1905                    contentView.setViewVisibility(R.id.text2, View.VISIBLE);
1906                    showLine2 = true;
1907                } else {
1908                    contentView.setViewVisibility(R.id.text2, View.GONE);
1909                }
1910            } else {
1911                contentView.setViewVisibility(R.id.text2, View.GONE);
1912                if (mProgressMax != 0 || mProgressIndeterminate) {
1913                    contentView.setProgressBar(
1914                            R.id.progress, mProgressMax, mProgress, mProgressIndeterminate);
1915                    contentView.setViewVisibility(R.id.progress, View.VISIBLE);
1916                    showLine2 = true;
1917                } else {
1918                    contentView.setViewVisibility(R.id.progress, View.GONE);
1919                }
1920            }
1921            if (showLine2) {
1922                if (fitIn1U) {
1923                    // need to shrink all the type to make sure everything fits
1924                    final Resources res = mContext.getResources();
1925                    final float subTextSize = res.getDimensionPixelSize(
1926                            R.dimen.notification_subtext_size);
1927                    contentView.setTextViewTextSize(R.id.text, TypedValue.COMPLEX_UNIT_PX, subTextSize);
1928                }
1929                // vertical centering
1930                contentView.setViewPadding(R.id.line1, 0, 0, 0, 0);
1931            }
1932
1933            if (mWhen != 0 && mShowWhen) {
1934                if (mUseChronometer) {
1935                    contentView.setViewVisibility(R.id.chronometer, View.VISIBLE);
1936                    contentView.setLong(R.id.chronometer, "setBase",
1937                            mWhen + (SystemClock.elapsedRealtime() - System.currentTimeMillis()));
1938                    contentView.setBoolean(R.id.chronometer, "setStarted", true);
1939                } else {
1940                    contentView.setViewVisibility(R.id.time, View.VISIBLE);
1941                    contentView.setLong(R.id.time, "setTime", mWhen);
1942                }
1943            } else {
1944                contentView.setViewVisibility(R.id.time, View.GONE);
1945            }
1946
1947            contentView.setViewVisibility(R.id.line3, showLine3 ? View.VISIBLE : View.GONE);
1948            contentView.setViewVisibility(R.id.overflow_divider, showLine3 ? View.VISIBLE : View.GONE);
1949            return contentView;
1950        }
1951
1952        private RemoteViews applyStandardTemplateWithActions(int layoutId) {
1953            RemoteViews big = applyStandardTemplate(layoutId, false);
1954
1955            int N = mActions.size();
1956            if (N > 0) {
1957                // Log.d("Notification", "has actions: " + mContentText);
1958                big.setViewVisibility(R.id.actions, View.VISIBLE);
1959                big.setViewVisibility(R.id.action_divider, View.VISIBLE);
1960                if (N>MAX_ACTION_BUTTONS) N=MAX_ACTION_BUTTONS;
1961                big.removeAllViews(R.id.actions);
1962                for (int i=0; i<N; i++) {
1963                    final RemoteViews button = generateActionButton(mActions.get(i));
1964                    //Log.d("Notification", "adding action " + i + ": " + mActions.get(i).title);
1965                    big.addView(R.id.actions, button);
1966                }
1967            }
1968            return big;
1969        }
1970
1971        private RemoteViews makeContentView() {
1972            if (mContentView != null) {
1973                return mContentView;
1974            } else {
1975                return applyStandardTemplate(getBaseLayoutResource(), true); // no more special large_icon flavor
1976            }
1977        }
1978
1979        private RemoteViews makeTickerView() {
1980            if (mTickerView != null) {
1981                return mTickerView;
1982            } else {
1983                if (mContentView == null) {
1984                    return applyStandardTemplate(mLargeIcon == null
1985                            ? R.layout.status_bar_latest_event_ticker
1986                            : R.layout.status_bar_latest_event_ticker_large_icon, true);
1987                } else {
1988                    return null;
1989                }
1990            }
1991        }
1992
1993        private RemoteViews makeBigContentView() {
1994            if (mActions.size() == 0) return null;
1995
1996            return applyStandardTemplateWithActions(getBigBaseLayoutResource());
1997        }
1998
1999        private RemoteViews makeHeadsUpContentView() {
2000            if (mActions.size() == 0) return null;
2001
2002            return applyStandardTemplateWithActions(getBigBaseLayoutResource());
2003        }
2004
2005
2006        private RemoteViews generateActionButton(Action action) {
2007            final boolean tombstone = (action.actionIntent == null);
2008            RemoteViews button = new RemoteViews(mContext.getPackageName(),
2009                    tombstone ? getActionTombstoneLayoutResource()
2010                              : getActionLayoutResource());
2011            button.setTextViewCompoundDrawablesRelative(R.id.action0, action.icon, 0, 0, 0);
2012            button.setTextViewText(R.id.action0, processLegacyText(action.title));
2013            if (!tombstone) {
2014                button.setOnClickPendingIntent(R.id.action0, action.actionIntent);
2015            }
2016            button.setContentDescription(R.id.action0, action.title);
2017            processLegacyAction(action, button);
2018            return button;
2019        }
2020
2021        /**
2022         * @return Whether we are currently building a notification from a legacy (an app that
2023         *         doesn't create quantum notifications by itself) app.
2024         */
2025        private boolean isLegacy() {
2026            return mLegacyNotificationUtil != null;
2027        }
2028
2029        private void processLegacyAction(Action action, RemoteViews button) {
2030            if (isLegacy()) {
2031                if (mLegacyNotificationUtil.isGrayscale(mContext, action.icon)) {
2032                    button.setTextViewCompoundDrawablesRelativeColorFilter(R.id.action0, 0,
2033                            mContext.getResources().getColor(
2034                                    R.color.notification_action_legacy_color_filter),
2035                            PorterDuff.Mode.MULTIPLY);
2036                }
2037            }
2038        }
2039
2040        private CharSequence processLegacyText(CharSequence charSequence) {
2041            if (isLegacy()) {
2042                return mLegacyNotificationUtil.invertCharSequenceColors(charSequence);
2043            } else {
2044                return charSequence;
2045            }
2046        }
2047
2048        private void processLegacyLargeIcon(int largeIconId, RemoteViews contentView) {
2049            if (isLegacy()) {
2050                processLegacyLargeIcon(
2051                        mLegacyNotificationUtil.isGrayscale(mContext, largeIconId),
2052                        contentView);
2053            }
2054        }
2055
2056        private void processLegacyLargeIcon(Bitmap largeIcon, RemoteViews contentView) {
2057            if (isLegacy()) {
2058                processLegacyLargeIcon(
2059                        mLegacyNotificationUtil.isGrayscale(largeIcon),
2060                        contentView);
2061            }
2062        }
2063
2064        private void processLegacyLargeIcon(boolean isGrayscale, RemoteViews contentView) {
2065            if (isLegacy() && isGrayscale) {
2066                contentView.setInt(R.id.icon, "setBackgroundResource",
2067                        R.drawable.notification_icon_legacy_bg_inset);
2068            }
2069        }
2070
2071        private void processLegacySmallIcon(int smallIconDrawableId, int smallIconImageViewId,
2072                RemoteViews contentView) {
2073            if (isLegacy()) {
2074                if (mLegacyNotificationUtil.isGrayscale(mContext, smallIconDrawableId)) {
2075                    contentView.setDrawableParameters(smallIconImageViewId, false, -1,
2076                            mContext.getResources().getColor(
2077                                    R.color.notification_action_legacy_color_filter),
2078                            PorterDuff.Mode.MULTIPLY, -1);
2079                }
2080            }
2081        }
2082
2083        /**
2084         * Apply the unstyled operations and return a new {@link Notification} object.
2085         * @hide
2086         */
2087        public Notification buildUnstyled() {
2088            Notification n = new Notification();
2089            n.when = mWhen;
2090            n.icon = mSmallIcon;
2091            n.iconLevel = mSmallIconLevel;
2092            n.number = mNumber;
2093            n.contentView = makeContentView();
2094            n.contentIntent = mContentIntent;
2095            n.deleteIntent = mDeleteIntent;
2096            n.fullScreenIntent = mFullScreenIntent;
2097            n.tickerText = mTickerText;
2098            n.tickerView = makeTickerView();
2099            n.largeIcon = mLargeIcon;
2100            n.sound = mSound;
2101            n.audioStreamType = mAudioStreamType;
2102            n.vibrate = mVibrate;
2103            n.ledARGB = mLedArgb;
2104            n.ledOnMS = mLedOnMs;
2105            n.ledOffMS = mLedOffMs;
2106            n.defaults = mDefaults;
2107            n.flags = mFlags;
2108            n.bigContentView = makeBigContentView();
2109            n.headsUpContentView = makeHeadsUpContentView();
2110            if (mLedOnMs != 0 || mLedOffMs != 0) {
2111                n.flags |= FLAG_SHOW_LIGHTS;
2112            }
2113            if ((mDefaults & DEFAULT_LIGHTS) != 0) {
2114                n.flags |= FLAG_SHOW_LIGHTS;
2115            }
2116            n.category = mCategory;
2117            n.priority = mPriority;
2118            if (mActions.size() > 0) {
2119                n.actions = new Action[mActions.size()];
2120                mActions.toArray(n.actions);
2121            }
2122            n.visibility = mVisibility;
2123
2124            if (mPublicVersion != null) {
2125                n.publicVersion = new Notification();
2126                mPublicVersion.cloneInto(n.publicVersion, true);
2127            }
2128
2129            return n;
2130        }
2131
2132        /**
2133         * Capture, in the provided bundle, semantic information used in the construction of
2134         * this Notification object.
2135         * @hide
2136         */
2137        public void populateExtras(Bundle extras) {
2138            // Store original information used in the construction of this object
2139            extras.putCharSequence(EXTRA_TITLE, mContentTitle);
2140            extras.putCharSequence(EXTRA_TEXT, mContentText);
2141            extras.putCharSequence(EXTRA_SUB_TEXT, mSubText);
2142            extras.putCharSequence(EXTRA_INFO_TEXT, mContentInfo);
2143            extras.putInt(EXTRA_SMALL_ICON, mSmallIcon);
2144            extras.putInt(EXTRA_PROGRESS, mProgress);
2145            extras.putInt(EXTRA_PROGRESS_MAX, mProgressMax);
2146            extras.putBoolean(EXTRA_PROGRESS_INDETERMINATE, mProgressIndeterminate);
2147            extras.putBoolean(EXTRA_SHOW_CHRONOMETER, mUseChronometer);
2148            extras.putBoolean(EXTRA_SHOW_WHEN, mShowWhen);
2149            if (mLargeIcon != null) {
2150                extras.putParcelable(EXTRA_LARGE_ICON, mLargeIcon);
2151            }
2152        }
2153
2154        /**
2155         * @deprecated Use {@link #build()} instead.
2156         */
2157        @Deprecated
2158        public Notification getNotification() {
2159            return build();
2160        }
2161
2162        /**
2163         * Combine all of the options that have been set and return a new {@link Notification}
2164         * object.
2165         */
2166        public Notification build() {
2167            Notification n = buildUnstyled();
2168
2169            if (mStyle != null) {
2170                n = mStyle.buildStyled(n);
2171            }
2172
2173            n.extras = mExtras != null ? new Bundle(mExtras) : new Bundle();
2174
2175            populateExtras(n.extras);
2176            if (mStyle != null) {
2177                mStyle.addExtras(n.extras);
2178            }
2179
2180            return n;
2181        }
2182
2183        /**
2184         * Apply this Builder to an existing {@link Notification} object.
2185         *
2186         * @hide
2187         */
2188        public Notification buildInto(Notification n) {
2189            build().cloneInto(n, true);
2190            return n;
2191        }
2192
2193
2194        private int getBaseLayoutResource() {
2195            return mQuantumTheme
2196                    ? R.layout.notification_template_quantum_base
2197                    : R.layout.notification_template_base;
2198        }
2199
2200        private int getBigBaseLayoutResource() {
2201            return mQuantumTheme
2202                    ? R.layout.notification_template_quantum_big_base
2203                    : R.layout.notification_template_big_base;
2204        }
2205
2206        private int getBigPictureLayoutResource() {
2207            return mQuantumTheme
2208                    ? R.layout.notification_template_quantum_big_picture
2209                    : R.layout.notification_template_big_picture;
2210        }
2211
2212        private int getBigTextLayoutResource() {
2213            return mQuantumTheme
2214                    ? R.layout.notification_template_quantum_big_text
2215                    : R.layout.notification_template_big_text;
2216        }
2217
2218        private int getInboxLayoutResource() {
2219            return mQuantumTheme
2220                    ? R.layout.notification_template_quantum_inbox
2221                    : R.layout.notification_template_inbox;
2222        }
2223
2224        private int getActionLayoutResource() {
2225            return mQuantumTheme
2226                    ? R.layout.notification_quantum_action
2227                    : R.layout.notification_action;
2228        }
2229
2230        private int getActionTombstoneLayoutResource() {
2231            return mQuantumTheme
2232                    ? R.layout.notification_quantum_action_tombstone
2233                    : R.layout.notification_action_tombstone;
2234        }
2235    }
2236
2237    /**
2238     * An object that can apply a rich notification style to a {@link Notification.Builder}
2239     * object.
2240     */
2241    public static abstract class Style {
2242        private CharSequence mBigContentTitle;
2243        private CharSequence mSummaryText = null;
2244        private boolean mSummaryTextSet = false;
2245
2246        protected Builder mBuilder;
2247
2248        /**
2249         * Overrides ContentTitle in the big form of the template.
2250         * This defaults to the value passed to setContentTitle().
2251         */
2252        protected void internalSetBigContentTitle(CharSequence title) {
2253            mBigContentTitle = title;
2254        }
2255
2256        /**
2257         * Set the first line of text after the detail section in the big form of the template.
2258         */
2259        protected void internalSetSummaryText(CharSequence cs) {
2260            mSummaryText = cs;
2261            mSummaryTextSet = true;
2262        }
2263
2264        public void setBuilder(Builder builder) {
2265            if (mBuilder != builder) {
2266                mBuilder = builder;
2267                if (mBuilder != null) {
2268                    mBuilder.setStyle(this);
2269                }
2270            }
2271        }
2272
2273        protected void checkBuilder() {
2274            if (mBuilder == null) {
2275                throw new IllegalArgumentException("Style requires a valid Builder object");
2276            }
2277        }
2278
2279        protected RemoteViews getStandardView(int layoutId) {
2280            checkBuilder();
2281
2282            if (mBigContentTitle != null) {
2283                mBuilder.setContentTitle(mBigContentTitle);
2284            }
2285
2286            RemoteViews contentView = mBuilder.applyStandardTemplateWithActions(layoutId);
2287
2288            if (mBigContentTitle != null && mBigContentTitle.equals("")) {
2289                contentView.setViewVisibility(R.id.line1, View.GONE);
2290            } else {
2291                contentView.setViewVisibility(R.id.line1, View.VISIBLE);
2292            }
2293
2294            // The last line defaults to the subtext, but can be replaced by mSummaryText
2295            final CharSequence overflowText =
2296                    mSummaryTextSet ? mSummaryText
2297                                    : mBuilder.mSubText;
2298            if (overflowText != null) {
2299                contentView.setTextViewText(R.id.text, mBuilder.processLegacyText(overflowText));
2300                contentView.setViewVisibility(R.id.overflow_divider, View.VISIBLE);
2301                contentView.setViewVisibility(R.id.line3, View.VISIBLE);
2302            } else {
2303                contentView.setViewVisibility(R.id.overflow_divider, View.GONE);
2304                contentView.setViewVisibility(R.id.line3, View.GONE);
2305            }
2306
2307            return contentView;
2308        }
2309
2310        /**
2311         * @hide
2312         */
2313        public void addExtras(Bundle extras) {
2314            if (mSummaryTextSet) {
2315                extras.putCharSequence(EXTRA_SUMMARY_TEXT, mSummaryText);
2316            }
2317            if (mBigContentTitle != null) {
2318                extras.putCharSequence(EXTRA_TITLE_BIG, mBigContentTitle);
2319            }
2320            extras.putString(EXTRA_TEMPLATE, this.getClass().getName());
2321        }
2322
2323        /**
2324         * @hide
2325         */
2326        public abstract Notification buildStyled(Notification wip);
2327
2328        /**
2329         * Calls {@link android.app.Notification.Builder#build()} on the Builder this Style is
2330         * attached to.
2331         *
2332         * @return the fully constructed Notification.
2333         */
2334        public Notification build() {
2335            checkBuilder();
2336            return mBuilder.build();
2337        }
2338    }
2339
2340    /**
2341     * Helper class for generating large-format notifications that include a large image attachment.
2342     *
2343     * This class is a "rebuilder": It consumes a Builder object and modifies its behavior, like so:
2344     * <pre class="prettyprint">
2345     * Notification noti = new Notification.BigPictureStyle(
2346     *      new Notification.Builder()
2347     *         .setContentTitle(&quot;New photo from &quot; + sender.toString())
2348     *         .setContentText(subject)
2349     *         .setSmallIcon(R.drawable.new_post)
2350     *         .setLargeIcon(aBitmap))
2351     *      .bigPicture(aBigBitmap)
2352     *      .build();
2353     * </pre>
2354     *
2355     * @see Notification#bigContentView
2356     */
2357    public static class BigPictureStyle extends Style {
2358        private Bitmap mPicture;
2359        private Bitmap mBigLargeIcon;
2360        private boolean mBigLargeIconSet = false;
2361
2362        public BigPictureStyle() {
2363        }
2364
2365        public BigPictureStyle(Builder builder) {
2366            setBuilder(builder);
2367        }
2368
2369        /**
2370         * Overrides ContentTitle in the big form of the template.
2371         * This defaults to the value passed to setContentTitle().
2372         */
2373        public BigPictureStyle setBigContentTitle(CharSequence title) {
2374            internalSetBigContentTitle(safeCharSequence(title));
2375            return this;
2376        }
2377
2378        /**
2379         * Set the first line of text after the detail section in the big form of the template.
2380         */
2381        public BigPictureStyle setSummaryText(CharSequence cs) {
2382            internalSetSummaryText(safeCharSequence(cs));
2383            return this;
2384        }
2385
2386        /**
2387         * Provide the bitmap to be used as the payload for the BigPicture notification.
2388         */
2389        public BigPictureStyle bigPicture(Bitmap b) {
2390            mPicture = b;
2391            return this;
2392        }
2393
2394        /**
2395         * Override the large icon when the big notification is shown.
2396         */
2397        public BigPictureStyle bigLargeIcon(Bitmap b) {
2398            mBigLargeIconSet = true;
2399            mBigLargeIcon = b;
2400            return this;
2401        }
2402
2403        private RemoteViews makeBigContentView() {
2404            RemoteViews contentView = getStandardView(mBuilder.getBigPictureLayoutResource());
2405
2406            contentView.setImageViewBitmap(R.id.big_picture, mPicture);
2407
2408            return contentView;
2409        }
2410
2411        /**
2412         * @hide
2413         */
2414        public void addExtras(Bundle extras) {
2415            super.addExtras(extras);
2416
2417            if (mBigLargeIconSet) {
2418                extras.putParcelable(EXTRA_LARGE_ICON_BIG, mBigLargeIcon);
2419            }
2420            extras.putParcelable(EXTRA_PICTURE, mPicture);
2421        }
2422
2423        /**
2424         * @hide
2425         */
2426        @Override
2427        public Notification buildStyled(Notification wip) {
2428            if (mBigLargeIconSet ) {
2429                mBuilder.mLargeIcon = mBigLargeIcon;
2430            }
2431            wip.bigContentView = makeBigContentView();
2432            return wip;
2433        }
2434    }
2435
2436    /**
2437     * Helper class for generating large-format notifications that include a lot of text.
2438     *
2439     * This class is a "rebuilder": It consumes a Builder object and modifies its behavior, like so:
2440     * <pre class="prettyprint">
2441     * Notification noti = new Notification.BigTextStyle(
2442     *      new Notification.Builder()
2443     *         .setContentTitle(&quot;New mail from &quot; + sender.toString())
2444     *         .setContentText(subject)
2445     *         .setSmallIcon(R.drawable.new_mail)
2446     *         .setLargeIcon(aBitmap))
2447     *      .bigText(aVeryLongString)
2448     *      .build();
2449     * </pre>
2450     *
2451     * @see Notification#bigContentView
2452     */
2453    public static class BigTextStyle extends Style {
2454        private CharSequence mBigText;
2455
2456        public BigTextStyle() {
2457        }
2458
2459        public BigTextStyle(Builder builder) {
2460            setBuilder(builder);
2461        }
2462
2463        /**
2464         * Overrides ContentTitle in the big form of the template.
2465         * This defaults to the value passed to setContentTitle().
2466         */
2467        public BigTextStyle setBigContentTitle(CharSequence title) {
2468            internalSetBigContentTitle(safeCharSequence(title));
2469            return this;
2470        }
2471
2472        /**
2473         * Set the first line of text after the detail section in the big form of the template.
2474         */
2475        public BigTextStyle setSummaryText(CharSequence cs) {
2476            internalSetSummaryText(safeCharSequence(cs));
2477            return this;
2478        }
2479
2480        /**
2481         * Provide the longer text to be displayed in the big form of the
2482         * template in place of the content text.
2483         */
2484        public BigTextStyle bigText(CharSequence cs) {
2485            mBigText = safeCharSequence(cs);
2486            return this;
2487        }
2488
2489        /**
2490         * @hide
2491         */
2492        public void addExtras(Bundle extras) {
2493            super.addExtras(extras);
2494
2495            extras.putCharSequence(EXTRA_TEXT, mBigText);
2496        }
2497
2498        private RemoteViews makeBigContentView() {
2499            // Remove the content text so line3 only shows if you have a summary
2500            final boolean hadThreeLines = (mBuilder.mContentText != null && mBuilder.mSubText != null);
2501            mBuilder.mContentText = null;
2502
2503            RemoteViews contentView = getStandardView(mBuilder.getBigTextLayoutResource());
2504
2505            if (hadThreeLines) {
2506                // vertical centering
2507                contentView.setViewPadding(R.id.line1, 0, 0, 0, 0);
2508            }
2509
2510            contentView.setTextViewText(R.id.big_text, mBuilder.processLegacyText(mBigText));
2511            contentView.setViewVisibility(R.id.big_text, View.VISIBLE);
2512            contentView.setViewVisibility(R.id.text2, View.GONE);
2513
2514            return contentView;
2515        }
2516
2517        /**
2518         * @hide
2519         */
2520        @Override
2521        public Notification buildStyled(Notification wip) {
2522            wip.bigContentView = makeBigContentView();
2523
2524            wip.extras.putCharSequence(EXTRA_TEXT, mBigText);
2525
2526            return wip;
2527        }
2528    }
2529
2530    /**
2531     * Helper class for generating large-format notifications that include a list of (up to 5) strings.
2532     *
2533     * This class is a "rebuilder": It consumes a Builder object and modifies its behavior, like so:
2534     * <pre class="prettyprint">
2535     * Notification noti = new Notification.InboxStyle(
2536     *      new Notification.Builder()
2537     *         .setContentTitle(&quot;5 New mails from &quot; + sender.toString())
2538     *         .setContentText(subject)
2539     *         .setSmallIcon(R.drawable.new_mail)
2540     *         .setLargeIcon(aBitmap))
2541     *      .addLine(str1)
2542     *      .addLine(str2)
2543     *      .setContentTitle("")
2544     *      .setSummaryText(&quot;+3 more&quot;)
2545     *      .build();
2546     * </pre>
2547     *
2548     * @see Notification#bigContentView
2549     */
2550    public static class InboxStyle extends Style {
2551        private ArrayList<CharSequence> mTexts = new ArrayList<CharSequence>(5);
2552
2553        public InboxStyle() {
2554        }
2555
2556        public InboxStyle(Builder builder) {
2557            setBuilder(builder);
2558        }
2559
2560        /**
2561         * Overrides ContentTitle in the big form of the template.
2562         * This defaults to the value passed to setContentTitle().
2563         */
2564        public InboxStyle setBigContentTitle(CharSequence title) {
2565            internalSetBigContentTitle(safeCharSequence(title));
2566            return this;
2567        }
2568
2569        /**
2570         * Set the first line of text after the detail section in the big form of the template.
2571         */
2572        public InboxStyle setSummaryText(CharSequence cs) {
2573            internalSetSummaryText(safeCharSequence(cs));
2574            return this;
2575        }
2576
2577        /**
2578         * Append a line to the digest section of the Inbox notification.
2579         */
2580        public InboxStyle addLine(CharSequence cs) {
2581            mTexts.add(safeCharSequence(cs));
2582            return this;
2583        }
2584
2585        /**
2586         * @hide
2587         */
2588        public void addExtras(Bundle extras) {
2589            super.addExtras(extras);
2590            CharSequence[] a = new CharSequence[mTexts.size()];
2591            extras.putCharSequenceArray(EXTRA_TEXT_LINES, mTexts.toArray(a));
2592        }
2593
2594        private RemoteViews makeBigContentView() {
2595            // Remove the content text so line3 disappears unless you have a summary
2596            mBuilder.mContentText = null;
2597            RemoteViews contentView = getStandardView(mBuilder.getInboxLayoutResource());
2598
2599            contentView.setViewVisibility(R.id.text2, View.GONE);
2600
2601            int[] rowIds = {R.id.inbox_text0, R.id.inbox_text1, R.id.inbox_text2, R.id.inbox_text3,
2602                    R.id.inbox_text4, R.id.inbox_text5, R.id.inbox_text6};
2603
2604            // Make sure all rows are gone in case we reuse a view.
2605            for (int rowId : rowIds) {
2606                contentView.setViewVisibility(rowId, View.GONE);
2607            }
2608
2609
2610            int i=0;
2611            while (i < mTexts.size() && i < rowIds.length) {
2612                CharSequence str = mTexts.get(i);
2613                if (str != null && !str.equals("")) {
2614                    contentView.setViewVisibility(rowIds[i], View.VISIBLE);
2615                    contentView.setTextViewText(rowIds[i], mBuilder.processLegacyText(str));
2616                }
2617                i++;
2618            }
2619
2620            contentView.setViewVisibility(R.id.inbox_end_pad,
2621                    mTexts.size() > 0 ? View.VISIBLE : View.GONE);
2622
2623            contentView.setViewVisibility(R.id.inbox_more,
2624                    mTexts.size() > rowIds.length ? View.VISIBLE : View.GONE);
2625
2626            return contentView;
2627        }
2628
2629        /**
2630         * @hide
2631         */
2632        @Override
2633        public Notification buildStyled(Notification wip) {
2634            wip.bigContentView = makeBigContentView();
2635
2636            return wip;
2637        }
2638    }
2639}
2640