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