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