Notification.java revision 7c12112d6292f9424726c257b237d0fd1bd03eab
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 would only like the sound, vibrate and ticker to be played
332     * if the notification was not already showing.
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        private ArrayList<String> mPeople;
1315
1316        /**
1317         * Constructs a new Builder with the defaults:
1318         *
1319
1320         * <table>
1321         * <tr><th align=right>priority</th>
1322         *     <td>{@link #PRIORITY_DEFAULT}</td></tr>
1323         * <tr><th align=right>when</th>
1324         *     <td>now ({@link System#currentTimeMillis()})</td></tr>
1325         * <tr><th align=right>audio stream</th>
1326         *     <td>{@link #STREAM_DEFAULT}</td></tr>
1327         * </table>
1328         *
1329
1330         * @param context
1331         *            A {@link Context} that will be used by the Builder to construct the
1332         *            RemoteViews. The Context will not be held past the lifetime of this Builder
1333         *            object.
1334         */
1335        public Builder(Context context) {
1336            mContext = context;
1337
1338            // Set defaults to match the defaults of a Notification
1339            mWhen = System.currentTimeMillis();
1340            mAudioStreamType = STREAM_DEFAULT;
1341            mPriority = PRIORITY_DEFAULT;
1342            mPeople = new ArrayList<String>();
1343
1344            // TODO: Decide on targetSdk from calling app whether to use quantum theme.
1345            mQuantumTheme = true;
1346
1347            // TODO: Decide on targetSdk from calling app whether to instantiate the processor at
1348            // all.
1349            mLegacyNotificationUtil = LegacyNotificationUtil.getInstance();
1350        }
1351
1352        /**
1353         * Add a timestamp pertaining to the notification (usually the time the event occurred).
1354         * It will be shown in the notification content view by default; use
1355         * {@link Builder#setShowWhen(boolean) setShowWhen} to control this.
1356         *
1357         * @see Notification#when
1358         */
1359        public Builder setWhen(long when) {
1360            mWhen = when;
1361            return this;
1362        }
1363
1364        /**
1365         * Control whether the timestamp set with {@link Builder#setWhen(long) setWhen} is shown
1366         * in the content view.
1367         */
1368        public Builder setShowWhen(boolean show) {
1369            mShowWhen = show;
1370            return this;
1371        }
1372
1373        /**
1374         * Show the {@link Notification#when} field as a stopwatch.
1375         *
1376         * Instead of presenting <code>when</code> as a timestamp, the notification will show an
1377         * automatically updating display of the minutes and seconds since <code>when</code>.
1378         *
1379         * Useful when showing an elapsed time (like an ongoing phone call).
1380         *
1381         * @see android.widget.Chronometer
1382         * @see Notification#when
1383         */
1384        public Builder setUsesChronometer(boolean b) {
1385            mUseChronometer = b;
1386            return this;
1387        }
1388
1389        /**
1390         * Set the small icon resource, which will be used to represent the notification in the
1391         * status bar.
1392         *
1393
1394         * The platform template for the expanded view will draw this icon in the left, unless a
1395         * {@link #setLargeIcon(Bitmap) large icon} has also been specified, in which case the small
1396         * icon will be moved to the right-hand side.
1397         *
1398
1399         * @param icon
1400         *            A resource ID in the application's package of the drawable to use.
1401         * @see Notification#icon
1402         */
1403        public Builder setSmallIcon(int icon) {
1404            mSmallIcon = icon;
1405            return this;
1406        }
1407
1408        /**
1409         * A variant of {@link #setSmallIcon(int) setSmallIcon(int)} that takes an additional
1410         * level parameter for when the icon is a {@link android.graphics.drawable.LevelListDrawable
1411         * LevelListDrawable}.
1412         *
1413         * @param icon A resource ID in the application's package of the drawable to use.
1414         * @param level The level to use for the icon.
1415         *
1416         * @see Notification#icon
1417         * @see Notification#iconLevel
1418         */
1419        public Builder setSmallIcon(int icon, int level) {
1420            mSmallIcon = icon;
1421            mSmallIconLevel = level;
1422            return this;
1423        }
1424
1425        /**
1426         * Set the first line of text in the platform notification template.
1427         */
1428        public Builder setContentTitle(CharSequence title) {
1429            mContentTitle = safeCharSequence(title);
1430            return this;
1431        }
1432
1433        /**
1434         * Set the second line of text in the platform notification template.
1435         */
1436        public Builder setContentText(CharSequence text) {
1437            mContentText = safeCharSequence(text);
1438            return this;
1439        }
1440
1441        /**
1442         * Set the third line of text in the platform notification template.
1443         * Don't use if you're also using {@link #setProgress(int, int, boolean)}; they occupy the
1444         * same location in the standard template.
1445         */
1446        public Builder setSubText(CharSequence text) {
1447            mSubText = safeCharSequence(text);
1448            return this;
1449        }
1450
1451        /**
1452         * Set the large number at the right-hand side of the notification.  This is
1453         * equivalent to setContentInfo, although it might show the number in a different
1454         * font size for readability.
1455         */
1456        public Builder setNumber(int number) {
1457            mNumber = number;
1458            return this;
1459        }
1460
1461        /**
1462         * A small piece of additional information pertaining to this notification.
1463         *
1464         * The platform template will draw this on the last line of the notification, at the far
1465         * right (to the right of a smallIcon if it has been placed there).
1466         */
1467        public Builder setContentInfo(CharSequence info) {
1468            mContentInfo = safeCharSequence(info);
1469            return this;
1470        }
1471
1472        /**
1473         * Set the progress this notification represents.
1474         *
1475         * The platform template will represent this using a {@link ProgressBar}.
1476         */
1477        public Builder setProgress(int max, int progress, boolean indeterminate) {
1478            mProgressMax = max;
1479            mProgress = progress;
1480            mProgressIndeterminate = indeterminate;
1481            return this;
1482        }
1483
1484        /**
1485         * Supply a custom RemoteViews to use instead of the platform template.
1486         *
1487         * @see Notification#contentView
1488         */
1489        public Builder setContent(RemoteViews views) {
1490            mContentView = views;
1491            return this;
1492        }
1493
1494        /**
1495         * Supply a {@link PendingIntent} to be sent when the notification is clicked.
1496         *
1497         * As of {@link android.os.Build.VERSION_CODES#HONEYCOMB}, if this field is unset and you
1498         * have specified a custom RemoteViews with {@link #setContent(RemoteViews)}, you can use
1499         * {@link RemoteViews#setOnClickPendingIntent RemoteViews.setOnClickPendingIntent(int,PendingIntent)}
1500         * to assign PendingIntents to individual views in that custom layout (i.e., to create
1501         * clickable buttons inside the notification view).
1502         *
1503         * @see Notification#contentIntent Notification.contentIntent
1504         */
1505        public Builder setContentIntent(PendingIntent intent) {
1506            mContentIntent = intent;
1507            return this;
1508        }
1509
1510        /**
1511         * Supply a {@link PendingIntent} to send when the notification is cleared explicitly by the user.
1512         *
1513         * @see Notification#deleteIntent
1514         */
1515        public Builder setDeleteIntent(PendingIntent intent) {
1516            mDeleteIntent = intent;
1517            return this;
1518        }
1519
1520        /**
1521         * An intent to launch instead of posting the notification to the status bar.
1522         * Only for use with extremely high-priority notifications demanding the user's
1523         * <strong>immediate</strong> attention, such as an incoming phone call or
1524         * alarm clock that the user has explicitly set to a particular time.
1525         * If this facility is used for something else, please give the user an option
1526         * to turn it off and use a normal notification, as this can be extremely
1527         * disruptive.
1528         *
1529         * @param intent The pending intent to launch.
1530         * @param highPriority Passing true will cause this notification to be sent
1531         *          even if other notifications are suppressed.
1532         *
1533         * @see Notification#fullScreenIntent
1534         */
1535        public Builder setFullScreenIntent(PendingIntent intent, boolean highPriority) {
1536            mFullScreenIntent = intent;
1537            setFlag(FLAG_HIGH_PRIORITY, highPriority);
1538            return this;
1539        }
1540
1541        /**
1542         * Set the "ticker" text which is displayed in the status bar when the notification first
1543         * arrives.
1544         *
1545         * @see Notification#tickerText
1546         */
1547        public Builder setTicker(CharSequence tickerText) {
1548            mTickerText = safeCharSequence(tickerText);
1549            return this;
1550        }
1551
1552        /**
1553         * Set the text that is displayed in the status bar when the notification first
1554         * arrives, and also a RemoteViews object that may be displayed instead on some
1555         * devices.
1556         *
1557         * @see Notification#tickerText
1558         * @see Notification#tickerView
1559         */
1560        public Builder setTicker(CharSequence tickerText, RemoteViews views) {
1561            mTickerText = safeCharSequence(tickerText);
1562            mTickerView = views;
1563            return this;
1564        }
1565
1566        /**
1567         * Add a large icon to the notification (and the ticker on some devices).
1568         *
1569         * In the platform template, this image will be shown on the left of the notification view
1570         * in place of the {@link #setSmallIcon(int) small icon} (which will move to the right side).
1571         *
1572         * @see Notification#largeIcon
1573         */
1574        public Builder setLargeIcon(Bitmap icon) {
1575            mLargeIcon = icon;
1576            return this;
1577        }
1578
1579        /**
1580         * Set the sound to play.
1581         *
1582         * It will be played on the {@link #STREAM_DEFAULT default stream} for notifications.
1583         *
1584         * @see Notification#sound
1585         */
1586        public Builder setSound(Uri sound) {
1587            mSound = sound;
1588            mAudioStreamType = STREAM_DEFAULT;
1589            return this;
1590        }
1591
1592        /**
1593         * Set the sound to play, along with a specific stream on which to play it.
1594         *
1595         * See {@link android.media.AudioManager} for the <code>STREAM_</code> constants.
1596         *
1597         * @see Notification#sound
1598         */
1599        public Builder setSound(Uri sound, int streamType) {
1600            mSound = sound;
1601            mAudioStreamType = streamType;
1602            return this;
1603        }
1604
1605        /**
1606         * Set the vibration pattern to use.
1607         *
1608
1609         * See {@link android.os.Vibrator#vibrate(long[], int)} for a discussion of the
1610         * <code>pattern</code> parameter.
1611         *
1612
1613         * @see Notification#vibrate
1614         */
1615        public Builder setVibrate(long[] pattern) {
1616            mVibrate = pattern;
1617            return this;
1618        }
1619
1620        /**
1621         * Set the desired color for the indicator LED on the device, as well as the
1622         * blink duty cycle (specified in milliseconds).
1623         *
1624
1625         * Not all devices will honor all (or even any) of these values.
1626         *
1627
1628         * @see Notification#ledARGB
1629         * @see Notification#ledOnMS
1630         * @see Notification#ledOffMS
1631         */
1632        public Builder setLights(int argb, int onMs, int offMs) {
1633            mLedArgb = argb;
1634            mLedOnMs = onMs;
1635            mLedOffMs = offMs;
1636            return this;
1637        }
1638
1639        /**
1640         * Set whether this is an "ongoing" notification.
1641         *
1642
1643         * Ongoing notifications cannot be dismissed by the user, so your application or service
1644         * must take care of canceling them.
1645         *
1646
1647         * They are typically used to indicate a background task that the user is actively engaged
1648         * with (e.g., playing music) or is pending in some way and therefore occupying the device
1649         * (e.g., a file download, sync operation, active network connection).
1650         *
1651
1652         * @see Notification#FLAG_ONGOING_EVENT
1653         * @see Service#setForeground(boolean)
1654         */
1655        public Builder setOngoing(boolean ongoing) {
1656            setFlag(FLAG_ONGOING_EVENT, ongoing);
1657            return this;
1658        }
1659
1660        /**
1661         * Set this flag if you would only like the sound, vibrate
1662         * and ticker to be played if the notification is not already showing.
1663         *
1664         * @see Notification#FLAG_ONLY_ALERT_ONCE
1665         */
1666        public Builder setOnlyAlertOnce(boolean onlyAlertOnce) {
1667            setFlag(FLAG_ONLY_ALERT_ONCE, onlyAlertOnce);
1668            return this;
1669        }
1670
1671        /**
1672         * Make this notification automatically dismissed when the user touches it. The
1673         * PendingIntent set with {@link #setDeleteIntent} will be sent when this happens.
1674         *
1675         * @see Notification#FLAG_AUTO_CANCEL
1676         */
1677        public Builder setAutoCancel(boolean autoCancel) {
1678            setFlag(FLAG_AUTO_CANCEL, autoCancel);
1679            return this;
1680        }
1681
1682        /**
1683         * Set whether or not this notification should not bridge to other devices.
1684         *
1685         * <p>Some notifications can be bridged to other devices for remote display.
1686         * This hint can be set to recommend this notification not be bridged.
1687         */
1688        public Builder setLocalOnly(boolean localOnly) {
1689            setFlag(FLAG_LOCAL_ONLY, localOnly);
1690            return this;
1691        }
1692
1693        /**
1694         * Set which notification properties will be inherited from system defaults.
1695         * <p>
1696         * The value should be one or more of the following fields combined with
1697         * bitwise-or:
1698         * {@link #DEFAULT_SOUND}, {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}.
1699         * <p>
1700         * For all default values, use {@link #DEFAULT_ALL}.
1701         */
1702        public Builder setDefaults(int defaults) {
1703            mDefaults = defaults;
1704            return this;
1705        }
1706
1707        /**
1708         * Set the priority of this notification.
1709         *
1710         * @see Notification#priority
1711         */
1712        public Builder setPriority(@Priority int pri) {
1713            mPriority = pri;
1714            return this;
1715        }
1716
1717        /**
1718         * Set the notification category.
1719         *
1720         * @see Notification#category
1721         */
1722        public Builder setCategory(String category) {
1723            mCategory = category;
1724            return this;
1725        }
1726
1727        /**
1728         * Add a person that is relevant to this notification.
1729         *
1730         * @see Notification#EXTRA_PEOPLE
1731         */
1732        public Builder addPerson(String handle) {
1733            mPeople.add(handle);
1734            return this;
1735        }
1736
1737        /**
1738         * Merge additional metadata into this notification.
1739         *
1740         * <p>Values within the Bundle will replace existing extras values in this Builder.
1741         *
1742         * @see Notification#extras
1743         */
1744        public Builder addExtras(Bundle bag) {
1745            if (mExtras == null) {
1746                mExtras = new Bundle(bag);
1747            } else {
1748                mExtras.putAll(bag);
1749            }
1750            return this;
1751        }
1752
1753        /**
1754         * Set metadata for this notification.
1755         *
1756         * <p>A reference to the Bundle is held for the lifetime of this Builder, and the Bundle's
1757         * current contents are copied into the Notification each time {@link #build()} is
1758         * called.
1759         *
1760         * <p>Replaces any existing extras values with those from the provided Bundle.
1761         * Use {@link #addExtras} to merge in metadata instead.
1762         *
1763         * @see Notification#extras
1764         */
1765        public Builder setExtras(Bundle bag) {
1766            mExtras = bag;
1767            return this;
1768        }
1769
1770        /**
1771         * Get the current metadata Bundle used by this notification Builder.
1772         *
1773         * <p>The returned Bundle is shared with this Builder.
1774         *
1775         * <p>The current contents of this Bundle are copied into the Notification each time
1776         * {@link #build()} is called.
1777         *
1778         * @see Notification#extras
1779         */
1780        public Bundle getExtras() {
1781            if (mExtras == null) {
1782                mExtras = new Bundle();
1783            }
1784            return mExtras;
1785        }
1786
1787        /**
1788         * Add an action to this notification. Actions are typically displayed by
1789         * the system as a button adjacent to the notification content.
1790         * <p>
1791         * Every action must have an icon (32dp square and matching the
1792         * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo
1793         * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}.
1794         * <p>
1795         * A notification in its expanded form can display up to 3 actions, from left to right in
1796         * the order they were added. Actions will not be displayed when the notification is
1797         * collapsed, however, so be sure that any essential functions may be accessed by the user
1798         * in some other way (for example, in the Activity pointed to by {@link #contentIntent}).
1799         *
1800         * @param icon Resource ID of a drawable that represents the action.
1801         * @param title Text describing the action.
1802         * @param intent PendingIntent to be fired when the action is invoked.
1803         */
1804        public Builder addAction(int icon, CharSequence title, PendingIntent intent) {
1805            mActions.add(new Action(icon, safeCharSequence(title), intent));
1806            return this;
1807        }
1808
1809        /**
1810         * Add a rich notification style to be applied at build time.
1811         *
1812         * @param style Object responsible for modifying the notification style.
1813         */
1814        public Builder setStyle(Style style) {
1815            if (mStyle != style) {
1816                mStyle = style;
1817                if (mStyle != null) {
1818                    mStyle.setBuilder(this);
1819                }
1820            }
1821            return this;
1822        }
1823
1824        /**
1825         * Specify the value of {@link #visibility}.
1826
1827         * @param visibility One of {@link #VISIBILITY_PRIVATE} (the default),
1828         * {@link #VISIBILITY_SECRET}, or {@link #VISIBILITY_PUBLIC}.
1829         *
1830         * @return The same Builder.
1831         */
1832        public Builder setVisibility(int visibility) {
1833            mVisibility = visibility;
1834            return this;
1835        }
1836
1837        /**
1838         * Supply a replacement Notification whose contents should be shown in insecure contexts
1839         * (i.e. atop the secure lockscreen). See {@link #visibility} and {@link #VISIBILITY_PUBLIC}.
1840         * @param n A replacement notification, presumably with some or all info redacted.
1841         * @return The same Builder.
1842         */
1843        public Builder setPublicVersion(Notification n) {
1844            mPublicVersion = n;
1845            return this;
1846        }
1847
1848        private void setFlag(int mask, boolean value) {
1849            if (value) {
1850                mFlags |= mask;
1851            } else {
1852                mFlags &= ~mask;
1853            }
1854        }
1855
1856        private RemoteViews applyStandardTemplate(int resId, boolean fitIn1U) {
1857            RemoteViews contentView = new RemoteViews(mContext.getPackageName(), resId);
1858            boolean showLine3 = false;
1859            boolean showLine2 = false;
1860            int smallIconImageViewId = R.id.icon;
1861            if (!mQuantumTheme && mPriority < PRIORITY_LOW) {
1862                contentView.setInt(R.id.icon,
1863                        "setBackgroundResource", R.drawable.notification_template_icon_low_bg);
1864                contentView.setInt(R.id.status_bar_latest_event_content,
1865                        "setBackgroundResource", R.drawable.notification_bg_low);
1866            }
1867            if (mLargeIcon != null) {
1868                contentView.setImageViewBitmap(R.id.icon, mLargeIcon);
1869                processLegacyLargeIcon(mLargeIcon, contentView);
1870                smallIconImageViewId = R.id.right_icon;
1871            }
1872            if (mSmallIcon != 0) {
1873                contentView.setImageViewResource(smallIconImageViewId, mSmallIcon);
1874                contentView.setViewVisibility(smallIconImageViewId, View.VISIBLE);
1875                if (mLargeIcon != null) {
1876                    processLegacySmallIcon(mSmallIcon, smallIconImageViewId, contentView);
1877                } else {
1878                    processLegacyLargeIcon(mSmallIcon, contentView);
1879                }
1880
1881            } else {
1882                contentView.setViewVisibility(smallIconImageViewId, View.GONE);
1883            }
1884            if (mContentTitle != null) {
1885                contentView.setTextViewText(R.id.title, processLegacyText(mContentTitle));
1886            }
1887            if (mContentText != null) {
1888                contentView.setTextViewText(R.id.text, processLegacyText(mContentText));
1889                showLine3 = true;
1890            }
1891            if (mContentInfo != null) {
1892                contentView.setTextViewText(R.id.info, processLegacyText(mContentInfo));
1893                contentView.setViewVisibility(R.id.info, View.VISIBLE);
1894                showLine3 = true;
1895            } else if (mNumber > 0) {
1896                final int tooBig = mContext.getResources().getInteger(
1897                        R.integer.status_bar_notification_info_maxnum);
1898                if (mNumber > tooBig) {
1899                    contentView.setTextViewText(R.id.info, processLegacyText(
1900                            mContext.getResources().getString(
1901                                    R.string.status_bar_notification_info_overflow)));
1902                } else {
1903                    NumberFormat f = NumberFormat.getIntegerInstance();
1904                    contentView.setTextViewText(R.id.info, processLegacyText(f.format(mNumber)));
1905                }
1906                contentView.setViewVisibility(R.id.info, View.VISIBLE);
1907                showLine3 = true;
1908            } else {
1909                contentView.setViewVisibility(R.id.info, View.GONE);
1910            }
1911
1912            // Need to show three lines?
1913            if (mSubText != null) {
1914                contentView.setTextViewText(R.id.text, processLegacyText(mSubText));
1915                if (mContentText != null) {
1916                    contentView.setTextViewText(R.id.text2, processLegacyText(mContentText));
1917                    contentView.setViewVisibility(R.id.text2, View.VISIBLE);
1918                    showLine2 = true;
1919                } else {
1920                    contentView.setViewVisibility(R.id.text2, View.GONE);
1921                }
1922            } else {
1923                contentView.setViewVisibility(R.id.text2, View.GONE);
1924                if (mProgressMax != 0 || mProgressIndeterminate) {
1925                    contentView.setProgressBar(
1926                            R.id.progress, mProgressMax, mProgress, mProgressIndeterminate);
1927                    contentView.setViewVisibility(R.id.progress, View.VISIBLE);
1928                    showLine2 = true;
1929                } else {
1930                    contentView.setViewVisibility(R.id.progress, View.GONE);
1931                }
1932            }
1933            if (showLine2) {
1934                if (fitIn1U) {
1935                    // need to shrink all the type to make sure everything fits
1936                    final Resources res = mContext.getResources();
1937                    final float subTextSize = res.getDimensionPixelSize(
1938                            R.dimen.notification_subtext_size);
1939                    contentView.setTextViewTextSize(R.id.text, TypedValue.COMPLEX_UNIT_PX, subTextSize);
1940                }
1941                // vertical centering
1942                contentView.setViewPadding(R.id.line1, 0, 0, 0, 0);
1943            }
1944
1945            if (mWhen != 0 && mShowWhen) {
1946                if (mUseChronometer) {
1947                    contentView.setViewVisibility(R.id.chronometer, View.VISIBLE);
1948                    contentView.setLong(R.id.chronometer, "setBase",
1949                            mWhen + (SystemClock.elapsedRealtime() - System.currentTimeMillis()));
1950                    contentView.setBoolean(R.id.chronometer, "setStarted", true);
1951                } else {
1952                    contentView.setViewVisibility(R.id.time, View.VISIBLE);
1953                    contentView.setLong(R.id.time, "setTime", mWhen);
1954                }
1955            } else {
1956                contentView.setViewVisibility(R.id.time, View.GONE);
1957            }
1958
1959            contentView.setViewVisibility(R.id.line3, showLine3 ? View.VISIBLE : View.GONE);
1960            contentView.setViewVisibility(R.id.overflow_divider, showLine3 ? View.VISIBLE : View.GONE);
1961            return contentView;
1962        }
1963
1964        private RemoteViews applyStandardTemplateWithActions(int layoutId) {
1965            RemoteViews big = applyStandardTemplate(layoutId, false);
1966
1967            int N = mActions.size();
1968            if (N > 0) {
1969                // Log.d("Notification", "has actions: " + mContentText);
1970                big.setViewVisibility(R.id.actions, View.VISIBLE);
1971                big.setViewVisibility(R.id.action_divider, View.VISIBLE);
1972                if (N>MAX_ACTION_BUTTONS) N=MAX_ACTION_BUTTONS;
1973                big.removeAllViews(R.id.actions);
1974                for (int i=0; i<N; i++) {
1975                    final RemoteViews button = generateActionButton(mActions.get(i));
1976                    //Log.d("Notification", "adding action " + i + ": " + mActions.get(i).title);
1977                    big.addView(R.id.actions, button);
1978                }
1979            }
1980            return big;
1981        }
1982
1983        private RemoteViews makeContentView() {
1984            if (mContentView != null) {
1985                return mContentView;
1986            } else {
1987                return applyStandardTemplate(getBaseLayoutResource(), true); // no more special large_icon flavor
1988            }
1989        }
1990
1991        private RemoteViews makeTickerView() {
1992            if (mTickerView != null) {
1993                return mTickerView;
1994            } else {
1995                if (mContentView == null) {
1996                    return applyStandardTemplate(mLargeIcon == null
1997                            ? R.layout.status_bar_latest_event_ticker
1998                            : R.layout.status_bar_latest_event_ticker_large_icon, true);
1999                } else {
2000                    return null;
2001                }
2002            }
2003        }
2004
2005        private RemoteViews makeBigContentView() {
2006            if (mActions.size() == 0) return null;
2007
2008            return applyStandardTemplateWithActions(getBigBaseLayoutResource());
2009        }
2010
2011        private RemoteViews makeHeadsUpContentView() {
2012            if (mActions.size() == 0) return null;
2013
2014            return applyStandardTemplateWithActions(getBigBaseLayoutResource());
2015        }
2016
2017
2018        private RemoteViews generateActionButton(Action action) {
2019            final boolean tombstone = (action.actionIntent == null);
2020            RemoteViews button = new RemoteViews(mContext.getPackageName(),
2021                    tombstone ? getActionTombstoneLayoutResource()
2022                              : getActionLayoutResource());
2023            button.setTextViewCompoundDrawablesRelative(R.id.action0, action.icon, 0, 0, 0);
2024            button.setTextViewText(R.id.action0, processLegacyText(action.title));
2025            if (!tombstone) {
2026                button.setOnClickPendingIntent(R.id.action0, action.actionIntent);
2027            }
2028            button.setContentDescription(R.id.action0, action.title);
2029            processLegacyAction(action, button);
2030            return button;
2031        }
2032
2033        /**
2034         * @return Whether we are currently building a notification from a legacy (an app that
2035         *         doesn't create quantum notifications by itself) app.
2036         */
2037        private boolean isLegacy() {
2038            return mLegacyNotificationUtil != null;
2039        }
2040
2041        private void processLegacyAction(Action action, RemoteViews button) {
2042            if (isLegacy()) {
2043                if (mLegacyNotificationUtil.isGrayscale(mContext, action.icon)) {
2044                    button.setTextViewCompoundDrawablesRelativeColorFilter(R.id.action0, 0,
2045                            mContext.getResources().getColor(
2046                                    R.color.notification_action_legacy_color_filter),
2047                            PorterDuff.Mode.MULTIPLY);
2048                }
2049            }
2050        }
2051
2052        private CharSequence processLegacyText(CharSequence charSequence) {
2053            if (isLegacy()) {
2054                return mLegacyNotificationUtil.invertCharSequenceColors(charSequence);
2055            } else {
2056                return charSequence;
2057            }
2058        }
2059
2060        private void processLegacyLargeIcon(int largeIconId, RemoteViews contentView) {
2061            if (isLegacy()) {
2062                processLegacyLargeIcon(
2063                        mLegacyNotificationUtil.isGrayscale(mContext, largeIconId),
2064                        contentView);
2065            }
2066        }
2067
2068        private void processLegacyLargeIcon(Bitmap largeIcon, RemoteViews contentView) {
2069            if (isLegacy()) {
2070                processLegacyLargeIcon(
2071                        mLegacyNotificationUtil.isGrayscale(largeIcon),
2072                        contentView);
2073            }
2074        }
2075
2076        private void processLegacyLargeIcon(boolean isGrayscale, RemoteViews contentView) {
2077            if (isLegacy() && isGrayscale) {
2078                contentView.setInt(R.id.icon, "setBackgroundResource",
2079                        R.drawable.notification_icon_legacy_bg_inset);
2080            }
2081        }
2082
2083        private void processLegacySmallIcon(int smallIconDrawableId, int smallIconImageViewId,
2084                RemoteViews contentView) {
2085            if (isLegacy()) {
2086                if (mLegacyNotificationUtil.isGrayscale(mContext, smallIconDrawableId)) {
2087                    contentView.setDrawableParameters(smallIconImageViewId, false, -1,
2088                            mContext.getResources().getColor(
2089                                    R.color.notification_action_legacy_color_filter),
2090                            PorterDuff.Mode.MULTIPLY, -1);
2091                }
2092            }
2093        }
2094
2095        /**
2096         * Apply the unstyled operations and return a new {@link Notification} object.
2097         * @hide
2098         */
2099        public Notification buildUnstyled() {
2100            Notification n = new Notification();
2101            n.when = mWhen;
2102            n.icon = mSmallIcon;
2103            n.iconLevel = mSmallIconLevel;
2104            n.number = mNumber;
2105            n.contentView = makeContentView();
2106            n.contentIntent = mContentIntent;
2107            n.deleteIntent = mDeleteIntent;
2108            n.fullScreenIntent = mFullScreenIntent;
2109            n.tickerText = mTickerText;
2110            n.tickerView = makeTickerView();
2111            n.largeIcon = mLargeIcon;
2112            n.sound = mSound;
2113            n.audioStreamType = mAudioStreamType;
2114            n.vibrate = mVibrate;
2115            n.ledARGB = mLedArgb;
2116            n.ledOnMS = mLedOnMs;
2117            n.ledOffMS = mLedOffMs;
2118            n.defaults = mDefaults;
2119            n.flags = mFlags;
2120            n.bigContentView = makeBigContentView();
2121            n.headsUpContentView = makeHeadsUpContentView();
2122            if (mLedOnMs != 0 || mLedOffMs != 0) {
2123                n.flags |= FLAG_SHOW_LIGHTS;
2124            }
2125            if ((mDefaults & DEFAULT_LIGHTS) != 0) {
2126                n.flags |= FLAG_SHOW_LIGHTS;
2127            }
2128            n.category = mCategory;
2129            n.priority = mPriority;
2130            if (mActions.size() > 0) {
2131                n.actions = new Action[mActions.size()];
2132                mActions.toArray(n.actions);
2133            }
2134            n.visibility = mVisibility;
2135
2136            if (mPublicVersion != null) {
2137                n.publicVersion = new Notification();
2138                mPublicVersion.cloneInto(n.publicVersion, true);
2139            }
2140
2141            return n;
2142        }
2143
2144        /**
2145         * Capture, in the provided bundle, semantic information used in the construction of
2146         * this Notification object.
2147         * @hide
2148         */
2149        public void populateExtras(Bundle extras) {
2150            // Store original information used in the construction of this object
2151            extras.putCharSequence(EXTRA_TITLE, mContentTitle);
2152            extras.putCharSequence(EXTRA_TEXT, mContentText);
2153            extras.putCharSequence(EXTRA_SUB_TEXT, mSubText);
2154            extras.putCharSequence(EXTRA_INFO_TEXT, mContentInfo);
2155            extras.putInt(EXTRA_SMALL_ICON, mSmallIcon);
2156            extras.putInt(EXTRA_PROGRESS, mProgress);
2157            extras.putInt(EXTRA_PROGRESS_MAX, mProgressMax);
2158            extras.putBoolean(EXTRA_PROGRESS_INDETERMINATE, mProgressIndeterminate);
2159            extras.putBoolean(EXTRA_SHOW_CHRONOMETER, mUseChronometer);
2160            extras.putBoolean(EXTRA_SHOW_WHEN, mShowWhen);
2161            if (mLargeIcon != null) {
2162                extras.putParcelable(EXTRA_LARGE_ICON, mLargeIcon);
2163            }
2164            if (!mPeople.isEmpty()) {
2165                extras.putStringArray(EXTRA_PEOPLE, mPeople.toArray(new String[mPeople.size()]));
2166            }
2167        }
2168
2169        /**
2170         * @deprecated Use {@link #build()} instead.
2171         */
2172        @Deprecated
2173        public Notification getNotification() {
2174            return build();
2175        }
2176
2177        /**
2178         * Combine all of the options that have been set and return a new {@link Notification}
2179         * object.
2180         */
2181        public Notification build() {
2182            Notification n = buildUnstyled();
2183
2184            if (mStyle != null) {
2185                n = mStyle.buildStyled(n);
2186            }
2187
2188            n.extras = mExtras != null ? new Bundle(mExtras) : new Bundle();
2189
2190            populateExtras(n.extras);
2191            if (mStyle != null) {
2192                mStyle.addExtras(n.extras);
2193            }
2194
2195            return n;
2196        }
2197
2198        /**
2199         * Apply this Builder to an existing {@link Notification} object.
2200         *
2201         * @hide
2202         */
2203        public Notification buildInto(Notification n) {
2204            build().cloneInto(n, true);
2205            return n;
2206        }
2207
2208
2209        private int getBaseLayoutResource() {
2210            return mQuantumTheme
2211                    ? R.layout.notification_template_quantum_base
2212                    : R.layout.notification_template_base;
2213        }
2214
2215        private int getBigBaseLayoutResource() {
2216            return mQuantumTheme
2217                    ? R.layout.notification_template_quantum_big_base
2218                    : R.layout.notification_template_big_base;
2219        }
2220
2221        private int getBigPictureLayoutResource() {
2222            return mQuantumTheme
2223                    ? R.layout.notification_template_quantum_big_picture
2224                    : R.layout.notification_template_big_picture;
2225        }
2226
2227        private int getBigTextLayoutResource() {
2228            return mQuantumTheme
2229                    ? R.layout.notification_template_quantum_big_text
2230                    : R.layout.notification_template_big_text;
2231        }
2232
2233        private int getInboxLayoutResource() {
2234            return mQuantumTheme
2235                    ? R.layout.notification_template_quantum_inbox
2236                    : R.layout.notification_template_inbox;
2237        }
2238
2239        private int getActionLayoutResource() {
2240            return mQuantumTheme
2241                    ? R.layout.notification_quantum_action
2242                    : R.layout.notification_action;
2243        }
2244
2245        private int getActionTombstoneLayoutResource() {
2246            return mQuantumTheme
2247                    ? R.layout.notification_quantum_action_tombstone
2248                    : R.layout.notification_action_tombstone;
2249        }
2250    }
2251
2252    /**
2253     * An object that can apply a rich notification style to a {@link Notification.Builder}
2254     * object.
2255     */
2256    public static abstract class Style {
2257        private CharSequence mBigContentTitle;
2258        private CharSequence mSummaryText = null;
2259        private boolean mSummaryTextSet = false;
2260
2261        protected Builder mBuilder;
2262
2263        /**
2264         * Overrides ContentTitle in the big form of the template.
2265         * This defaults to the value passed to setContentTitle().
2266         */
2267        protected void internalSetBigContentTitle(CharSequence title) {
2268            mBigContentTitle = title;
2269        }
2270
2271        /**
2272         * Set the first line of text after the detail section in the big form of the template.
2273         */
2274        protected void internalSetSummaryText(CharSequence cs) {
2275            mSummaryText = cs;
2276            mSummaryTextSet = true;
2277        }
2278
2279        public void setBuilder(Builder builder) {
2280            if (mBuilder != builder) {
2281                mBuilder = builder;
2282                if (mBuilder != null) {
2283                    mBuilder.setStyle(this);
2284                }
2285            }
2286        }
2287
2288        protected void checkBuilder() {
2289            if (mBuilder == null) {
2290                throw new IllegalArgumentException("Style requires a valid Builder object");
2291            }
2292        }
2293
2294        protected RemoteViews getStandardView(int layoutId) {
2295            checkBuilder();
2296
2297            if (mBigContentTitle != null) {
2298                mBuilder.setContentTitle(mBigContentTitle);
2299            }
2300
2301            RemoteViews contentView = mBuilder.applyStandardTemplateWithActions(layoutId);
2302
2303            if (mBigContentTitle != null && mBigContentTitle.equals("")) {
2304                contentView.setViewVisibility(R.id.line1, View.GONE);
2305            } else {
2306                contentView.setViewVisibility(R.id.line1, View.VISIBLE);
2307            }
2308
2309            // The last line defaults to the subtext, but can be replaced by mSummaryText
2310            final CharSequence overflowText =
2311                    mSummaryTextSet ? mSummaryText
2312                                    : mBuilder.mSubText;
2313            if (overflowText != null) {
2314                contentView.setTextViewText(R.id.text, mBuilder.processLegacyText(overflowText));
2315                contentView.setViewVisibility(R.id.overflow_divider, View.VISIBLE);
2316                contentView.setViewVisibility(R.id.line3, View.VISIBLE);
2317            } else {
2318                contentView.setViewVisibility(R.id.overflow_divider, View.GONE);
2319                contentView.setViewVisibility(R.id.line3, View.GONE);
2320            }
2321
2322            return contentView;
2323        }
2324
2325        /**
2326         * @hide
2327         */
2328        public void addExtras(Bundle extras) {
2329            if (mSummaryTextSet) {
2330                extras.putCharSequence(EXTRA_SUMMARY_TEXT, mSummaryText);
2331            }
2332            if (mBigContentTitle != null) {
2333                extras.putCharSequence(EXTRA_TITLE_BIG, mBigContentTitle);
2334            }
2335            extras.putString(EXTRA_TEMPLATE, this.getClass().getName());
2336        }
2337
2338        /**
2339         * @hide
2340         */
2341        public abstract Notification buildStyled(Notification wip);
2342
2343        /**
2344         * Calls {@link android.app.Notification.Builder#build()} on the Builder this Style is
2345         * attached to.
2346         *
2347         * @return the fully constructed Notification.
2348         */
2349        public Notification build() {
2350            checkBuilder();
2351            return mBuilder.build();
2352        }
2353    }
2354
2355    /**
2356     * Helper class for generating large-format notifications that include a large image attachment.
2357     *
2358     * This class is a "rebuilder": It consumes a Builder object and modifies its behavior, like so:
2359     * <pre class="prettyprint">
2360     * Notification noti = new Notification.BigPictureStyle(
2361     *      new Notification.Builder()
2362     *         .setContentTitle(&quot;New photo from &quot; + sender.toString())
2363     *         .setContentText(subject)
2364     *         .setSmallIcon(R.drawable.new_post)
2365     *         .setLargeIcon(aBitmap))
2366     *      .bigPicture(aBigBitmap)
2367     *      .build();
2368     * </pre>
2369     *
2370     * @see Notification#bigContentView
2371     */
2372    public static class BigPictureStyle extends Style {
2373        private Bitmap mPicture;
2374        private Bitmap mBigLargeIcon;
2375        private boolean mBigLargeIconSet = false;
2376
2377        public BigPictureStyle() {
2378        }
2379
2380        public BigPictureStyle(Builder builder) {
2381            setBuilder(builder);
2382        }
2383
2384        /**
2385         * Overrides ContentTitle in the big form of the template.
2386         * This defaults to the value passed to setContentTitle().
2387         */
2388        public BigPictureStyle setBigContentTitle(CharSequence title) {
2389            internalSetBigContentTitle(safeCharSequence(title));
2390            return this;
2391        }
2392
2393        /**
2394         * Set the first line of text after the detail section in the big form of the template.
2395         */
2396        public BigPictureStyle setSummaryText(CharSequence cs) {
2397            internalSetSummaryText(safeCharSequence(cs));
2398            return this;
2399        }
2400
2401        /**
2402         * Provide the bitmap to be used as the payload for the BigPicture notification.
2403         */
2404        public BigPictureStyle bigPicture(Bitmap b) {
2405            mPicture = b;
2406            return this;
2407        }
2408
2409        /**
2410         * Override the large icon when the big notification is shown.
2411         */
2412        public BigPictureStyle bigLargeIcon(Bitmap b) {
2413            mBigLargeIconSet = true;
2414            mBigLargeIcon = b;
2415            return this;
2416        }
2417
2418        private RemoteViews makeBigContentView() {
2419            RemoteViews contentView = getStandardView(mBuilder.getBigPictureLayoutResource());
2420
2421            contentView.setImageViewBitmap(R.id.big_picture, mPicture);
2422
2423            return contentView;
2424        }
2425
2426        /**
2427         * @hide
2428         */
2429        public void addExtras(Bundle extras) {
2430            super.addExtras(extras);
2431
2432            if (mBigLargeIconSet) {
2433                extras.putParcelable(EXTRA_LARGE_ICON_BIG, mBigLargeIcon);
2434            }
2435            extras.putParcelable(EXTRA_PICTURE, mPicture);
2436        }
2437
2438        /**
2439         * @hide
2440         */
2441        @Override
2442        public Notification buildStyled(Notification wip) {
2443            if (mBigLargeIconSet ) {
2444                mBuilder.mLargeIcon = mBigLargeIcon;
2445            }
2446            wip.bigContentView = makeBigContentView();
2447            return wip;
2448        }
2449    }
2450
2451    /**
2452     * Helper class for generating large-format notifications that include a lot of text.
2453     *
2454     * This class is a "rebuilder": It consumes a Builder object and modifies its behavior, like so:
2455     * <pre class="prettyprint">
2456     * Notification noti = new Notification.BigTextStyle(
2457     *      new Notification.Builder()
2458     *         .setContentTitle(&quot;New mail from &quot; + sender.toString())
2459     *         .setContentText(subject)
2460     *         .setSmallIcon(R.drawable.new_mail)
2461     *         .setLargeIcon(aBitmap))
2462     *      .bigText(aVeryLongString)
2463     *      .build();
2464     * </pre>
2465     *
2466     * @see Notification#bigContentView
2467     */
2468    public static class BigTextStyle extends Style {
2469        private CharSequence mBigText;
2470
2471        public BigTextStyle() {
2472        }
2473
2474        public BigTextStyle(Builder builder) {
2475            setBuilder(builder);
2476        }
2477
2478        /**
2479         * Overrides ContentTitle in the big form of the template.
2480         * This defaults to the value passed to setContentTitle().
2481         */
2482        public BigTextStyle setBigContentTitle(CharSequence title) {
2483            internalSetBigContentTitle(safeCharSequence(title));
2484            return this;
2485        }
2486
2487        /**
2488         * Set the first line of text after the detail section in the big form of the template.
2489         */
2490        public BigTextStyle setSummaryText(CharSequence cs) {
2491            internalSetSummaryText(safeCharSequence(cs));
2492            return this;
2493        }
2494
2495        /**
2496         * Provide the longer text to be displayed in the big form of the
2497         * template in place of the content text.
2498         */
2499        public BigTextStyle bigText(CharSequence cs) {
2500            mBigText = safeCharSequence(cs);
2501            return this;
2502        }
2503
2504        /**
2505         * @hide
2506         */
2507        public void addExtras(Bundle extras) {
2508            super.addExtras(extras);
2509
2510            extras.putCharSequence(EXTRA_TEXT, mBigText);
2511        }
2512
2513        private RemoteViews makeBigContentView() {
2514            // Remove the content text so line3 only shows if you have a summary
2515            final boolean hadThreeLines = (mBuilder.mContentText != null && mBuilder.mSubText != null);
2516            mBuilder.mContentText = null;
2517
2518            RemoteViews contentView = getStandardView(mBuilder.getBigTextLayoutResource());
2519
2520            if (hadThreeLines) {
2521                // vertical centering
2522                contentView.setViewPadding(R.id.line1, 0, 0, 0, 0);
2523            }
2524
2525            contentView.setTextViewText(R.id.big_text, mBuilder.processLegacyText(mBigText));
2526            contentView.setViewVisibility(R.id.big_text, View.VISIBLE);
2527            contentView.setViewVisibility(R.id.text2, View.GONE);
2528
2529            return contentView;
2530        }
2531
2532        /**
2533         * @hide
2534         */
2535        @Override
2536        public Notification buildStyled(Notification wip) {
2537            wip.bigContentView = makeBigContentView();
2538
2539            wip.extras.putCharSequence(EXTRA_TEXT, mBigText);
2540
2541            return wip;
2542        }
2543    }
2544
2545    /**
2546     * Helper class for generating large-format notifications that include a list of (up to 5) strings.
2547     *
2548     * This class is a "rebuilder": It consumes a Builder object and modifies its behavior, like so:
2549     * <pre class="prettyprint">
2550     * Notification noti = new Notification.InboxStyle(
2551     *      new Notification.Builder()
2552     *         .setContentTitle(&quot;5 New mails from &quot; + sender.toString())
2553     *         .setContentText(subject)
2554     *         .setSmallIcon(R.drawable.new_mail)
2555     *         .setLargeIcon(aBitmap))
2556     *      .addLine(str1)
2557     *      .addLine(str2)
2558     *      .setContentTitle("")
2559     *      .setSummaryText(&quot;+3 more&quot;)
2560     *      .build();
2561     * </pre>
2562     *
2563     * @see Notification#bigContentView
2564     */
2565    public static class InboxStyle extends Style {
2566        private ArrayList<CharSequence> mTexts = new ArrayList<CharSequence>(5);
2567
2568        public InboxStyle() {
2569        }
2570
2571        public InboxStyle(Builder builder) {
2572            setBuilder(builder);
2573        }
2574
2575        /**
2576         * Overrides ContentTitle in the big form of the template.
2577         * This defaults to the value passed to setContentTitle().
2578         */
2579        public InboxStyle setBigContentTitle(CharSequence title) {
2580            internalSetBigContentTitle(safeCharSequence(title));
2581            return this;
2582        }
2583
2584        /**
2585         * Set the first line of text after the detail section in the big form of the template.
2586         */
2587        public InboxStyle setSummaryText(CharSequence cs) {
2588            internalSetSummaryText(safeCharSequence(cs));
2589            return this;
2590        }
2591
2592        /**
2593         * Append a line to the digest section of the Inbox notification.
2594         */
2595        public InboxStyle addLine(CharSequence cs) {
2596            mTexts.add(safeCharSequence(cs));
2597            return this;
2598        }
2599
2600        /**
2601         * @hide
2602         */
2603        public void addExtras(Bundle extras) {
2604            super.addExtras(extras);
2605            CharSequence[] a = new CharSequence[mTexts.size()];
2606            extras.putCharSequenceArray(EXTRA_TEXT_LINES, mTexts.toArray(a));
2607        }
2608
2609        private RemoteViews makeBigContentView() {
2610            // Remove the content text so line3 disappears unless you have a summary
2611            mBuilder.mContentText = null;
2612            RemoteViews contentView = getStandardView(mBuilder.getInboxLayoutResource());
2613
2614            contentView.setViewVisibility(R.id.text2, View.GONE);
2615
2616            int[] rowIds = {R.id.inbox_text0, R.id.inbox_text1, R.id.inbox_text2, R.id.inbox_text3,
2617                    R.id.inbox_text4, R.id.inbox_text5, R.id.inbox_text6};
2618
2619            // Make sure all rows are gone in case we reuse a view.
2620            for (int rowId : rowIds) {
2621                contentView.setViewVisibility(rowId, View.GONE);
2622            }
2623
2624
2625            int i=0;
2626            while (i < mTexts.size() && i < rowIds.length) {
2627                CharSequence str = mTexts.get(i);
2628                if (str != null && !str.equals("")) {
2629                    contentView.setViewVisibility(rowIds[i], View.VISIBLE);
2630                    contentView.setTextViewText(rowIds[i], mBuilder.processLegacyText(str));
2631                }
2632                i++;
2633            }
2634
2635            contentView.setViewVisibility(R.id.inbox_end_pad,
2636                    mTexts.size() > 0 ? View.VISIBLE : View.GONE);
2637
2638            contentView.setViewVisibility(R.id.inbox_more,
2639                    mTexts.size() > rowIds.length ? View.VISIBLE : View.GONE);
2640
2641            return contentView;
2642        }
2643
2644        /**
2645         * @hide
2646         */
2647        @Override
2648        public Notification buildStyled(Notification wip) {
2649            wip.bigContentView = makeBigContentView();
2650
2651            return wip;
2652        }
2653    }
2654}
2655