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