Notification.java revision 6f72ac5d5f4b7bae34bb3dab7821f3dbcbf02bcd
1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.app;
18
19import android.content.Context;
20import android.content.Intent;
21import android.content.res.Resources;
22import android.graphics.Bitmap;
23import android.media.AudioManager;
24import android.net.Uri;
25import android.os.BadParcelableException;
26import android.os.Bundle;
27import android.os.Parcel;
28import android.os.Parcelable;
29import android.os.SystemClock;
30import android.os.UserHandle;
31import android.text.TextUtils;
32import android.util.Log;
33import android.util.TypedValue;
34import android.view.Gravity;
35import android.view.View;
36import android.widget.ProgressBar;
37import android.widget.RemoteViews;
38
39import com.android.internal.R;
40
41import java.text.NumberFormat;
42import java.util.ArrayList;
43import java.util.Arrays;
44import java.util.Collections;
45import java.util.List;
46
47/**
48 * A class that represents how a persistent notification is to be presented to
49 * the user using the {@link android.app.NotificationManager}.
50 *
51 * <p>The {@link Notification.Builder Notification.Builder} has been added to make it
52 * easier to construct Notifications.</p>
53 *
54 * <div class="special reference">
55 * <h3>Developer Guides</h3>
56 * <p>For a guide to creating notifications, read the
57 * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a>
58 * developer guide.</p>
59 * </div>
60 */
61public class Notification implements Parcelable
62{
63    private static final String TAG = "Notification";
64
65    /**
66     * Use all default values (where applicable).
67     */
68    public static final int DEFAULT_ALL = ~0;
69
70    /**
71     * Use the default notification sound. This will ignore any given
72     * {@link #sound}.
73     *
74
75     * @see #defaults
76     */
77
78    public static final int DEFAULT_SOUND = 1;
79
80    /**
81     * Use the default notification vibrate. This will ignore any given
82     * {@link #vibrate}. Using phone vibration requires the
83     * {@link android.Manifest.permission#VIBRATE VIBRATE} permission.
84     *
85     * @see #defaults
86     */
87
88    public static final int DEFAULT_VIBRATE = 2;
89
90    /**
91     * Use the default notification lights. This will ignore the
92     * {@link #FLAG_SHOW_LIGHTS} bit, and {@link #ledARGB}, {@link #ledOffMS}, or
93     * {@link #ledOnMS}.
94     *
95     * @see #defaults
96     */
97
98    public static final int DEFAULT_LIGHTS = 4;
99
100    /**
101     * A timestamp related to this notification, in milliseconds since the epoch.
102     *
103     * Default value: {@link System#currentTimeMillis() Now}.
104     *
105     * Choose a timestamp that will be most relevant to the user. For most finite events, this
106     * corresponds to the time the event happened (or will happen, in the case of events that have
107     * yet to occur but about which the user is being informed). Indefinite events should be
108     * timestamped according to when the activity began.
109     *
110     * Some examples:
111     *
112     * <ul>
113     *   <li>Notification of a new chat message should be stamped when the message was received.</li>
114     *   <li>Notification of an ongoing file download (with a progress bar, for example) should be stamped when the download started.</li>
115     *   <li>Notification of a completed file download should be stamped when the download finished.</li>
116     *   <li>Notification of an upcoming meeting should be stamped with the time the meeting will begin (that is, in the future).</li>
117     *   <li>Notification of an ongoing stopwatch (increasing timer) should be stamped with the watch's start time.
118     *   <li>Notification of an ongoing countdown timer should be stamped with the timer's end time.
119     * </ul>
120     *
121     */
122    public long when;
123
124    /**
125     * The resource id of a drawable to use as the icon in the status bar.
126     * This is required; notifications with an invalid icon resource will not be shown.
127     */
128    public int icon;
129
130    /**
131     * If the icon in the status bar is to have more than one level, you can set this.  Otherwise,
132     * leave it at its default value of 0.
133     *
134     * @see android.widget.ImageView#setImageLevel
135     * @see android.graphics.drawable.Drawable#setLevel
136     */
137    public int iconLevel;
138
139    /**
140     * The number of events that this notification represents. For example, in a new mail
141     * notification, this could be the number of unread messages.
142     *
143     * The system may or may not use this field to modify the appearance of the notification. For
144     * example, before {@link android.os.Build.VERSION_CODES#HONEYCOMB}, this number was
145     * superimposed over the icon in the status bar. Starting with
146     * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, the template used by
147     * {@link Notification.Builder} has displayed the number in the expanded notification view.
148     *
149     * If the number is 0 or negative, it is never shown.
150     */
151    public int number;
152
153    /**
154     * The intent to execute when the expanded status entry is clicked.  If
155     * this is an activity, it must include the
156     * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires
157     * that you take care of task management as described in the
158     * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back
159     * Stack</a> document.  In particular, make sure to read the notification section
160     * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html#HandlingNotifications">Handling
161     * Notifications</a> for the correct ways to launch an application from a
162     * notification.
163     */
164    public PendingIntent contentIntent;
165
166    /**
167     * The intent to execute when the notification is explicitly dismissed by the user, either with
168     * the "Clear All" button or by swiping it away individually.
169     *
170     * This probably shouldn't be launching an activity since several of those will be sent
171     * at the same time.
172     */
173    public PendingIntent deleteIntent;
174
175    /**
176     * An intent to launch instead of posting the notification to the status bar.
177     *
178     * @see Notification.Builder#setFullScreenIntent
179     */
180    public PendingIntent fullScreenIntent;
181
182    /**
183     * Text to scroll across the screen when this item is added to
184     * the status bar on large and smaller devices.
185     *
186     * @see #tickerView
187     */
188    public CharSequence tickerText;
189
190    /**
191     * The view to show as the ticker in the status bar when the notification
192     * is posted.
193     */
194    public RemoteViews tickerView;
195
196    /**
197     * The view that will represent this notification in the expanded status bar.
198     */
199    public RemoteViews contentView;
200
201    /**
202     * A large-format version of {@link #contentView}, giving the Notification an
203     * opportunity to show more detail. The system UI may choose to show this
204     * instead of the normal content view at its discretion.
205     */
206    public RemoteViews bigContentView;
207
208    /**
209     * The bitmap that may escape the bounds of the panel and bar.
210     */
211    public Bitmap largeIcon;
212
213    /**
214     * The sound to play.
215     *
216     * <p>
217     * To play the default notification sound, see {@link #defaults}.
218     * </p>
219     */
220    public Uri sound;
221
222    /**
223     * Use this constant as the value for audioStreamType to request that
224     * the default stream type for notifications be used.  Currently the
225     * default stream type is {@link AudioManager#STREAM_NOTIFICATION}.
226     */
227    public static final int STREAM_DEFAULT = -1;
228
229    /**
230     * The audio stream type to use when playing the sound.
231     * Should be one of the STREAM_ constants from
232     * {@link android.media.AudioManager}.
233     */
234    public int audioStreamType = STREAM_DEFAULT;
235
236    /**
237     * The pattern with which to vibrate.
238     *
239     * <p>
240     * To vibrate the default pattern, see {@link #defaults}.
241     * </p>
242     *
243     * @see android.os.Vibrator#vibrate(long[],int)
244     */
245    public long[] vibrate;
246
247    /**
248     * The color of the led.  The hardware will do its best approximation.
249     *
250     * @see #FLAG_SHOW_LIGHTS
251     * @see #flags
252     */
253    public int ledARGB;
254
255    /**
256     * The number of milliseconds for the LED to be on while it's flashing.
257     * The hardware will do its best approximation.
258     *
259     * @see #FLAG_SHOW_LIGHTS
260     * @see #flags
261     */
262    public int ledOnMS;
263
264    /**
265     * The number of milliseconds for the LED to be off while it's flashing.
266     * The hardware will do its best approximation.
267     *
268     * @see #FLAG_SHOW_LIGHTS
269     * @see #flags
270     */
271    public int ledOffMS;
272
273    /**
274     * Specifies which values should be taken from the defaults.
275     * <p>
276     * To set, OR the desired from {@link #DEFAULT_SOUND},
277     * {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}. For all default
278     * values, use {@link #DEFAULT_ALL}.
279     * </p>
280     */
281    public int defaults;
282
283    /**
284     * Bit to be bitwise-ored into the {@link #flags} field that should be
285     * set if you want the LED on for this notification.
286     * <ul>
287     * <li>To turn the LED off, pass 0 in the alpha channel for colorARGB
288     *      or 0 for both ledOnMS and ledOffMS.</li>
289     * <li>To turn the LED on, pass 1 for ledOnMS and 0 for ledOffMS.</li>
290     * <li>To flash the LED, pass the number of milliseconds that it should
291     *      be on and off to ledOnMS and ledOffMS.</li>
292     * </ul>
293     * <p>
294     * Since hardware varies, you are not guaranteed that any of the values
295     * you pass are honored exactly.  Use the system defaults (TODO) if possible
296     * because they will be set to values that work on any given hardware.
297     * <p>
298     * The alpha channel must be set for forward compatibility.
299     *
300     */
301    public static final int FLAG_SHOW_LIGHTS        = 0x00000001;
302
303    /**
304     * Bit to be bitwise-ored into the {@link #flags} field that should be
305     * set if this notification is in reference to something that is ongoing,
306     * like a phone call.  It should not be set if this notification is in
307     * reference to something that happened at a particular point in time,
308     * like a missed phone call.
309     */
310    public static final int FLAG_ONGOING_EVENT      = 0x00000002;
311
312    /**
313     * Bit to be bitwise-ored into the {@link #flags} field that if set,
314     * the audio will be repeated until the notification is
315     * cancelled or the notification window is opened.
316     */
317    public static final int FLAG_INSISTENT          = 0x00000004;
318
319    /**
320     * Bit to be bitwise-ored into the {@link #flags} field that should be
321     * set if you would only like the sound, vibrate and ticker to be played
322     * if the notification was not already showing.
323     */
324    public static final int FLAG_ONLY_ALERT_ONCE    = 0x00000008;
325
326    /**
327     * Bit to be bitwise-ored into the {@link #flags} field that should be
328     * set if the notification should be canceled when it is clicked by the
329     * user.
330
331     */
332    public static final int FLAG_AUTO_CANCEL        = 0x00000010;
333
334    /**
335     * Bit to be bitwise-ored into the {@link #flags} field that should be
336     * set if the notification should not be canceled when the user clicks
337     * the Clear all button.
338     */
339    public static final int FLAG_NO_CLEAR           = 0x00000020;
340
341    /**
342     * Bit to be bitwise-ored into the {@link #flags} field that should be
343     * set if this notification represents a currently running service.  This
344     * will normally be set for you by {@link Service#startForeground}.
345     */
346    public static final int FLAG_FOREGROUND_SERVICE = 0x00000040;
347
348    /**
349     * Obsolete flag indicating high-priority notifications; use the priority field instead.
350     *
351     * @deprecated Use {@link #priority} with a positive value.
352     */
353    public static final int FLAG_HIGH_PRIORITY      = 0x00000080;
354
355    /**
356     * Bit to be bitswise-ored into the {@link #flags} field that should be
357     * set if this notification is relevant to the current device only
358     * and it is not recommended that it bridge to other devices.
359     */
360    public static final int FLAG_LOCAL_ONLY         = 0x00000100;
361
362    /**
363     * Bit to be bitswise-ored into the {@link #flags} field that should be
364     * set if this notification is the group summary for a group of notifications.
365     * Grouped notifications may display in a cluster or stack on devices which
366     * support such rendering. Requires a group key also be set using {@link Builder#setGroup}.
367     */
368    public static final int FLAG_GROUP_SUMMARY      = 0x00000200;
369
370    public int flags;
371
372    /**
373     * Default notification {@link #priority}. If your application does not prioritize its own
374     * notifications, use this value for all notifications.
375     */
376    public static final int PRIORITY_DEFAULT = 0;
377
378    /**
379     * Lower {@link #priority}, for items that are less important. The UI may choose to show these
380     * items smaller, or at a different position in the list, compared with your app's
381     * {@link #PRIORITY_DEFAULT} items.
382     */
383    public static final int PRIORITY_LOW = -1;
384
385    /**
386     * Lowest {@link #priority}; these items might not be shown to the user except under special
387     * circumstances, such as detailed notification logs.
388     */
389    public static final int PRIORITY_MIN = -2;
390
391    /**
392     * Higher {@link #priority}, for more important notifications or alerts. The UI may choose to
393     * show these items larger, or at a different position in notification lists, compared with
394     * your app's {@link #PRIORITY_DEFAULT} items.
395     */
396    public static final int PRIORITY_HIGH = 1;
397
398    /**
399     * Highest {@link #priority}, for your application's most important items that require the
400     * user's prompt attention or input.
401     */
402    public static final int PRIORITY_MAX = 2;
403
404    /**
405     * Relative priority for this notification.
406     *
407     * Priority is an indication of how much of the user's valuable attention should be consumed by
408     * this notification. Low-priority notifications may be hidden from the user in certain
409     * situations, while the user might be interrupted for a higher-priority notification. The
410     * system will make a determination about how to interpret this priority when presenting
411     * the notification.
412     */
413    public int priority;
414
415    /**
416     * Notification category: incoming call (voice or video) or similar synchronous communication request.
417     * @hide
418     */
419    public static final String CATEGORY_CALL = "call";
420
421    /**
422     * Notification category: incoming direct message (SMS, instant message, etc.).
423     * @hide
424     */
425    public static final String CATEGORY_MESSAGE = "msg";
426
427    /**
428     * Notification category: asynchronous bulk message (email).
429     * @hide
430     */
431    public static final String CATEGORY_EMAIL = "email";
432
433    /**
434     * Notification category: calendar event.
435     * @hide
436     */
437    public static final String CATEGORY_EVENT = "event";
438
439    /**
440     * Notification category: promotion or advertisement.
441     * @hide
442     */
443    public static final String CATEGORY_PROMO = "promo";
444
445    /**
446     * Notification category: alarm or timer.
447     * @hide
448     */
449    public static final String CATEGORY_ALARM = "alarm";
450
451    /**
452     * Notification category: progress of a long-running background operation.
453     * @hide
454     */
455    public static final String CATEGORY_PROGRESS = "progress";
456
457    /**
458     * Notification category: social network or sharing update.
459     * @hide
460     */
461    public static final String CATEGORY_SOCIAL = "social";
462
463    /**
464     * Notification category: error in background operation or authentication status.
465     * @hide
466     */
467    public static final String CATEGORY_ERROR = "err";
468
469    /**
470     * Notification category: media transport control for playback.
471     * @hide
472     */
473    public static final String CATEGORY_TRANSPORT = "transport";
474
475    /**
476     * Notification category: system or device status update.  Reserved for system use.
477     * @hide
478     */
479    public static final String CATEGORY_SYSTEM = "sys";
480
481    /**
482     * Notification category: indication of running background service.
483     * @hide
484     */
485    public static final String CATEGORY_SERVICE = "service";
486
487    /**
488     * Notification category: a specific, timely recommendation for a single thing.
489     * For example, a news app might want to recommend a news story it believes the user will
490     * want to read next.
491     * @hide
492     */
493    public static final String CATEGORY_RECOMMENDATION = "recommendation";
494
495    /**
496     * Notification category: ongoing information about device or contextual status.
497     * @hide
498     */
499    public static final String CATEGORY_STATUS = "status";
500
501    /**
502     * One of the predefined notification categories (see the <code>CATEGORY_*</code> constants)
503     * that best describes this Notification.  May be used by the system for ranking and filtering.
504     * @hide
505     */
506    public String category;
507
508    private String mGroupKey;
509
510    /**
511     * Get the key used to group this notification into a cluster or stack
512     * with other notifications on devices which support such rendering.
513     */
514    public String getGroup() {
515        return mGroupKey;
516    }
517
518    private String mSortKey;
519
520    /**
521     * Get a sort key that orders this notification among other notifications from the
522     * same package. This can be useful if an external sort was already applied and an app
523     * would like to preserve this. Notifications will be sorted lexicographically using this
524     * value, although providing different priorities in addition to providing sort key may
525     * cause this value to be ignored.
526     *
527     * <p>This sort key can also be used to order members of a notification group. See
528     * {@link Builder#setGroup}.
529     *
530     * @see String#compareTo(String)
531     */
532    public String getSortKey() {
533        return mSortKey;
534    }
535
536    /**
537     * Additional semantic data to be carried around with this Notification.
538     * <p>
539     * The extras keys defined here are intended to capture the original inputs to {@link Builder}
540     * APIs, and are intended to be used by
541     * {@link android.service.notification.NotificationListenerService} implementations to extract
542     * detailed information from notification objects.
543     */
544    public Bundle extras = new Bundle();
545
546    /**
547     * {@link #extras} key: this is the title of the notification,
548     * as supplied to {@link Builder#setContentTitle(CharSequence)}.
549     */
550    public static final String EXTRA_TITLE = "android.title";
551
552    /**
553     * {@link #extras} key: this is the title of the notification when shown in expanded form,
554     * e.g. as supplied to {@link BigTextStyle#setBigContentTitle(CharSequence)}.
555     */
556    public static final String EXTRA_TITLE_BIG = EXTRA_TITLE + ".big";
557
558    /**
559     * {@link #extras} key: this is the main text payload, as supplied to
560     * {@link Builder#setContentText(CharSequence)}.
561     */
562    public static final String EXTRA_TEXT = "android.text";
563
564    /**
565     * {@link #extras} key: this is a third line of text, as supplied to
566     * {@link Builder#setSubText(CharSequence)}.
567     */
568    public static final String EXTRA_SUB_TEXT = "android.subText";
569
570    /**
571     * {@link #extras} key: this is a small piece of additional text as supplied to
572     * {@link Builder#setContentInfo(CharSequence)}.
573     */
574    public static final String EXTRA_INFO_TEXT = "android.infoText";
575
576    /**
577     * {@link #extras} key: this is a line of summary information intended to be shown
578     * alongside expanded notifications, as supplied to (e.g.)
579     * {@link BigTextStyle#setSummaryText(CharSequence)}.
580     */
581    public static final String EXTRA_SUMMARY_TEXT = "android.summaryText";
582
583    /**
584     * {@link #extras} key: this is the resource ID of the notification's main small icon, as
585     * supplied to {@link Builder#setSmallIcon(int)}.
586     */
587    public static final String EXTRA_SMALL_ICON = "android.icon";
588
589    /**
590     * {@link #extras} key: this is a bitmap to be used instead of the small icon when showing the
591     * notification payload, as
592     * supplied to {@link Builder#setLargeIcon(android.graphics.Bitmap)}.
593     */
594    public static final String EXTRA_LARGE_ICON = "android.largeIcon";
595
596    /**
597     * {@link #extras} key: this is a bitmap to be used instead of the one from
598     * {@link Builder#setLargeIcon(android.graphics.Bitmap)} when the notification is
599     * shown in its expanded form, as supplied to
600     * {@link BigPictureStyle#bigLargeIcon(android.graphics.Bitmap)}.
601     */
602    public static final String EXTRA_LARGE_ICON_BIG = EXTRA_LARGE_ICON + ".big";
603
604    /**
605     * {@link #extras} key: this is the progress value supplied to
606     * {@link Builder#setProgress(int, int, boolean)}.
607     */
608    public static final String EXTRA_PROGRESS = "android.progress";
609
610    /**
611     * {@link #extras} key: this is the maximum value supplied to
612     * {@link Builder#setProgress(int, int, boolean)}.
613     */
614    public static final String EXTRA_PROGRESS_MAX = "android.progressMax";
615
616    /**
617     * {@link #extras} key: whether the progress bar is indeterminate, supplied to
618     * {@link Builder#setProgress(int, int, boolean)}.
619     */
620    public static final String EXTRA_PROGRESS_INDETERMINATE = "android.progressIndeterminate";
621
622    /**
623     * {@link #extras} key: whether {@link #when} should be shown as a count-up timer (specifically
624     * a {@link android.widget.Chronometer}) instead of a timestamp, as supplied to
625     * {@link Builder#setUsesChronometer(boolean)}.
626     */
627    public static final String EXTRA_SHOW_CHRONOMETER = "android.showChronometer";
628
629    /**
630     * {@link #extras} key: whether {@link #when} should be shown,
631     * as supplied to {@link Builder#setShowWhen(boolean)}.
632     */
633    public static final String EXTRA_SHOW_WHEN = "android.showWhen";
634
635    /**
636     * {@link #extras} key: this is a bitmap to be shown in {@link BigPictureStyle} expanded
637     * notifications, supplied to {@link BigPictureStyle#bigPicture(android.graphics.Bitmap)}.
638     */
639    public static final String EXTRA_PICTURE = "android.picture";
640
641    /**
642     * {@link #extras} key: An array of CharSequences to show in {@link InboxStyle} expanded
643     * notifications, each of which was supplied to {@link InboxStyle#addLine(CharSequence)}.
644     */
645    public static final String EXTRA_TEXT_LINES = "android.textLines";
646
647    /**
648     * {@link #extras} key: An array of people that this notification relates to, specified
649     * by contacts provider contact URI.
650     */
651    public static final String EXTRA_PEOPLE = "android.people";
652
653    /**
654     * @hide
655     * Extra added by NotificationManagerService to indicate whether a NotificationScorer
656     * modified the Notifications's score.
657     */
658    public static final String EXTRA_SCORE_MODIFIED = "android.scoreModified";
659
660    /**
661     * Not used.
662     * @hide
663     */
664    public static final String EXTRA_AS_HEADS_UP = "headsup";
665
666    /**
667     * Allow certain system-generated notifications to appear before the device is provisioned.
668     * Only available to notifications coming from the android package.
669     * @hide
670     */
671    public static final String EXTRA_ALLOW_DURING_SETUP = "android.allowDuringSetup";
672
673    /**
674     * Value for {@link #EXTRA_AS_HEADS_UP}.
675     * @hide
676     */
677    public static final int HEADS_UP_NEVER = 0;
678
679    /**
680     * Default value for {@link #EXTRA_AS_HEADS_UP}.
681     * @hide
682     */
683    public static final int HEADS_UP_ALLOWED = 1;
684
685    /**
686     * Value for {@link #EXTRA_AS_HEADS_UP}.
687     * @hide
688     */
689    public static final int HEADS_UP_REQUESTED = 2;
690
691    /**
692     * Structure to encapsulate a named action that can be shown as part of this notification.
693     * It must include an icon, a label, and a {@link PendingIntent} to be fired when the action is
694     * selected by the user.
695     * <p>
696     * Apps should use {@link Notification.Builder#addAction(int, CharSequence, PendingIntent)}
697     * or {@link Notification.Builder#addAction(Notification.Action)}
698     * to attach actions.
699     */
700    public static class Action implements Parcelable {
701        private final Bundle mExtras;
702        private final RemoteInput[] mRemoteInputs;
703
704        /**
705         * Small icon representing the action.
706         */
707        public int icon;
708
709        /**
710         * Title of the action.
711         */
712        public CharSequence title;
713
714        /**
715         * Intent to send when the user invokes this action. May be null, in which case the action
716         * may be rendered in a disabled presentation by the system UI.
717         */
718        public PendingIntent actionIntent;
719
720        private Action(Parcel in) {
721            icon = in.readInt();
722            title = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
723            if (in.readInt() == 1) {
724                actionIntent = PendingIntent.CREATOR.createFromParcel(in);
725            }
726            mExtras = in.readBundle();
727            mRemoteInputs = in.createTypedArray(RemoteInput.CREATOR);
728        }
729
730        /**
731         * Use {@link Notification.Builder#addAction(int, CharSequence, PendingIntent)}.
732         */
733        public Action(int icon, CharSequence title, PendingIntent intent) {
734            this(icon, title, intent, new Bundle(), null);
735        }
736
737        private Action(int icon, CharSequence title, PendingIntent intent, Bundle extras,
738                RemoteInput[] remoteInputs) {
739            this.icon = icon;
740            this.title = title;
741            this.actionIntent = intent;
742            this.mExtras = extras != null ? extras : new Bundle();
743            this.mRemoteInputs = remoteInputs;
744        }
745
746        /**
747         * Get additional metadata carried around with this Action.
748         */
749        public Bundle getExtras() {
750            return mExtras;
751        }
752
753        /**
754         * Get the list of inputs to be collected from the user when this action is sent.
755         * May return null if no remote inputs were added.
756         */
757        public RemoteInput[] getRemoteInputs() {
758            return mRemoteInputs;
759        }
760
761        /**
762         * Builder class for {@link Action} objects.
763         */
764        public static final class Builder {
765            private final int mIcon;
766            private final CharSequence mTitle;
767            private final PendingIntent mIntent;
768            private final Bundle mExtras;
769            private ArrayList<RemoteInput> mRemoteInputs;
770
771            /**
772             * Construct a new builder for {@link Action} object.
773             * @param icon icon to show for this action
774             * @param title the title of the action
775             * @param intent the {@link PendingIntent} to fire when users trigger this action
776             */
777            public Builder(int icon, CharSequence title, PendingIntent intent) {
778                this(icon, title, intent, new Bundle(), null);
779            }
780
781            /**
782             * Construct a new builder for {@link Action} object using the fields from an
783             * {@link Action}.
784             * @param action the action to read fields from.
785             */
786            public Builder(Action action) {
787                this(action.icon, action.title, action.actionIntent, new Bundle(action.mExtras),
788                        action.getRemoteInputs());
789            }
790
791            private Builder(int icon, CharSequence title, PendingIntent intent, Bundle extras,
792                    RemoteInput[] remoteInputs) {
793                mIcon = icon;
794                mTitle = title;
795                mIntent = intent;
796                mExtras = extras;
797                if (remoteInputs != null) {
798                    mRemoteInputs = new ArrayList<RemoteInput>(remoteInputs.length);
799                    Collections.addAll(mRemoteInputs, remoteInputs);
800                }
801            }
802
803            /**
804             * Merge additional metadata into this builder.
805             *
806             * <p>Values within the Bundle will replace existing extras values in this Builder.
807             *
808             * @see Notification.Action#extras
809             */
810            public Builder addExtras(Bundle extras) {
811                if (extras != null) {
812                    mExtras.putAll(extras);
813                }
814                return this;
815            }
816
817            /**
818             * Get the metadata Bundle used by this Builder.
819             *
820             * <p>The returned Bundle is shared with this Builder.
821             */
822            public Bundle getExtras() {
823                return mExtras;
824            }
825
826            /**
827             * Add an input to be collected from the user when this action is sent.
828             * Response values can be retrieved from the fired intent by using the
829             * {@link RemoteInput#getResultsFromIntent} function.
830             * @param remoteInput a {@link RemoteInput} to add to the action
831             * @return this object for method chaining
832             */
833            public Builder addRemoteInput(RemoteInput remoteInput) {
834                if (mRemoteInputs == null) {
835                    mRemoteInputs = new ArrayList<RemoteInput>();
836                }
837                mRemoteInputs.add(remoteInput);
838                return this;
839            }
840
841            /**
842             * Apply an extender to this action builder. Extenders may be used to add
843             * metadata or change options on this builder.
844             */
845            public Builder extend(Extender extender) {
846                extender.extend(this);
847                return this;
848            }
849
850            /**
851             * Combine all of the options that have been set and return a new {@link Action}
852             * object.
853             * @return the built action
854             */
855            public Action build() {
856                RemoteInput[] remoteInputs = mRemoteInputs != null
857                        ? mRemoteInputs.toArray(new RemoteInput[mRemoteInputs.size()]) : null;
858                return new Action(mIcon, mTitle, mIntent, mExtras, remoteInputs);
859            }
860        }
861
862        @Override
863        public Action clone() {
864            return new Action(
865                    icon,
866                    title,
867                    actionIntent, // safe to alias
868                    new Bundle(mExtras),
869                    getRemoteInputs());
870        }
871        @Override
872        public int describeContents() {
873            return 0;
874        }
875        @Override
876        public void writeToParcel(Parcel out, int flags) {
877            out.writeInt(icon);
878            TextUtils.writeToParcel(title, out, flags);
879            if (actionIntent != null) {
880                out.writeInt(1);
881                actionIntent.writeToParcel(out, flags);
882            } else {
883                out.writeInt(0);
884            }
885            out.writeBundle(mExtras);
886            out.writeTypedArray(mRemoteInputs, flags);
887        }
888        public static final Parcelable.Creator<Action> CREATOR =
889                new Parcelable.Creator<Action>() {
890            public Action createFromParcel(Parcel in) {
891                return new Action(in);
892            }
893            public Action[] newArray(int size) {
894                return new Action[size];
895            }
896        };
897
898        /**
899         * Extender interface for use with {@link Builder#extend}. Extenders may be used to add
900         * metadata or change options on an action builder.
901         */
902        public interface Extender {
903            /**
904             * Apply this extender to a notification action builder.
905             * @param builder the builder to be modified.
906             * @return the build object for chaining.
907             */
908            public Builder extend(Builder builder);
909        }
910
911        /**
912         * Wearable extender for notification actions. To add extensions to an action,
913         * create a new {@link android.app.Notification.Action.WearableExtender} object using
914         * the {@code WearableExtender()} constructor and apply it to a
915         * {@link android.app.Notification.Action.Builder} using
916         * {@link android.app.Notification.Action.Builder#extend}.
917         *
918         * <pre class="prettyprint">
919         * Notification.Action action = new Notification.Action.Builder(
920         *         R.drawable.archive_all, "Archive all", actionIntent)
921         *         .extend(new Notification.Action.WearableExtender()
922         *                 .setAvailableOffline(false))
923         *         .build();</pre>
924         */
925        public static final class WearableExtender implements Extender {
926            /** Notification action extra which contains wearable extensions */
927            private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS";
928
929            private static final String KEY_FLAGS = "flags";
930
931            // Flags bitwise-ored to mFlags
932            private static final int FLAG_AVAILABLE_OFFLINE = 0x1;
933
934            // Default value for flags integer
935            private static final int DEFAULT_FLAGS = FLAG_AVAILABLE_OFFLINE;
936
937            private int mFlags = DEFAULT_FLAGS;
938
939            /**
940             * Create a {@link android.app.Notification.Action.WearableExtender} with default
941             * options.
942             */
943            public WearableExtender() {
944            }
945
946            /**
947             * Create a {@link android.app.Notification.Action.WearableExtender} by reading
948             * wearable options present in an existing notification action.
949             * @param action the notification action to inspect.
950             */
951            public WearableExtender(Action action) {
952                Bundle wearableBundle = action.getExtras().getBundle(EXTRA_WEARABLE_EXTENSIONS);
953                if (wearableBundle != null) {
954                    mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS);
955                }
956            }
957
958            /**
959             * Apply wearable extensions to a notification action that is being built. This is
960             * typically called by the {@link android.app.Notification.Action.Builder#extend}
961             * method of {@link android.app.Notification.Action.Builder}.
962             */
963            @Override
964            public Action.Builder extend(Action.Builder builder) {
965                Bundle wearableBundle = new Bundle();
966
967                if (mFlags != DEFAULT_FLAGS) {
968                    wearableBundle.putInt(KEY_FLAGS, mFlags);
969                }
970
971                builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle);
972                return builder;
973            }
974
975            @Override
976            public WearableExtender clone() {
977                WearableExtender that = new WearableExtender();
978                that.mFlags = this.mFlags;
979                return that;
980            }
981
982            /**
983             * Set whether this action is available when the wearable device is not connected to
984             * a companion device. The user can still trigger this action when the wearable device is
985             * offline, but a visual hint will indicate that the action may not be available.
986             * Defaults to true.
987             */
988            public WearableExtender setAvailableOffline(boolean availableOffline) {
989                setFlag(FLAG_AVAILABLE_OFFLINE, availableOffline);
990                return this;
991            }
992
993            /**
994             * Get whether this action is available when the wearable device is not connected to
995             * a companion device. The user can still trigger this action when the wearable device is
996             * offline, but a visual hint will indicate that the action may not be available.
997             * Defaults to true.
998             */
999            public boolean isAvailableOffline() {
1000                return (mFlags & FLAG_AVAILABLE_OFFLINE) != 0;
1001            }
1002
1003            private void setFlag(int mask, boolean value) {
1004                if (value) {
1005                    mFlags |= mask;
1006                } else {
1007                    mFlags &= ~mask;
1008                }
1009            }
1010        }
1011    }
1012
1013    /**
1014     * Array of all {@link Action} structures attached to this notification by
1015     * {@link Builder#addAction(int, CharSequence, PendingIntent)}. Mostly useful for instances of
1016     * {@link android.service.notification.NotificationListenerService} that provide an alternative
1017     * interface for invoking actions.
1018     */
1019    public Action[] actions;
1020
1021    /**
1022     * Constructs a Notification object with default values.
1023     * You might want to consider using {@link Builder} instead.
1024     */
1025    public Notification()
1026    {
1027        this.when = System.currentTimeMillis();
1028        this.priority = PRIORITY_DEFAULT;
1029    }
1030
1031    /**
1032     * @hide
1033     */
1034    public Notification(Context context, int icon, CharSequence tickerText, long when,
1035            CharSequence contentTitle, CharSequence contentText, Intent contentIntent)
1036    {
1037        this.when = when;
1038        this.icon = icon;
1039        this.tickerText = tickerText;
1040        setLatestEventInfo(context, contentTitle, contentText,
1041                PendingIntent.getActivity(context, 0, contentIntent, 0));
1042    }
1043
1044    /**
1045     * Constructs a Notification object with the information needed to
1046     * have a status bar icon without the standard expanded view.
1047     *
1048     * @param icon          The resource id of the icon to put in the status bar.
1049     * @param tickerText    The text that flows by in the status bar when the notification first
1050     *                      activates.
1051     * @param when          The time to show in the time field.  In the System.currentTimeMillis
1052     *                      timebase.
1053     *
1054     * @deprecated Use {@link Builder} instead.
1055     */
1056    @Deprecated
1057    public Notification(int icon, CharSequence tickerText, long when)
1058    {
1059        this.icon = icon;
1060        this.tickerText = tickerText;
1061        this.when = when;
1062    }
1063
1064    /**
1065     * Unflatten the notification from a parcel.
1066     */
1067    public Notification(Parcel parcel)
1068    {
1069        int version = parcel.readInt();
1070
1071        when = parcel.readLong();
1072        icon = parcel.readInt();
1073        number = parcel.readInt();
1074        if (parcel.readInt() != 0) {
1075            contentIntent = PendingIntent.CREATOR.createFromParcel(parcel);
1076        }
1077        if (parcel.readInt() != 0) {
1078            deleteIntent = PendingIntent.CREATOR.createFromParcel(parcel);
1079        }
1080        if (parcel.readInt() != 0) {
1081            tickerText = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(parcel);
1082        }
1083        if (parcel.readInt() != 0) {
1084            tickerView = RemoteViews.CREATOR.createFromParcel(parcel);
1085        }
1086        if (parcel.readInt() != 0) {
1087            contentView = RemoteViews.CREATOR.createFromParcel(parcel);
1088        }
1089        if (parcel.readInt() != 0) {
1090            largeIcon = Bitmap.CREATOR.createFromParcel(parcel);
1091        }
1092        defaults = parcel.readInt();
1093        flags = parcel.readInt();
1094        if (parcel.readInt() != 0) {
1095            sound = Uri.CREATOR.createFromParcel(parcel);
1096        }
1097
1098        audioStreamType = parcel.readInt();
1099        vibrate = parcel.createLongArray();
1100        ledARGB = parcel.readInt();
1101        ledOnMS = parcel.readInt();
1102        ledOffMS = parcel.readInt();
1103        iconLevel = parcel.readInt();
1104
1105        if (parcel.readInt() != 0) {
1106            fullScreenIntent = PendingIntent.CREATOR.createFromParcel(parcel);
1107        }
1108
1109        priority = parcel.readInt();
1110
1111        category = parcel.readString();
1112
1113        mGroupKey = parcel.readString();
1114
1115        mSortKey = parcel.readString();
1116
1117        extras = parcel.readBundle(); // may be null
1118
1119        actions = parcel.createTypedArray(Action.CREATOR); // may be null
1120
1121        if (parcel.readInt() != 0) {
1122            bigContentView = RemoteViews.CREATOR.createFromParcel(parcel);
1123        }
1124    }
1125
1126    @Override
1127    public Notification clone() {
1128        Notification that = new Notification();
1129        cloneInto(that, true);
1130        return that;
1131    }
1132
1133    /**
1134     * Copy all (or if heavy is false, all except Bitmaps and RemoteViews) members
1135     * of this into that.
1136     * @hide
1137     */
1138    public void cloneInto(Notification that, boolean heavy) {
1139        that.when = this.when;
1140        that.icon = this.icon;
1141        that.number = this.number;
1142
1143        // PendingIntents are global, so there's no reason (or way) to clone them.
1144        that.contentIntent = this.contentIntent;
1145        that.deleteIntent = this.deleteIntent;
1146        that.fullScreenIntent = this.fullScreenIntent;
1147
1148        if (this.tickerText != null) {
1149            that.tickerText = this.tickerText.toString();
1150        }
1151        if (heavy && this.tickerView != null) {
1152            that.tickerView = this.tickerView.clone();
1153        }
1154        if (heavy && this.contentView != null) {
1155            that.contentView = this.contentView.clone();
1156        }
1157        if (heavy && this.largeIcon != null) {
1158            that.largeIcon = Bitmap.createBitmap(this.largeIcon);
1159        }
1160        that.iconLevel = this.iconLevel;
1161        that.sound = this.sound; // android.net.Uri is immutable
1162        that.audioStreamType = this.audioStreamType;
1163
1164        final long[] vibrate = this.vibrate;
1165        if (vibrate != null) {
1166            final int N = vibrate.length;
1167            final long[] vib = that.vibrate = new long[N];
1168            System.arraycopy(vibrate, 0, vib, 0, N);
1169        }
1170
1171        that.ledARGB = this.ledARGB;
1172        that.ledOnMS = this.ledOnMS;
1173        that.ledOffMS = this.ledOffMS;
1174        that.defaults = this.defaults;
1175
1176        that.flags = this.flags;
1177
1178        that.priority = this.priority;
1179
1180        that.category = this.category;
1181
1182        that.mGroupKey = this.mGroupKey;
1183
1184        that.mSortKey = this.mSortKey;
1185
1186        if (this.extras != null) {
1187            try {
1188                that.extras = new Bundle(this.extras);
1189                // will unparcel
1190                that.extras.size();
1191            } catch (BadParcelableException e) {
1192                Log.e(TAG, "could not unparcel extras from notification: " + this, e);
1193                that.extras = null;
1194            }
1195        }
1196
1197        if (this.actions != null) {
1198            that.actions = new Action[this.actions.length];
1199            for(int i=0; i<this.actions.length; i++) {
1200                that.actions[i] = this.actions[i].clone();
1201            }
1202        }
1203
1204        if (heavy && this.bigContentView != null) {
1205            that.bigContentView = this.bigContentView.clone();
1206        }
1207
1208        if (!heavy) {
1209            that.lightenPayload(); // will clean out extras
1210        }
1211    }
1212
1213    /**
1214     * Removes heavyweight parts of the Notification object for archival or for sending to
1215     * listeners when the full contents are not necessary.
1216     * @hide
1217     */
1218    public final void lightenPayload() {
1219        tickerView = null;
1220        contentView = null;
1221        bigContentView = null;
1222        largeIcon = null;
1223        if (extras != null) {
1224            extras.remove(Notification.EXTRA_LARGE_ICON);
1225            extras.remove(Notification.EXTRA_LARGE_ICON_BIG);
1226            extras.remove(Notification.EXTRA_PICTURE);
1227        }
1228    }
1229
1230    /**
1231     * Make sure this CharSequence is safe to put into a bundle, which basically
1232     * means it had better not be some custom Parcelable implementation.
1233     * @hide
1234     */
1235    public static CharSequence safeCharSequence(CharSequence cs) {
1236        if (cs instanceof Parcelable) {
1237            Log.e(TAG, "warning: " + cs.getClass().getCanonicalName()
1238                    + " instance is a custom Parcelable and not allowed in Notification");
1239            return cs.toString();
1240        }
1241
1242        return cs;
1243    }
1244
1245    public int describeContents() {
1246        return 0;
1247    }
1248
1249    /**
1250     * Flatten this notification from a parcel.
1251     */
1252    public void writeToParcel(Parcel parcel, int flags)
1253    {
1254        parcel.writeInt(1);
1255
1256        parcel.writeLong(when);
1257        parcel.writeInt(icon);
1258        parcel.writeInt(number);
1259        if (contentIntent != null) {
1260            parcel.writeInt(1);
1261            contentIntent.writeToParcel(parcel, 0);
1262        } else {
1263            parcel.writeInt(0);
1264        }
1265        if (deleteIntent != null) {
1266            parcel.writeInt(1);
1267            deleteIntent.writeToParcel(parcel, 0);
1268        } else {
1269            parcel.writeInt(0);
1270        }
1271        if (tickerText != null) {
1272            parcel.writeInt(1);
1273            TextUtils.writeToParcel(tickerText, parcel, flags);
1274        } else {
1275            parcel.writeInt(0);
1276        }
1277        if (tickerView != null) {
1278            parcel.writeInt(1);
1279            tickerView.writeToParcel(parcel, 0);
1280        } else {
1281            parcel.writeInt(0);
1282        }
1283        if (contentView != null) {
1284            parcel.writeInt(1);
1285            contentView.writeToParcel(parcel, 0);
1286        } else {
1287            parcel.writeInt(0);
1288        }
1289        if (largeIcon != null) {
1290            parcel.writeInt(1);
1291            largeIcon.writeToParcel(parcel, 0);
1292        } else {
1293            parcel.writeInt(0);
1294        }
1295
1296        parcel.writeInt(defaults);
1297        parcel.writeInt(this.flags);
1298
1299        if (sound != null) {
1300            parcel.writeInt(1);
1301            sound.writeToParcel(parcel, 0);
1302        } else {
1303            parcel.writeInt(0);
1304        }
1305        parcel.writeInt(audioStreamType);
1306        parcel.writeLongArray(vibrate);
1307        parcel.writeInt(ledARGB);
1308        parcel.writeInt(ledOnMS);
1309        parcel.writeInt(ledOffMS);
1310        parcel.writeInt(iconLevel);
1311
1312        if (fullScreenIntent != null) {
1313            parcel.writeInt(1);
1314            fullScreenIntent.writeToParcel(parcel, 0);
1315        } else {
1316            parcel.writeInt(0);
1317        }
1318
1319        parcel.writeInt(priority);
1320
1321        parcel.writeString(category);
1322
1323        parcel.writeString(mGroupKey);
1324
1325        parcel.writeString(mSortKey);
1326
1327        parcel.writeBundle(extras); // null ok
1328
1329        parcel.writeTypedArray(actions, 0); // null ok
1330
1331        if (bigContentView != null) {
1332            parcel.writeInt(1);
1333            bigContentView.writeToParcel(parcel, 0);
1334        } else {
1335            parcel.writeInt(0);
1336        }
1337    }
1338
1339    /**
1340     * Parcelable.Creator that instantiates Notification objects
1341     */
1342    public static final Parcelable.Creator<Notification> CREATOR
1343            = new Parcelable.Creator<Notification>()
1344    {
1345        public Notification createFromParcel(Parcel parcel)
1346        {
1347            return new Notification(parcel);
1348        }
1349
1350        public Notification[] newArray(int size)
1351        {
1352            return new Notification[size];
1353        }
1354    };
1355
1356    /**
1357     * Sets the {@link #contentView} field to be a view with the standard "Latest Event"
1358     * layout.
1359     *
1360     * <p>Uses the {@link #icon} and {@link #when} fields to set the icon and time fields
1361     * in the view.</p>
1362     * @param context       The context for your application / activity.
1363     * @param contentTitle The title that goes in the expanded entry.
1364     * @param contentText  The text that goes in the expanded entry.
1365     * @param contentIntent The intent to launch when the user clicks the expanded notification.
1366     * If this is an activity, it must include the
1367     * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires
1368     * that you take care of task management as described in the
1369     * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back
1370     * Stack</a> document.
1371     *
1372     * @deprecated Use {@link Builder} instead.
1373     */
1374    @Deprecated
1375    public void setLatestEventInfo(Context context,
1376            CharSequence contentTitle, CharSequence contentText, PendingIntent contentIntent) {
1377        Notification.Builder builder = new Notification.Builder(context);
1378
1379        // First, ensure that key pieces of information that may have been set directly
1380        // are preserved
1381        builder.setWhen(this.when);
1382        builder.setSmallIcon(this.icon);
1383        builder.setPriority(this.priority);
1384        builder.setTicker(this.tickerText);
1385        builder.setNumber(this.number);
1386        builder.mFlags = this.flags;
1387        builder.setSound(this.sound, this.audioStreamType);
1388        builder.setDefaults(this.defaults);
1389        builder.setVibrate(this.vibrate);
1390
1391        // now apply the latestEventInfo fields
1392        if (contentTitle != null) {
1393            builder.setContentTitle(contentTitle);
1394        }
1395        if (contentText != null) {
1396            builder.setContentText(contentText);
1397        }
1398        builder.setContentIntent(contentIntent);
1399        builder.buildInto(this);
1400    }
1401
1402    @Override
1403    public String toString() {
1404        StringBuilder sb = new StringBuilder();
1405        sb.append("Notification(pri=");
1406        sb.append(priority);
1407        sb.append(" contentView=");
1408        if (contentView != null) {
1409            sb.append(contentView.getPackage());
1410            sb.append("/0x");
1411            sb.append(Integer.toHexString(contentView.getLayoutId()));
1412        } else {
1413            sb.append("null");
1414        }
1415        // TODO(dsandler): defaults take precedence over local values, so reorder the branches below
1416        sb.append(" vibrate=");
1417        if ((this.defaults & DEFAULT_VIBRATE) != 0) {
1418            sb.append("default");
1419        } else if (this.vibrate != null) {
1420            int N = this.vibrate.length-1;
1421            sb.append("[");
1422            for (int i=0; i<N; i++) {
1423                sb.append(this.vibrate[i]);
1424                sb.append(',');
1425            }
1426            if (N != -1) {
1427                sb.append(this.vibrate[N]);
1428            }
1429            sb.append("]");
1430        } else {
1431            sb.append("null");
1432        }
1433        sb.append(" sound=");
1434        if ((this.defaults & DEFAULT_SOUND) != 0) {
1435            sb.append("default");
1436        } else if (this.sound != null) {
1437            sb.append(this.sound.toString());
1438        } else {
1439            sb.append("null");
1440        }
1441        sb.append(" defaults=0x");
1442        sb.append(Integer.toHexString(this.defaults));
1443        sb.append(" flags=0x");
1444        sb.append(Integer.toHexString(this.flags));
1445        if (this.category != null) {
1446            sb.append(" category=");
1447            sb.append(this.category);
1448        }
1449        if (this.mGroupKey != null) {
1450            sb.append(" groupKey=");
1451            sb.append(this.mGroupKey);
1452        }
1453        if (this.mSortKey != null) {
1454            sb.append(" sortKey=");
1455            sb.append(this.mSortKey);
1456        }
1457        if (actions != null) {
1458            sb.append(" ");
1459            sb.append(actions.length);
1460            sb.append(" action");
1461            if (actions.length > 1) sb.append("s");
1462        }
1463        sb.append(")");
1464        return sb.toString();
1465    }
1466
1467    /** {@hide} */
1468    public void setUser(UserHandle user) {
1469        if (user.getIdentifier() == UserHandle.USER_ALL) {
1470            user = UserHandle.OWNER;
1471        }
1472        if (tickerView != null) {
1473            tickerView.setUser(user);
1474        }
1475        if (contentView != null) {
1476            contentView.setUser(user);
1477        }
1478        if (bigContentView != null) {
1479            bigContentView.setUser(user);
1480        }
1481    }
1482
1483    /**
1484     * Builder class for {@link Notification} objects.
1485     *
1486     * Provides a convenient way to set the various fields of a {@link Notification} and generate
1487     * content views using the platform's notification layout template. If your app supports
1488     * versions of Android as old as API level 4, you can instead use
1489     * {@link android.support.v4.app.NotificationCompat.Builder NotificationCompat.Builder},
1490     * available in the <a href="{@docRoot}tools/extras/support-library.html">Android Support
1491     * library</a>.
1492     *
1493     * <p>Example:
1494     *
1495     * <pre class="prettyprint">
1496     * Notification noti = new Notification.Builder(mContext)
1497     *         .setContentTitle(&quot;New mail from &quot; + sender.toString())
1498     *         .setContentText(subject)
1499     *         .setSmallIcon(R.drawable.new_mail)
1500     *         .setLargeIcon(aBitmap)
1501     *         .build();
1502     * </pre>
1503     */
1504    public static class Builder {
1505        private static final int MAX_ACTION_BUTTONS = 3;
1506
1507        private Context mContext;
1508
1509        private long mWhen;
1510        private int mSmallIcon;
1511        private int mSmallIconLevel;
1512        private int mNumber;
1513        private CharSequence mContentTitle;
1514        private CharSequence mContentText;
1515        private CharSequence mContentInfo;
1516        private CharSequence mSubText;
1517        private PendingIntent mContentIntent;
1518        private RemoteViews mContentView;
1519        private PendingIntent mDeleteIntent;
1520        private PendingIntent mFullScreenIntent;
1521        private CharSequence mTickerText;
1522        private RemoteViews mTickerView;
1523        private Bitmap mLargeIcon;
1524        private Uri mSound;
1525        private int mAudioStreamType;
1526        private long[] mVibrate;
1527        private int mLedArgb;
1528        private int mLedOnMs;
1529        private int mLedOffMs;
1530        private int mDefaults;
1531        private int mFlags;
1532        private int mProgressMax;
1533        private int mProgress;
1534        private boolean mProgressIndeterminate;
1535        private String mCategory;
1536        private String mGroupKey;
1537        private String mSortKey;
1538        private Bundle mExtras;
1539        private int mPriority;
1540        private ArrayList<Action> mActions = new ArrayList<Action>(MAX_ACTION_BUTTONS);
1541        private boolean mUseChronometer;
1542        private Style mStyle;
1543        private boolean mShowWhen = true;
1544
1545        /**
1546         * Constructs a new Builder with the defaults:
1547         *
1548
1549         * <table>
1550         * <tr><th align=right>priority</th>
1551         *     <td>{@link #PRIORITY_DEFAULT}</td></tr>
1552         * <tr><th align=right>when</th>
1553         *     <td>now ({@link System#currentTimeMillis()})</td></tr>
1554         * <tr><th align=right>audio stream</th>
1555         *     <td>{@link #STREAM_DEFAULT}</td></tr>
1556         * </table>
1557         *
1558
1559         * @param context
1560         *            A {@link Context} that will be used by the Builder to construct the
1561         *            RemoteViews. The Context will not be held past the lifetime of this Builder
1562         *            object.
1563         */
1564        public Builder(Context context) {
1565            mContext = context;
1566
1567            // Set defaults to match the defaults of a Notification
1568            mWhen = System.currentTimeMillis();
1569            mAudioStreamType = STREAM_DEFAULT;
1570            mPriority = PRIORITY_DEFAULT;
1571        }
1572
1573        /**
1574         * Add a timestamp pertaining to the notification (usually the time the event occurred).
1575         * It will be shown in the notification content view by default; use
1576         * {@link #setShowWhen(boolean) setShowWhen} to control this.
1577         *
1578         * @see Notification#when
1579         */
1580        public Builder setWhen(long when) {
1581            mWhen = when;
1582            return this;
1583        }
1584
1585        /**
1586         * Control whether the timestamp set with {@link #setWhen(long) setWhen} is shown
1587         * in the content view.
1588         */
1589        public Builder setShowWhen(boolean show) {
1590            mShowWhen = show;
1591            return this;
1592        }
1593
1594        /**
1595         * Show the {@link Notification#when} field as a stopwatch.
1596         *
1597         * Instead of presenting <code>when</code> as a timestamp, the notification will show an
1598         * automatically updating display of the minutes and seconds since <code>when</code>.
1599         *
1600         * Useful when showing an elapsed time (like an ongoing phone call).
1601         *
1602         * @see android.widget.Chronometer
1603         * @see Notification#when
1604         */
1605        public Builder setUsesChronometer(boolean b) {
1606            mUseChronometer = b;
1607            return this;
1608        }
1609
1610        /**
1611         * Set the small icon resource, which will be used to represent the notification in the
1612         * status bar.
1613         *
1614
1615         * The platform template for the expanded view will draw this icon in the left, unless a
1616         * {@link #setLargeIcon(Bitmap) large icon} has also been specified, in which case the small
1617         * icon will be moved to the right-hand side.
1618         *
1619
1620         * @param icon
1621         *            A resource ID in the application's package of the drawable to use.
1622         * @see Notification#icon
1623         */
1624        public Builder setSmallIcon(int icon) {
1625            mSmallIcon = icon;
1626            return this;
1627        }
1628
1629        /**
1630         * A variant of {@link #setSmallIcon(int) setSmallIcon(int)} that takes an additional
1631         * level parameter for when the icon is a {@link android.graphics.drawable.LevelListDrawable
1632         * LevelListDrawable}.
1633         *
1634         * @param icon A resource ID in the application's package of the drawable to use.
1635         * @param level The level to use for the icon.
1636         *
1637         * @see Notification#icon
1638         * @see Notification#iconLevel
1639         */
1640        public Builder setSmallIcon(int icon, int level) {
1641            mSmallIcon = icon;
1642            mSmallIconLevel = level;
1643            return this;
1644        }
1645
1646        /**
1647         * Set the first line of text in the platform notification template.
1648         */
1649        public Builder setContentTitle(CharSequence title) {
1650            mContentTitle = safeCharSequence(title);
1651            return this;
1652        }
1653
1654        /**
1655         * Set the second line of text in the platform notification template.
1656         */
1657        public Builder setContentText(CharSequence text) {
1658            mContentText = safeCharSequence(text);
1659            return this;
1660        }
1661
1662        /**
1663         * Set the third line of text in the platform notification template.
1664         * Don't use if you're also using {@link #setProgress(int, int, boolean)}; they occupy the
1665         * same location in the standard template.
1666         */
1667        public Builder setSubText(CharSequence text) {
1668            mSubText = safeCharSequence(text);
1669            return this;
1670        }
1671
1672        /**
1673         * Set the large number at the right-hand side of the notification.  This is
1674         * equivalent to setContentInfo, although it might show the number in a different
1675         * font size for readability.
1676         */
1677        public Builder setNumber(int number) {
1678            mNumber = number;
1679            return this;
1680        }
1681
1682        /**
1683         * A small piece of additional information pertaining to this notification.
1684         *
1685         * The platform template will draw this on the last line of the notification, at the far
1686         * right (to the right of a smallIcon if it has been placed there).
1687         */
1688        public Builder setContentInfo(CharSequence info) {
1689            mContentInfo = safeCharSequence(info);
1690            return this;
1691        }
1692
1693        /**
1694         * Set the progress this notification represents.
1695         *
1696         * The platform template will represent this using a {@link ProgressBar}.
1697         */
1698        public Builder setProgress(int max, int progress, boolean indeterminate) {
1699            mProgressMax = max;
1700            mProgress = progress;
1701            mProgressIndeterminate = indeterminate;
1702            return this;
1703        }
1704
1705        /**
1706         * Supply a custom RemoteViews to use instead of the platform template.
1707         *
1708         * @see Notification#contentView
1709         */
1710        public Builder setContent(RemoteViews views) {
1711            mContentView = views;
1712            return this;
1713        }
1714
1715        /**
1716         * Supply a {@link PendingIntent} to be sent when the notification is clicked.
1717         *
1718         * As of {@link android.os.Build.VERSION_CODES#HONEYCOMB}, if this field is unset and you
1719         * have specified a custom RemoteViews with {@link #setContent(RemoteViews)}, you can use
1720         * {@link RemoteViews#setOnClickPendingIntent RemoteViews.setOnClickPendingIntent(int,PendingIntent)}
1721         * to assign PendingIntents to individual views in that custom layout (i.e., to create
1722         * clickable buttons inside the notification view).
1723         *
1724         * @see Notification#contentIntent Notification.contentIntent
1725         */
1726        public Builder setContentIntent(PendingIntent intent) {
1727            mContentIntent = intent;
1728            return this;
1729        }
1730
1731        /**
1732         * Supply a {@link PendingIntent} to send when the notification is cleared explicitly by the user.
1733         *
1734         * @see Notification#deleteIntent
1735         */
1736        public Builder setDeleteIntent(PendingIntent intent) {
1737            mDeleteIntent = intent;
1738            return this;
1739        }
1740
1741        /**
1742         * An intent to launch instead of posting the notification to the status bar.
1743         * Only for use with extremely high-priority notifications demanding the user's
1744         * <strong>immediate</strong> attention, such as an incoming phone call or
1745         * alarm clock that the user has explicitly set to a particular time.
1746         * If this facility is used for something else, please give the user an option
1747         * to turn it off and use a normal notification, as this can be extremely
1748         * disruptive.
1749         *
1750         * @param intent The pending intent to launch.
1751         * @param highPriority Passing true will cause this notification to be sent
1752         *          even if other notifications are suppressed.
1753         *
1754         * @see Notification#fullScreenIntent
1755         */
1756        public Builder setFullScreenIntent(PendingIntent intent, boolean highPriority) {
1757            mFullScreenIntent = intent;
1758            setFlag(FLAG_HIGH_PRIORITY, highPriority);
1759            return this;
1760        }
1761
1762        /**
1763         * Set the "ticker" text which is displayed in the status bar when the notification first
1764         * arrives.
1765         *
1766         * @see Notification#tickerText
1767         */
1768        public Builder setTicker(CharSequence tickerText) {
1769            mTickerText = safeCharSequence(tickerText);
1770            return this;
1771        }
1772
1773        /**
1774         * Set the text that is displayed in the status bar when the notification first
1775         * arrives, and also a RemoteViews object that may be displayed instead on some
1776         * devices.
1777         *
1778         * @see Notification#tickerText
1779         * @see Notification#tickerView
1780         */
1781        public Builder setTicker(CharSequence tickerText, RemoteViews views) {
1782            mTickerText = safeCharSequence(tickerText);
1783            mTickerView = views;
1784            return this;
1785        }
1786
1787        /**
1788         * Add a large icon to the notification (and the ticker on some devices).
1789         *
1790         * In the platform template, this image will be shown on the left of the notification view
1791         * in place of the {@link #setSmallIcon(int) small icon} (which will move to the right side).
1792         *
1793         * @see Notification#largeIcon
1794         */
1795        public Builder setLargeIcon(Bitmap icon) {
1796            mLargeIcon = icon;
1797            return this;
1798        }
1799
1800        /**
1801         * Set the sound to play.
1802         *
1803         * It will be played on the {@link #STREAM_DEFAULT default stream} for notifications.
1804         *
1805         * @see Notification#sound
1806         */
1807        public Builder setSound(Uri sound) {
1808            mSound = sound;
1809            mAudioStreamType = STREAM_DEFAULT;
1810            return this;
1811        }
1812
1813        /**
1814         * Set the sound to play, along with a specific stream on which to play it.
1815         *
1816         * See {@link android.media.AudioManager} for the <code>STREAM_</code> constants.
1817         *
1818         * @see Notification#sound
1819         */
1820        public Builder setSound(Uri sound, int streamType) {
1821            mSound = sound;
1822            mAudioStreamType = streamType;
1823            return this;
1824        }
1825
1826        /**
1827         * Set the vibration pattern to use.
1828         *
1829
1830         * See {@link android.os.Vibrator#vibrate(long[], int)} for a discussion of the
1831         * <code>pattern</code> parameter.
1832         *
1833
1834         * @see Notification#vibrate
1835         */
1836        public Builder setVibrate(long[] pattern) {
1837            mVibrate = pattern;
1838            return this;
1839        }
1840
1841        /**
1842         * Set the desired color for the indicator LED on the device, as well as the
1843         * blink duty cycle (specified in milliseconds).
1844         *
1845
1846         * Not all devices will honor all (or even any) of these values.
1847         *
1848
1849         * @see Notification#ledARGB
1850         * @see Notification#ledOnMS
1851         * @see Notification#ledOffMS
1852         */
1853        public Builder setLights(int argb, int onMs, int offMs) {
1854            mLedArgb = argb;
1855            mLedOnMs = onMs;
1856            mLedOffMs = offMs;
1857            return this;
1858        }
1859
1860        /**
1861         * Set whether this is an "ongoing" notification.
1862         *
1863
1864         * Ongoing notifications cannot be dismissed by the user, so your application or service
1865         * must take care of canceling them.
1866         *
1867
1868         * They are typically used to indicate a background task that the user is actively engaged
1869         * with (e.g., playing music) or is pending in some way and therefore occupying the device
1870         * (e.g., a file download, sync operation, active network connection).
1871         *
1872
1873         * @see Notification#FLAG_ONGOING_EVENT
1874         * @see Service#setForeground(boolean)
1875         */
1876        public Builder setOngoing(boolean ongoing) {
1877            setFlag(FLAG_ONGOING_EVENT, ongoing);
1878            return this;
1879        }
1880
1881        /**
1882         * Set this flag if you would only like the sound, vibrate
1883         * and ticker to be played if the notification is not already showing.
1884         *
1885         * @see Notification#FLAG_ONLY_ALERT_ONCE
1886         */
1887        public Builder setOnlyAlertOnce(boolean onlyAlertOnce) {
1888            setFlag(FLAG_ONLY_ALERT_ONCE, onlyAlertOnce);
1889            return this;
1890        }
1891
1892        /**
1893         * Make this notification automatically dismissed when the user touches it. The
1894         * PendingIntent set with {@link #setDeleteIntent} will be sent when this happens.
1895         *
1896         * @see Notification#FLAG_AUTO_CANCEL
1897         */
1898        public Builder setAutoCancel(boolean autoCancel) {
1899            setFlag(FLAG_AUTO_CANCEL, autoCancel);
1900            return this;
1901        }
1902
1903        /**
1904         * Set whether or not this notification should not bridge to other devices.
1905         *
1906         * <p>Some notifications can be bridged to other devices for remote display.
1907         * This hint can be set to recommend this notification not be bridged.
1908         */
1909        public Builder setLocalOnly(boolean localOnly) {
1910            setFlag(FLAG_LOCAL_ONLY, localOnly);
1911            return this;
1912        }
1913
1914        /**
1915         * Set which notification properties will be inherited from system defaults.
1916         * <p>
1917         * The value should be one or more of the following fields combined with
1918         * bitwise-or:
1919         * {@link #DEFAULT_SOUND}, {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}.
1920         * <p>
1921         * For all default values, use {@link #DEFAULT_ALL}.
1922         */
1923        public Builder setDefaults(int defaults) {
1924            mDefaults = defaults;
1925            return this;
1926        }
1927
1928        /**
1929         * Set the priority of this notification.
1930         *
1931         * @see Notification#priority
1932         */
1933        public Builder setPriority(int pri) {
1934            mPriority = pri;
1935            return this;
1936        }
1937
1938        /**
1939         * Set the notification category.
1940         *
1941         * @see Notification#category
1942         * @hide
1943         */
1944        public Builder setCategory(String category) {
1945            mCategory = category;
1946            return this;
1947        }
1948
1949        /**
1950         * Set this notification to be part of a group of notifications sharing the same key.
1951         * Grouped notifications may display in a cluster or stack on devices which
1952         * support such rendering.
1953         *
1954         * <p>To make this notification the summary for its group, also call
1955         * {@link #setGroupSummary}. A sort order can be specified for group members by using
1956         * {@link #setSortKey}.
1957         * @param groupKey The group key of the group.
1958         * @return this object for method chaining
1959         */
1960        public Builder setGroup(String groupKey) {
1961            mGroupKey = groupKey;
1962            return this;
1963        }
1964
1965        /**
1966         * Set this notification to be the group summary for a group of notifications.
1967         * Grouped notifications may display in a cluster or stack on devices which
1968         * support such rendering. Requires a group key also be set using {@link #setGroup}.
1969         * @param isGroupSummary Whether this notification should be a group summary.
1970         * @return this object for method chaining
1971         */
1972        public Builder setGroupSummary(boolean isGroupSummary) {
1973            setFlag(FLAG_GROUP_SUMMARY, isGroupSummary);
1974            return this;
1975        }
1976
1977        /**
1978         * Set a sort key that orders this notification among other notifications from the
1979         * same package. This can be useful if an external sort was already applied and an app
1980         * would like to preserve this. Notifications will be sorted lexicographically using this
1981         * value, although providing different priorities in addition to providing sort key may
1982         * cause this value to be ignored.
1983         *
1984         * <p>This sort key can also be used to order members of a notification group. See
1985         * {@link #setGroup}.
1986         *
1987         * @see String#compareTo(String)
1988         */
1989        public Builder setSortKey(String sortKey) {
1990            mSortKey = sortKey;
1991            return this;
1992        }
1993
1994        /**
1995         * Merge additional metadata into this notification.
1996         *
1997         * <p>Values within the Bundle will replace existing extras values in this Builder.
1998         *
1999         * @see Notification#extras
2000         */
2001        public Builder addExtras(Bundle extras) {
2002            if (extras != null) {
2003                if (mExtras == null) {
2004                    mExtras = new Bundle(extras);
2005                } else {
2006                    mExtras.putAll(extras);
2007                }
2008            }
2009            return this;
2010        }
2011
2012        /**
2013         * Set metadata for this notification.
2014         *
2015         * <p>A reference to the Bundle is held for the lifetime of this Builder, and the Bundle's
2016         * current contents are copied into the Notification each time {@link #build()} is
2017         * called.
2018         *
2019         * <p>Replaces any existing extras values with those from the provided Bundle.
2020         * Use {@link #addExtras} to merge in metadata instead.
2021         *
2022         * @see Notification#extras
2023         */
2024        public Builder setExtras(Bundle extras) {
2025            mExtras = extras;
2026            return this;
2027        }
2028
2029        /**
2030         * Get the current metadata Bundle used by this notification Builder.
2031         *
2032         * <p>The returned Bundle is shared with this Builder.
2033         *
2034         * <p>The current contents of this Bundle are copied into the Notification each time
2035         * {@link #build()} is called.
2036         *
2037         * @see Notification#extras
2038         */
2039        public Bundle getExtras() {
2040            if (mExtras == null) {
2041                mExtras = new Bundle();
2042            }
2043            return mExtras;
2044        }
2045
2046        /**
2047         * Add an action to this notification. Actions are typically displayed by
2048         * the system as a button adjacent to the notification content.
2049         * <p>
2050         * Every action must have an icon (32dp square and matching the
2051         * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo
2052         * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}.
2053         * <p>
2054         * A notification in its expanded form can display up to 3 actions, from left to right in
2055         * the order they were added. Actions will not be displayed when the notification is
2056         * collapsed, however, so be sure that any essential functions may be accessed by the user
2057         * in some other way (for example, in the Activity pointed to by {@link #contentIntent}).
2058         *
2059         * @param icon Resource ID of a drawable that represents the action.
2060         * @param title Text describing the action.
2061         * @param intent PendingIntent to be fired when the action is invoked.
2062         */
2063        public Builder addAction(int icon, CharSequence title, PendingIntent intent) {
2064            mActions.add(new Action(icon, safeCharSequence(title), intent));
2065            return this;
2066        }
2067
2068        /**
2069         * Add an action to this notification. Actions are typically displayed by
2070         * the system as a button adjacent to the notification content.
2071         * <p>
2072         * Every action must have an icon (32dp square and matching the
2073         * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo
2074         * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}.
2075         * <p>
2076         * A notification in its expanded form can display up to 3 actions, from left to right in
2077         * the order they were added. Actions will not be displayed when the notification is
2078         * collapsed, however, so be sure that any essential functions may be accessed by the user
2079         * in some other way (for example, in the Activity pointed to by {@link #contentIntent}).
2080         *
2081         * @param action The action to add.
2082         */
2083        public Builder addAction(Action action) {
2084            mActions.add(action);
2085            return this;
2086        }
2087
2088        /**
2089         * Add a rich notification style to be applied at build time.
2090         *
2091         * @param style Object responsible for modifying the notification style.
2092         */
2093        public Builder setStyle(Style style) {
2094            if (mStyle != style) {
2095                mStyle = style;
2096                if (mStyle != null) {
2097                    mStyle.setBuilder(this);
2098                }
2099            }
2100            return this;
2101        }
2102
2103        /**
2104         * Apply an extender to this notification builder. Extenders may be used to add
2105         * metadata or change options on this builder.
2106         */
2107        public Builder extend(Extender extender) {
2108            extender.extend(this);
2109            return this;
2110        }
2111
2112        private void setFlag(int mask, boolean value) {
2113            if (value) {
2114                mFlags |= mask;
2115            } else {
2116                mFlags &= ~mask;
2117            }
2118        }
2119
2120        private RemoteViews applyStandardTemplate(int resId, boolean fitIn1U) {
2121            RemoteViews contentView = new RemoteViews(mContext.getPackageName(), resId);
2122            boolean showLine3 = false;
2123            boolean showLine2 = false;
2124            int smallIconImageViewId = R.id.icon;
2125            if (mLargeIcon != null) {
2126                contentView.setImageViewBitmap(R.id.icon, mLargeIcon);
2127                smallIconImageViewId = R.id.right_icon;
2128            }
2129            if (mPriority < PRIORITY_LOW) {
2130                contentView.setInt(R.id.icon,
2131                        "setBackgroundResource", R.drawable.notification_template_icon_low_bg);
2132                contentView.setInt(R.id.status_bar_latest_event_content,
2133                        "setBackgroundResource", R.drawable.notification_bg_low);
2134            }
2135            if (mSmallIcon != 0) {
2136                contentView.setImageViewResource(smallIconImageViewId, mSmallIcon);
2137                contentView.setViewVisibility(smallIconImageViewId, View.VISIBLE);
2138            } else {
2139                contentView.setViewVisibility(smallIconImageViewId, View.GONE);
2140            }
2141            if (mContentTitle != null) {
2142                contentView.setTextViewText(R.id.title, mContentTitle);
2143            }
2144            if (mContentText != null) {
2145                contentView.setTextViewText(R.id.text, mContentText);
2146                showLine3 = true;
2147            }
2148            if (mContentInfo != null) {
2149                contentView.setTextViewText(R.id.info, mContentInfo);
2150                contentView.setViewVisibility(R.id.info, View.VISIBLE);
2151                showLine3 = true;
2152            } else if (mNumber > 0) {
2153                final int tooBig = mContext.getResources().getInteger(
2154                        R.integer.status_bar_notification_info_maxnum);
2155                if (mNumber > tooBig) {
2156                    contentView.setTextViewText(R.id.info, mContext.getResources().getString(
2157                                R.string.status_bar_notification_info_overflow));
2158                } else {
2159                    NumberFormat f = NumberFormat.getIntegerInstance();
2160                    contentView.setTextViewText(R.id.info, f.format(mNumber));
2161                }
2162                contentView.setViewVisibility(R.id.info, View.VISIBLE);
2163                showLine3 = true;
2164            } else {
2165                contentView.setViewVisibility(R.id.info, View.GONE);
2166            }
2167
2168            // Need to show three lines?
2169            if (mSubText != null) {
2170                contentView.setTextViewText(R.id.text, mSubText);
2171                if (mContentText != null) {
2172                    contentView.setTextViewText(R.id.text2, mContentText);
2173                    contentView.setViewVisibility(R.id.text2, View.VISIBLE);
2174                    showLine2 = true;
2175                } else {
2176                    contentView.setViewVisibility(R.id.text2, View.GONE);
2177                }
2178            } else {
2179                contentView.setViewVisibility(R.id.text2, View.GONE);
2180                if (mProgressMax != 0 || mProgressIndeterminate) {
2181                    contentView.setProgressBar(
2182                            R.id.progress, mProgressMax, mProgress, mProgressIndeterminate);
2183                    contentView.setViewVisibility(R.id.progress, View.VISIBLE);
2184                    showLine2 = true;
2185                } else {
2186                    contentView.setViewVisibility(R.id.progress, View.GONE);
2187                }
2188            }
2189            if (showLine2) {
2190                if (fitIn1U) {
2191                    // need to shrink all the type to make sure everything fits
2192                    final Resources res = mContext.getResources();
2193                    final float subTextSize = res.getDimensionPixelSize(
2194                            R.dimen.notification_subtext_size);
2195                    contentView.setTextViewTextSize(R.id.text, TypedValue.COMPLEX_UNIT_PX, subTextSize);
2196                }
2197                // vertical centering
2198                contentView.setViewPadding(R.id.line1, 0, 0, 0, 0);
2199            }
2200
2201            if (mWhen != 0 && mShowWhen) {
2202                if (mUseChronometer) {
2203                    contentView.setViewVisibility(R.id.chronometer, View.VISIBLE);
2204                    contentView.setLong(R.id.chronometer, "setBase",
2205                            mWhen + (SystemClock.elapsedRealtime() - System.currentTimeMillis()));
2206                    contentView.setBoolean(R.id.chronometer, "setStarted", true);
2207                } else {
2208                    contentView.setViewVisibility(R.id.time, View.VISIBLE);
2209                    contentView.setLong(R.id.time, "setTime", mWhen);
2210                }
2211            } else {
2212                contentView.setViewVisibility(R.id.time, View.GONE);
2213            }
2214
2215            contentView.setViewVisibility(R.id.line3, showLine3 ? View.VISIBLE : View.GONE);
2216            contentView.setViewVisibility(R.id.overflow_divider, showLine3 ? View.VISIBLE : View.GONE);
2217            return contentView;
2218        }
2219
2220        private RemoteViews applyStandardTemplateWithActions(int layoutId) {
2221            RemoteViews big = applyStandardTemplate(layoutId, false);
2222
2223            int N = mActions.size();
2224            if (N > 0) {
2225                // Log.d("Notification", "has actions: " + mContentText);
2226                big.setViewVisibility(R.id.actions, View.VISIBLE);
2227                big.setViewVisibility(R.id.action_divider, View.VISIBLE);
2228                if (N>MAX_ACTION_BUTTONS) N=MAX_ACTION_BUTTONS;
2229                big.removeAllViews(R.id.actions);
2230                for (int i=0; i<N; i++) {
2231                    final RemoteViews button = generateActionButton(mActions.get(i));
2232                    //Log.d("Notification", "adding action " + i + ": " + mActions.get(i).title);
2233                    big.addView(R.id.actions, button);
2234                }
2235            }
2236            return big;
2237        }
2238
2239        private RemoteViews makeContentView() {
2240            if (mContentView != null) {
2241                return mContentView;
2242            } else {
2243                return applyStandardTemplate(R.layout.notification_template_base, true); // no more special large_icon flavor
2244            }
2245        }
2246
2247        private RemoteViews makeTickerView() {
2248            if (mTickerView != null) {
2249                return mTickerView;
2250            } else {
2251                if (mContentView == null) {
2252                    return applyStandardTemplate(mLargeIcon == null
2253                            ? R.layout.status_bar_latest_event_ticker
2254                            : R.layout.status_bar_latest_event_ticker_large_icon, true);
2255                } else {
2256                    return null;
2257                }
2258            }
2259        }
2260
2261        private RemoteViews makeBigContentView() {
2262            if (mActions.size() == 0) return null;
2263
2264            return applyStandardTemplateWithActions(R.layout.notification_template_big_base);
2265        }
2266
2267        private RemoteViews generateActionButton(Action action) {
2268            final boolean tombstone = (action.actionIntent == null);
2269            RemoteViews button = new RemoteViews(mContext.getPackageName(),
2270                    tombstone ? R.layout.notification_action_tombstone
2271                              : R.layout.notification_action);
2272            button.setTextViewCompoundDrawablesRelative(R.id.action0, action.icon, 0, 0, 0);
2273            button.setTextViewText(R.id.action0, action.title);
2274            if (!tombstone) {
2275                button.setOnClickPendingIntent(R.id.action0, action.actionIntent);
2276            }
2277            button.setContentDescription(R.id.action0, action.title);
2278            return button;
2279        }
2280
2281        /**
2282         * Apply the unstyled operations and return a new {@link Notification} object.
2283         * @hide
2284         */
2285        public Notification buildUnstyled() {
2286            Notification n = new Notification();
2287            n.when = mWhen;
2288            n.icon = mSmallIcon;
2289            n.iconLevel = mSmallIconLevel;
2290            n.number = mNumber;
2291            n.contentView = makeContentView();
2292            n.contentIntent = mContentIntent;
2293            n.deleteIntent = mDeleteIntent;
2294            n.fullScreenIntent = mFullScreenIntent;
2295            n.tickerText = mTickerText;
2296            n.tickerView = makeTickerView();
2297            n.largeIcon = mLargeIcon;
2298            n.sound = mSound;
2299            n.audioStreamType = mAudioStreamType;
2300            n.vibrate = mVibrate;
2301            n.ledARGB = mLedArgb;
2302            n.ledOnMS = mLedOnMs;
2303            n.ledOffMS = mLedOffMs;
2304            n.defaults = mDefaults;
2305            n.flags = mFlags;
2306            n.bigContentView = makeBigContentView();
2307            if (mLedOnMs != 0 || mLedOffMs != 0) {
2308                n.flags |= FLAG_SHOW_LIGHTS;
2309            }
2310            if ((mDefaults & DEFAULT_LIGHTS) != 0) {
2311                n.flags |= FLAG_SHOW_LIGHTS;
2312            }
2313            n.category = mCategory;
2314            n.mGroupKey = mGroupKey;
2315            n.mSortKey = mSortKey;
2316            n.priority = mPriority;
2317            if (mActions.size() > 0) {
2318                n.actions = new Action[mActions.size()];
2319                mActions.toArray(n.actions);
2320            }
2321            return n;
2322        }
2323
2324        /**
2325         * Capture, in the provided bundle, semantic information used in the construction of
2326         * this Notification object.
2327         * @hide
2328         */
2329        public void populateExtras(Bundle extras) {
2330            // Store original information used in the construction of this object
2331            extras.putCharSequence(EXTRA_TITLE, mContentTitle);
2332            extras.putCharSequence(EXTRA_TEXT, mContentText);
2333            extras.putCharSequence(EXTRA_SUB_TEXT, mSubText);
2334            extras.putCharSequence(EXTRA_INFO_TEXT, mContentInfo);
2335            extras.putInt(EXTRA_SMALL_ICON, mSmallIcon);
2336            extras.putInt(EXTRA_PROGRESS, mProgress);
2337            extras.putInt(EXTRA_PROGRESS_MAX, mProgressMax);
2338            extras.putBoolean(EXTRA_PROGRESS_INDETERMINATE, mProgressIndeterminate);
2339            extras.putBoolean(EXTRA_SHOW_CHRONOMETER, mUseChronometer);
2340            extras.putBoolean(EXTRA_SHOW_WHEN, mShowWhen);
2341            if (mLargeIcon != null) {
2342                extras.putParcelable(EXTRA_LARGE_ICON, mLargeIcon);
2343            }
2344        }
2345
2346        /**
2347         * @deprecated Use {@link #build()} instead.
2348         */
2349        @Deprecated
2350        public Notification getNotification() {
2351            return build();
2352        }
2353
2354        /**
2355         * Combine all of the options that have been set and return a new {@link Notification}
2356         * object.
2357         */
2358        public Notification build() {
2359            Notification n = buildUnstyled();
2360
2361            if (mStyle != null) {
2362                n = mStyle.buildStyled(n);
2363            }
2364
2365            n.extras = mExtras != null ? new Bundle(mExtras) : new Bundle();
2366
2367            populateExtras(n.extras);
2368            if (mStyle != null) {
2369                mStyle.addExtras(n.extras);
2370            }
2371
2372            return n;
2373        }
2374
2375        /**
2376         * Apply this Builder to an existing {@link Notification} object.
2377         *
2378         * @hide
2379         */
2380        public Notification buildInto(Notification n) {
2381            build().cloneInto(n, true);
2382            return n;
2383        }
2384    }
2385
2386    /**
2387     * An object that can apply a rich notification style to a {@link Notification.Builder}
2388     * object.
2389     */
2390    public static abstract class Style {
2391        private CharSequence mBigContentTitle;
2392        private CharSequence mSummaryText = null;
2393        private boolean mSummaryTextSet = false;
2394
2395        protected Builder mBuilder;
2396
2397        /**
2398         * Overrides ContentTitle in the big form of the template.
2399         * This defaults to the value passed to setContentTitle().
2400         */
2401        protected void internalSetBigContentTitle(CharSequence title) {
2402            mBigContentTitle = title;
2403        }
2404
2405        /**
2406         * Set the first line of text after the detail section in the big form of the template.
2407         */
2408        protected void internalSetSummaryText(CharSequence cs) {
2409            mSummaryText = cs;
2410            mSummaryTextSet = true;
2411        }
2412
2413        public void setBuilder(Builder builder) {
2414            if (mBuilder != builder) {
2415                mBuilder = builder;
2416                if (mBuilder != null) {
2417                    mBuilder.setStyle(this);
2418                }
2419            }
2420        }
2421
2422        protected void checkBuilder() {
2423            if (mBuilder == null) {
2424                throw new IllegalArgumentException("Style requires a valid Builder object");
2425            }
2426        }
2427
2428        protected RemoteViews getStandardView(int layoutId) {
2429            checkBuilder();
2430
2431            if (mBigContentTitle != null) {
2432                mBuilder.setContentTitle(mBigContentTitle);
2433            }
2434
2435            RemoteViews contentView = mBuilder.applyStandardTemplateWithActions(layoutId);
2436
2437            if (mBigContentTitle != null && mBigContentTitle.equals("")) {
2438                contentView.setViewVisibility(R.id.line1, View.GONE);
2439            } else {
2440                contentView.setViewVisibility(R.id.line1, View.VISIBLE);
2441            }
2442
2443            // The last line defaults to the subtext, but can be replaced by mSummaryText
2444            final CharSequence overflowText =
2445                    mSummaryTextSet ? mSummaryText
2446                                    : mBuilder.mSubText;
2447            if (overflowText != null) {
2448                contentView.setTextViewText(R.id.text, overflowText);
2449                contentView.setViewVisibility(R.id.overflow_divider, View.VISIBLE);
2450                contentView.setViewVisibility(R.id.line3, View.VISIBLE);
2451            } else {
2452                contentView.setViewVisibility(R.id.overflow_divider, View.GONE);
2453                contentView.setViewVisibility(R.id.line3, View.GONE);
2454            }
2455
2456            return contentView;
2457        }
2458
2459        /**
2460         * @hide
2461         */
2462        public void addExtras(Bundle extras) {
2463            if (mSummaryTextSet) {
2464                extras.putCharSequence(EXTRA_SUMMARY_TEXT, mSummaryText);
2465            }
2466            if (mBigContentTitle != null) {
2467                extras.putCharSequence(EXTRA_TITLE_BIG, mBigContentTitle);
2468            }
2469        }
2470
2471        /**
2472         * @hide
2473         */
2474        public abstract Notification buildStyled(Notification wip);
2475
2476        /**
2477         * Calls {@link android.app.Notification.Builder#build()} on the Builder this Style is
2478         * attached to.
2479         *
2480         * @return the fully constructed Notification.
2481         */
2482        public Notification build() {
2483            checkBuilder();
2484            return mBuilder.build();
2485        }
2486    }
2487
2488    /**
2489     * Helper class for generating large-format notifications that include a large image attachment.
2490     *
2491     * This class is a "rebuilder": It consumes a Builder object and modifies its behavior, like so:
2492     * <pre class="prettyprint">
2493     * Notification noti = new Notification.BigPictureStyle(
2494     *      new Notification.Builder()
2495     *         .setContentTitle(&quot;New photo from &quot; + sender.toString())
2496     *         .setContentText(subject)
2497     *         .setSmallIcon(R.drawable.new_post)
2498     *         .setLargeIcon(aBitmap))
2499     *      .bigPicture(aBigBitmap)
2500     *      .build();
2501     * </pre>
2502     *
2503     * @see Notification#bigContentView
2504     */
2505    public static class BigPictureStyle extends Style {
2506        private Bitmap mPicture;
2507        private Bitmap mBigLargeIcon;
2508        private boolean mBigLargeIconSet = false;
2509
2510        public BigPictureStyle() {
2511        }
2512
2513        public BigPictureStyle(Builder builder) {
2514            setBuilder(builder);
2515        }
2516
2517        /**
2518         * Overrides ContentTitle in the big form of the template.
2519         * This defaults to the value passed to setContentTitle().
2520         */
2521        public BigPictureStyle setBigContentTitle(CharSequence title) {
2522            internalSetBigContentTitle(safeCharSequence(title));
2523            return this;
2524        }
2525
2526        /**
2527         * Set the first line of text after the detail section in the big form of the template.
2528         */
2529        public BigPictureStyle setSummaryText(CharSequence cs) {
2530            internalSetSummaryText(safeCharSequence(cs));
2531            return this;
2532        }
2533
2534        /**
2535         * Provide the bitmap to be used as the payload for the BigPicture notification.
2536         */
2537        public BigPictureStyle bigPicture(Bitmap b) {
2538            mPicture = b;
2539            return this;
2540        }
2541
2542        /**
2543         * Override the large icon when the big notification is shown.
2544         */
2545        public BigPictureStyle bigLargeIcon(Bitmap b) {
2546            mBigLargeIconSet = true;
2547            mBigLargeIcon = b;
2548            return this;
2549        }
2550
2551        private RemoteViews makeBigContentView() {
2552            RemoteViews contentView = getStandardView(R.layout.notification_template_big_picture);
2553
2554            contentView.setImageViewBitmap(R.id.big_picture, mPicture);
2555
2556            return contentView;
2557        }
2558
2559        /**
2560         * @hide
2561         */
2562        public void addExtras(Bundle extras) {
2563            super.addExtras(extras);
2564
2565            if (mBigLargeIconSet) {
2566                extras.putParcelable(EXTRA_LARGE_ICON_BIG, mBigLargeIcon);
2567            }
2568            extras.putParcelable(EXTRA_PICTURE, mPicture);
2569        }
2570
2571        /**
2572         * @hide
2573         */
2574        @Override
2575        public Notification buildStyled(Notification wip) {
2576            if (mBigLargeIconSet ) {
2577                mBuilder.mLargeIcon = mBigLargeIcon;
2578            }
2579            wip.bigContentView = makeBigContentView();
2580            return wip;
2581        }
2582    }
2583
2584    /**
2585     * Helper class for generating large-format notifications that include a lot of text.
2586     *
2587     * This class is a "rebuilder": It consumes a Builder object and modifies its behavior, like so:
2588     * <pre class="prettyprint">
2589     * Notification noti = new Notification.BigTextStyle(
2590     *      new Notification.Builder()
2591     *         .setContentTitle(&quot;New mail from &quot; + sender.toString())
2592     *         .setContentText(subject)
2593     *         .setSmallIcon(R.drawable.new_mail)
2594     *         .setLargeIcon(aBitmap))
2595     *      .bigText(aVeryLongString)
2596     *      .build();
2597     * </pre>
2598     *
2599     * @see Notification#bigContentView
2600     */
2601    public static class BigTextStyle extends Style {
2602        private CharSequence mBigText;
2603
2604        public BigTextStyle() {
2605        }
2606
2607        public BigTextStyle(Builder builder) {
2608            setBuilder(builder);
2609        }
2610
2611        /**
2612         * Overrides ContentTitle in the big form of the template.
2613         * This defaults to the value passed to setContentTitle().
2614         */
2615        public BigTextStyle setBigContentTitle(CharSequence title) {
2616            internalSetBigContentTitle(safeCharSequence(title));
2617            return this;
2618        }
2619
2620        /**
2621         * Set the first line of text after the detail section in the big form of the template.
2622         */
2623        public BigTextStyle setSummaryText(CharSequence cs) {
2624            internalSetSummaryText(safeCharSequence(cs));
2625            return this;
2626        }
2627
2628        /**
2629         * Provide the longer text to be displayed in the big form of the
2630         * template in place of the content text.
2631         */
2632        public BigTextStyle bigText(CharSequence cs) {
2633            mBigText = safeCharSequence(cs);
2634            return this;
2635        }
2636
2637        /**
2638         * @hide
2639         */
2640        public void addExtras(Bundle extras) {
2641            super.addExtras(extras);
2642
2643            extras.putCharSequence(EXTRA_TEXT, mBigText);
2644        }
2645
2646        private RemoteViews makeBigContentView() {
2647            // Remove the content text so line3 only shows if you have a summary
2648            final boolean hadThreeLines = (mBuilder.mContentText != null && mBuilder.mSubText != null);
2649            mBuilder.mContentText = null;
2650
2651            RemoteViews contentView = getStandardView(R.layout.notification_template_big_text);
2652
2653            if (hadThreeLines) {
2654                // vertical centering
2655                contentView.setViewPadding(R.id.line1, 0, 0, 0, 0);
2656            }
2657
2658            contentView.setTextViewText(R.id.big_text, mBigText);
2659            contentView.setViewVisibility(R.id.big_text, View.VISIBLE);
2660            contentView.setViewVisibility(R.id.text2, View.GONE);
2661
2662            return contentView;
2663        }
2664
2665        /**
2666         * @hide
2667         */
2668        @Override
2669        public Notification buildStyled(Notification wip) {
2670            wip.bigContentView = makeBigContentView();
2671
2672            wip.extras.putCharSequence(EXTRA_TEXT, mBigText);
2673
2674            return wip;
2675        }
2676    }
2677
2678    /**
2679     * Helper class for generating large-format notifications that include a list of (up to 5) strings.
2680     *
2681     * This class is a "rebuilder": It consumes a Builder object and modifies its behavior, like so:
2682     * <pre class="prettyprint">
2683     * Notification noti = new Notification.InboxStyle(
2684     *      new Notification.Builder()
2685     *         .setContentTitle(&quot;5 New mails from &quot; + sender.toString())
2686     *         .setContentText(subject)
2687     *         .setSmallIcon(R.drawable.new_mail)
2688     *         .setLargeIcon(aBitmap))
2689     *      .addLine(str1)
2690     *      .addLine(str2)
2691     *      .setContentTitle("")
2692     *      .setSummaryText(&quot;+3 more&quot;)
2693     *      .build();
2694     * </pre>
2695     *
2696     * @see Notification#bigContentView
2697     */
2698    public static class InboxStyle extends Style {
2699        private ArrayList<CharSequence> mTexts = new ArrayList<CharSequence>(5);
2700
2701        public InboxStyle() {
2702        }
2703
2704        public InboxStyle(Builder builder) {
2705            setBuilder(builder);
2706        }
2707
2708        /**
2709         * Overrides ContentTitle in the big form of the template.
2710         * This defaults to the value passed to setContentTitle().
2711         */
2712        public InboxStyle setBigContentTitle(CharSequence title) {
2713            internalSetBigContentTitle(safeCharSequence(title));
2714            return this;
2715        }
2716
2717        /**
2718         * Set the first line of text after the detail section in the big form of the template.
2719         */
2720        public InboxStyle setSummaryText(CharSequence cs) {
2721            internalSetSummaryText(safeCharSequence(cs));
2722            return this;
2723        }
2724
2725        /**
2726         * Append a line to the digest section of the Inbox notification.
2727         */
2728        public InboxStyle addLine(CharSequence cs) {
2729            mTexts.add(safeCharSequence(cs));
2730            return this;
2731        }
2732
2733        /**
2734         * @hide
2735         */
2736        public void addExtras(Bundle extras) {
2737            super.addExtras(extras);
2738            CharSequence[] a = new CharSequence[mTexts.size()];
2739            extras.putCharSequenceArray(EXTRA_TEXT_LINES, mTexts.toArray(a));
2740        }
2741
2742        private RemoteViews makeBigContentView() {
2743            // Remove the content text so line3 disappears unless you have a summary
2744            mBuilder.mContentText = null;
2745            RemoteViews contentView = getStandardView(R.layout.notification_template_inbox);
2746
2747            contentView.setViewVisibility(R.id.text2, View.GONE);
2748
2749            int[] rowIds = {R.id.inbox_text0, R.id.inbox_text1, R.id.inbox_text2, R.id.inbox_text3,
2750                    R.id.inbox_text4, R.id.inbox_text5, R.id.inbox_text6};
2751
2752            // Make sure all rows are gone in case we reuse a view.
2753            for (int rowId : rowIds) {
2754                contentView.setViewVisibility(rowId, View.GONE);
2755            }
2756
2757
2758            int i=0;
2759            while (i < mTexts.size() && i < rowIds.length) {
2760                CharSequence str = mTexts.get(i);
2761                if (str != null && !str.equals("")) {
2762                    contentView.setViewVisibility(rowIds[i], View.VISIBLE);
2763                    contentView.setTextViewText(rowIds[i], str);
2764                }
2765                i++;
2766            }
2767
2768            contentView.setViewVisibility(R.id.inbox_end_pad,
2769                    mTexts.size() > 0 ? View.VISIBLE : View.GONE);
2770
2771            contentView.setViewVisibility(R.id.inbox_more,
2772                    mTexts.size() > rowIds.length ? View.VISIBLE : View.GONE);
2773
2774            return contentView;
2775        }
2776
2777        /**
2778         * @hide
2779         */
2780        @Override
2781        public Notification buildStyled(Notification wip) {
2782            wip.bigContentView = makeBigContentView();
2783
2784            return wip;
2785        }
2786    }
2787
2788    /**
2789     * Extender interface for use with {@link Builder#extend}. Extenders may be used to add
2790     * metadata or change options on a notification builder.
2791     */
2792    public interface Extender {
2793        /**
2794         * Apply this extender to a notification builder.
2795         * @param builder the builder to be modified.
2796         * @return the build object for chaining.
2797         */
2798        public Builder extend(Builder builder);
2799    }
2800
2801    /**
2802     * Helper class to add wearable extensions to notifications.
2803     * <p class="note"> See
2804     * <a href="{@docRoot}wear/notifications/creating.html">Creating Notifications
2805     * for Android Wear</a> for more information on how to use this class.
2806     * <p>
2807     * To create a notification with wearable extensions:
2808     * <ol>
2809     *   <li>Create a {@link android.app.Notification.Builder}, setting any desired
2810     *   properties.
2811     *   <li>Create a {@link android.app.Notification.WearableExtender}.
2812     *   <li>Set wearable-specific properties using the
2813     *   {@code add} and {@code set} methods of {@link android.app.Notification.WearableExtender}.
2814     *   <li>Call {@link android.app.Notification.Builder#extend} to apply the extensions to a
2815     *   notification.
2816     *   <li>Post the notification to the notification system with the
2817     *   {@code NotificationManager.notify(...)} methods.
2818     * </ol>
2819     *
2820     * <pre class="prettyprint">
2821     * Notification notif = new Notification.Builder(mContext)
2822     *         .setContentTitle(&quot;New mail from &quot; + sender.toString())
2823     *         .setContentText(subject)
2824     *         .setSmallIcon(R.drawable.new_mail)
2825     *         .extend(new Notification.WearableExtender()
2826     *                 .setContentIcon(R.drawable.new_mail))
2827     *         .build();
2828     * NotificationManager notificationManger =
2829     *         (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
2830     * notificationManger.notify(0, notif);</pre>
2831     *
2832     * <p>Wearable extensions can be accessed on an existing notification by using the
2833     * {@code WearableExtender(Notification)} constructor,
2834     * and then using the {@code get} methods to access values.
2835     *
2836     * <pre class="prettyprint">
2837     * Notification.WearableExtender wearableExtender = new Notification.WearableExtender(
2838     *         notification);
2839     * List&lt;Notification&gt; pages = wearableExtender.getPages();</pre>
2840     */
2841    public static final class WearableExtender implements Extender {
2842        /**
2843         * Sentinel value for an action index that is unset.
2844         */
2845        public static final int UNSET_ACTION_INDEX = -1;
2846
2847        /**
2848         * Size value for use with {@link #setCustomSizePreset} to show this notification with
2849         * default sizing.
2850         * <p>For custom display notifications created using {@link #setDisplayIntent},
2851         * the default is {@link #SIZE_LARGE}. All other notifications size automatically based
2852         * on their content.
2853         */
2854        public static final int SIZE_DEFAULT = 0;
2855
2856        /**
2857         * Size value for use with {@link #setCustomSizePreset} to show this notification
2858         * with an extra small size.
2859         * <p>This value is only applicable for custom display notifications created using
2860         * {@link #setDisplayIntent}.
2861         */
2862        public static final int SIZE_XSMALL = 1;
2863
2864        /**
2865         * Size value for use with {@link #setCustomSizePreset} to show this notification
2866         * with a small size.
2867         * <p>This value is only applicable for custom display notifications created using
2868         * {@link #setDisplayIntent}.
2869         */
2870        public static final int SIZE_SMALL = 2;
2871
2872        /**
2873         * Size value for use with {@link #setCustomSizePreset} to show this notification
2874         * with a medium size.
2875         * <p>This value is only applicable for custom display notifications created using
2876         * {@link #setDisplayIntent}.
2877         */
2878        public static final int SIZE_MEDIUM = 3;
2879
2880        /**
2881         * Size value for use with {@link #setCustomSizePreset} to show this notification
2882         * with a large size.
2883         * <p>This value is only applicable for custom display notifications created using
2884         * {@link #setDisplayIntent}.
2885         */
2886        public static final int SIZE_LARGE = 4;
2887
2888        /** Notification extra which contains wearable extensions */
2889        private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS";
2890
2891        // Keys within EXTRA_WEARABLE_OPTIONS for wearable options.
2892        private static final String KEY_ACTIONS = "actions";
2893        private static final String KEY_FLAGS = "flags";
2894        private static final String KEY_DISPLAY_INTENT = "displayIntent";
2895        private static final String KEY_PAGES = "pages";
2896        private static final String KEY_BACKGROUND = "background";
2897        private static final String KEY_CONTENT_ICON = "contentIcon";
2898        private static final String KEY_CONTENT_ICON_GRAVITY = "contentIconGravity";
2899        private static final String KEY_CONTENT_ACTION_INDEX = "contentActionIndex";
2900        private static final String KEY_CUSTOM_SIZE_PRESET = "customSizePreset";
2901        private static final String KEY_CUSTOM_CONTENT_HEIGHT = "customContentHeight";
2902        private static final String KEY_GRAVITY = "gravity";
2903
2904        // Flags bitwise-ored to mFlags
2905        private static final int FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE = 0x1;
2906        private static final int FLAG_HINT_HIDE_ICON = 1 << 1;
2907        private static final int FLAG_HINT_SHOW_BACKGROUND_ONLY = 1 << 2;
2908        private static final int FLAG_START_SCROLL_BOTTOM = 1 << 3;
2909
2910        // Default value for flags integer
2911        private static final int DEFAULT_FLAGS = FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE;
2912
2913        private static final int DEFAULT_CONTENT_ICON_GRAVITY = Gravity.END;
2914        private static final int DEFAULT_GRAVITY = Gravity.BOTTOM;
2915
2916        private ArrayList<Action> mActions = new ArrayList<Action>();
2917        private int mFlags = DEFAULT_FLAGS;
2918        private PendingIntent mDisplayIntent;
2919        private ArrayList<Notification> mPages = new ArrayList<Notification>();
2920        private Bitmap mBackground;
2921        private int mContentIcon;
2922        private int mContentIconGravity = DEFAULT_CONTENT_ICON_GRAVITY;
2923        private int mContentActionIndex = UNSET_ACTION_INDEX;
2924        private int mCustomSizePreset = SIZE_DEFAULT;
2925        private int mCustomContentHeight;
2926        private int mGravity = DEFAULT_GRAVITY;
2927
2928        /**
2929         * Create a {@link android.app.Notification.WearableExtender} with default
2930         * options.
2931         */
2932        public WearableExtender() {
2933        }
2934
2935        public WearableExtender(Notification notif) {
2936            Bundle wearableBundle = notif.extras.getBundle(EXTRA_WEARABLE_EXTENSIONS);
2937            if (wearableBundle != null) {
2938                List<Action> actions = wearableBundle.getParcelableArrayList(KEY_ACTIONS);
2939                if (actions != null) {
2940                    mActions.addAll(actions);
2941                }
2942
2943                mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS);
2944                mDisplayIntent = wearableBundle.getParcelable(KEY_DISPLAY_INTENT);
2945
2946                Notification[] pages = getNotificationArrayFromBundle(
2947                        wearableBundle, KEY_PAGES);
2948                if (pages != null) {
2949                    Collections.addAll(mPages, pages);
2950                }
2951
2952                mBackground = wearableBundle.getParcelable(KEY_BACKGROUND);
2953                mContentIcon = wearableBundle.getInt(KEY_CONTENT_ICON);
2954                mContentIconGravity = wearableBundle.getInt(KEY_CONTENT_ICON_GRAVITY,
2955                        DEFAULT_CONTENT_ICON_GRAVITY);
2956                mContentActionIndex = wearableBundle.getInt(KEY_CONTENT_ACTION_INDEX,
2957                        UNSET_ACTION_INDEX);
2958                mCustomSizePreset = wearableBundle.getInt(KEY_CUSTOM_SIZE_PRESET,
2959                        SIZE_DEFAULT);
2960                mCustomContentHeight = wearableBundle.getInt(KEY_CUSTOM_CONTENT_HEIGHT);
2961                mGravity = wearableBundle.getInt(KEY_GRAVITY, DEFAULT_GRAVITY);
2962            }
2963        }
2964
2965        /**
2966         * Apply wearable extensions to a notification that is being built. This is typically
2967         * called by the {@link android.app.Notification.Builder#extend} method of
2968         * {@link android.app.Notification.Builder}.
2969         */
2970        @Override
2971        public Notification.Builder extend(Notification.Builder builder) {
2972            Bundle wearableBundle = new Bundle();
2973
2974            if (!mActions.isEmpty()) {
2975                wearableBundle.putParcelableArrayList(KEY_ACTIONS, mActions);
2976            }
2977            if (mFlags != DEFAULT_FLAGS) {
2978                wearableBundle.putInt(KEY_FLAGS, mFlags);
2979            }
2980            if (mDisplayIntent != null) {
2981                wearableBundle.putParcelable(KEY_DISPLAY_INTENT, mDisplayIntent);
2982            }
2983            if (!mPages.isEmpty()) {
2984                wearableBundle.putParcelableArray(KEY_PAGES, mPages.toArray(
2985                        new Notification[mPages.size()]));
2986            }
2987            if (mBackground != null) {
2988                wearableBundle.putParcelable(KEY_BACKGROUND, mBackground);
2989            }
2990            if (mContentIcon != 0) {
2991                wearableBundle.putInt(KEY_CONTENT_ICON, mContentIcon);
2992            }
2993            if (mContentIconGravity != DEFAULT_CONTENT_ICON_GRAVITY) {
2994                wearableBundle.putInt(KEY_CONTENT_ICON_GRAVITY, mContentIconGravity);
2995            }
2996            if (mContentActionIndex != UNSET_ACTION_INDEX) {
2997                wearableBundle.putInt(KEY_CONTENT_ACTION_INDEX,
2998                        mContentActionIndex);
2999            }
3000            if (mCustomSizePreset != SIZE_DEFAULT) {
3001                wearableBundle.putInt(KEY_CUSTOM_SIZE_PRESET, mCustomSizePreset);
3002            }
3003            if (mCustomContentHeight != 0) {
3004                wearableBundle.putInt(KEY_CUSTOM_CONTENT_HEIGHT, mCustomContentHeight);
3005            }
3006            if (mGravity != DEFAULT_GRAVITY) {
3007                wearableBundle.putInt(KEY_GRAVITY, mGravity);
3008            }
3009
3010            builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle);
3011            return builder;
3012        }
3013
3014        @Override
3015        public WearableExtender clone() {
3016            WearableExtender that = new WearableExtender();
3017            that.mActions = new ArrayList<Action>(this.mActions);
3018            that.mFlags = this.mFlags;
3019            that.mDisplayIntent = this.mDisplayIntent;
3020            that.mPages = new ArrayList<Notification>(this.mPages);
3021            that.mBackground = this.mBackground;
3022            that.mContentIcon = this.mContentIcon;
3023            that.mContentIconGravity = this.mContentIconGravity;
3024            that.mContentActionIndex = this.mContentActionIndex;
3025            that.mCustomSizePreset = this.mCustomSizePreset;
3026            that.mCustomContentHeight = this.mCustomContentHeight;
3027            that.mGravity = this.mGravity;
3028            return that;
3029        }
3030
3031        /**
3032         * Add a wearable action to this notification.
3033         *
3034         * <p>When wearable actions are added using this method, the set of actions that
3035         * show on a wearable device splits from devices that only show actions added
3036         * using {@link android.app.Notification.Builder#addAction}. This allows for customization
3037         * of which actions display on different devices.
3038         *
3039         * @param action the action to add to this notification
3040         * @return this object for method chaining
3041         * @see android.app.Notification.Action
3042         */
3043        public WearableExtender addAction(Action action) {
3044            mActions.add(action);
3045            return this;
3046        }
3047
3048        /**
3049         * Adds wearable actions to this notification.
3050         *
3051         * <p>When wearable actions are added using this method, the set of actions that
3052         * show on a wearable device splits from devices that only show actions added
3053         * using {@link android.app.Notification.Builder#addAction}. This allows for customization
3054         * of which actions display on different devices.
3055         *
3056         * @param actions the actions to add to this notification
3057         * @return this object for method chaining
3058         * @see android.app.Notification.Action
3059         */
3060        public WearableExtender addActions(List<Action> actions) {
3061            mActions.addAll(actions);
3062            return this;
3063        }
3064
3065        /**
3066         * Clear all wearable actions present on this builder.
3067         * @return this object for method chaining.
3068         * @see #addAction
3069         */
3070        public WearableExtender clearActions() {
3071            mActions.clear();
3072            return this;
3073        }
3074
3075        /**
3076         * Get the wearable actions present on this notification.
3077         */
3078        public List<Action> getActions() {
3079            return mActions;
3080        }
3081
3082        /**
3083         * Set an intent to launch inside of an activity view when displaying
3084         * this notification. The {@link PendingIntent} provided should be for an activity.
3085         *
3086         * <pre class="prettyprint">
3087         * Intent displayIntent = new Intent(context, MyDisplayActivity.class);
3088         * PendingIntent displayPendingIntent = PendingIntent.getActivity(context,
3089         *         0, displayIntent, PendingIntent.FLAG_UPDATE_CURRENT);
3090         * Notification notif = new Notification.Builder(context)
3091         *         .extend(new Notification.WearableExtender()
3092         *                 .setDisplayIntent(displayPendingIntent)
3093         *                 .setCustomSizePreset(Notification.WearableExtender.SIZE_MEDIUM))
3094         *         .build();</pre>
3095         *
3096         * <p>The activity to launch needs to allow embedding, must be exported, and
3097         * should have an empty task affinity.
3098         *
3099         * <p>Example AndroidManifest.xml entry:
3100         * <pre class="prettyprint">
3101         * &lt;activity android:name=&quot;com.example.MyDisplayActivity&quot;
3102         *     android:exported=&quot;true&quot;
3103         *     android:allowEmbedded=&quot;true&quot;
3104         *     android:taskAffinity=&quot;&quot; /&gt;</pre>
3105         *
3106         * @param intent the {@link PendingIntent} for an activity
3107         * @return this object for method chaining
3108         * @see android.app.Notification.WearableExtender#getDisplayIntent
3109         */
3110        public WearableExtender setDisplayIntent(PendingIntent intent) {
3111            mDisplayIntent = intent;
3112            return this;
3113        }
3114
3115        /**
3116         * Get the intent to launch inside of an activity view when displaying this
3117         * notification. This {@code PendingIntent} should be for an activity.
3118         */
3119        public PendingIntent getDisplayIntent() {
3120            return mDisplayIntent;
3121        }
3122
3123        /**
3124         * Add an additional page of content to display with this notification. The current
3125         * notification forms the first page, and pages added using this function form
3126         * subsequent pages. This field can be used to separate a notification into multiple
3127         * sections.
3128         *
3129         * @param page the notification to add as another page
3130         * @return this object for method chaining
3131         * @see android.app.Notification.WearableExtender#getPages
3132         */
3133        public WearableExtender addPage(Notification page) {
3134            mPages.add(page);
3135            return this;
3136        }
3137
3138        /**
3139         * Add additional pages of content to display with this notification. The current
3140         * notification forms the first page, and pages added using this function form
3141         * subsequent pages. This field can be used to separate a notification into multiple
3142         * sections.
3143         *
3144         * @param pages a list of notifications
3145         * @return this object for method chaining
3146         * @see android.app.Notification.WearableExtender#getPages
3147         */
3148        public WearableExtender addPages(List<Notification> pages) {
3149            mPages.addAll(pages);
3150            return this;
3151        }
3152
3153        /**
3154         * Clear all additional pages present on this builder.
3155         * @return this object for method chaining.
3156         * @see #addPage
3157         */
3158        public WearableExtender clearPages() {
3159            mPages.clear();
3160            return this;
3161        }
3162
3163        /**
3164         * Get the array of additional pages of content for displaying this notification. The
3165         * current notification forms the first page, and elements within this array form
3166         * subsequent pages. This field can be used to separate a notification into multiple
3167         * sections.
3168         * @return the pages for this notification
3169         */
3170        public List<Notification> getPages() {
3171            return mPages;
3172        }
3173
3174        /**
3175         * Set a background image to be displayed behind the notification content.
3176         * Contrary to the {@link android.app.Notification.BigPictureStyle}, this background
3177         * will work with any notification style.
3178         *
3179         * @param background the background bitmap
3180         * @return this object for method chaining
3181         * @see android.app.Notification.WearableExtender#getBackground
3182         */
3183        public WearableExtender setBackground(Bitmap background) {
3184            mBackground = background;
3185            return this;
3186        }
3187
3188        /**
3189         * Get a background image to be displayed behind the notification content.
3190         * Contrary to the {@link android.app.Notification.BigPictureStyle}, this background
3191         * will work with any notification style.
3192         *
3193         * @return the background image
3194         * @see android.app.Notification.WearableExtender#setBackground
3195         */
3196        public Bitmap getBackground() {
3197            return mBackground;
3198        }
3199
3200        /**
3201         * Set an icon that goes with the content of this notification.
3202         */
3203        public WearableExtender setContentIcon(int icon) {
3204            mContentIcon = icon;
3205            return this;
3206        }
3207
3208        /**
3209         * Get an icon that goes with the content of this notification.
3210         */
3211        public int getContentIcon() {
3212            return mContentIcon;
3213        }
3214
3215        /**
3216         * Set the gravity that the content icon should have within the notification display.
3217         * Supported values include {@link android.view.Gravity#START} and
3218         * {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}.
3219         * @see #setContentIcon
3220         */
3221        public WearableExtender setContentIconGravity(int contentIconGravity) {
3222            mContentIconGravity = contentIconGravity;
3223            return this;
3224        }
3225
3226        /**
3227         * Get the gravity that the content icon should have within the notification display.
3228         * Supported values include {@link android.view.Gravity#START} and
3229         * {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}.
3230         * @see #getContentIcon
3231         */
3232        public int getContentIconGravity() {
3233            return mContentIconGravity;
3234        }
3235
3236        /**
3237         * Set an action from this notification's actions to be clickable with the content of
3238         * this notification. This action will no longer display separately from the
3239         * notification's content.
3240         *
3241         * <p>For notifications with multiple pages, child pages can also have content action's
3242         * set, although the list of available actions comes from the main notification and not
3243         * from the child page's notification.
3244         *
3245         * @param actionIndex The index of the action to hoist onto the current notification page.
3246         *                    If wearable actions were added to the main notification, this index
3247         *                    will apply to that list, otherwise it will apply to the regular
3248         *                    actions list.
3249         */
3250        public WearableExtender setContentAction(int actionIndex) {
3251            mContentActionIndex = actionIndex;
3252            return this;
3253        }
3254
3255        /**
3256         * Get the action index from this notification's actions to be clickable with the
3257         * content of this notification. This action will no longer display separately
3258         * from the notification's content.
3259         *
3260         * <p>For notifications with multiple pages, child pages can also have content action's
3261         * set, although the list of available actions comes from the main notification and not
3262         * from the child page's notification.
3263         *
3264         * <p>If wearable specific actions were added to the main notification, this index will
3265         * apply to that list, otherwise it will apply to the regular actions list.
3266         */
3267        public int getContentAction() {
3268            return mContentActionIndex;
3269        }
3270
3271        /**
3272         * Set the gravity that this notification should have within the available viewport space.
3273         * Supported values include {@link android.view.Gravity#TOP},
3274         * {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}.
3275         * The default value is {@link android.view.Gravity#BOTTOM}.
3276         */
3277        public WearableExtender setGravity(int gravity) {
3278            mGravity = gravity;
3279            return this;
3280        }
3281
3282        /**
3283         * Get the gravity that this notification should have within the available viewport space.
3284         * Supported values include {@link android.view.Gravity#TOP},
3285         * {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}.
3286         * The default value is {@link android.view.Gravity#BOTTOM}.
3287         */
3288        public int getGravity() {
3289            return mGravity;
3290        }
3291
3292        /**
3293         * Set the custom size preset for the display of this notification out of the available
3294         * presets found in {@link android.app.Notification.WearableExtender}, e.g.
3295         * {@link #SIZE_LARGE}.
3296         * <p>Some custom size presets are only applicable for custom display notifications created
3297         * using {@link android.app.Notification.WearableExtender#setDisplayIntent}. Check the
3298         * documentation for the preset in question. See also
3299         * {@link #setCustomContentHeight} and {@link #getCustomSizePreset}.
3300         */
3301        public WearableExtender setCustomSizePreset(int sizePreset) {
3302            mCustomSizePreset = sizePreset;
3303            return this;
3304        }
3305
3306        /**
3307         * Get the custom size preset for the display of this notification out of the available
3308         * presets found in {@link android.app.Notification.WearableExtender}, e.g.
3309         * {@link #SIZE_LARGE}.
3310         * <p>Some custom size presets are only applicable for custom display notifications created
3311         * using {@link #setDisplayIntent}. Check the documentation for the preset in question.
3312         * See also {@link #setCustomContentHeight} and {@link #setCustomSizePreset}.
3313         */
3314        public int getCustomSizePreset() {
3315            return mCustomSizePreset;
3316        }
3317
3318        /**
3319         * Set the custom height in pixels for the display of this notification's content.
3320         * <p>This option is only available for custom display notifications created
3321         * using {@link android.app.Notification.WearableExtender#setDisplayIntent}. See also
3322         * {@link android.app.Notification.WearableExtender#setCustomSizePreset} and
3323         * {@link #getCustomContentHeight}.
3324         */
3325        public WearableExtender setCustomContentHeight(int height) {
3326            mCustomContentHeight = height;
3327            return this;
3328        }
3329
3330        /**
3331         * Get the custom height in pixels for the display of this notification's content.
3332         * <p>This option is only available for custom display notifications created
3333         * using {@link #setDisplayIntent}. See also {@link #setCustomSizePreset} and
3334         * {@link #setCustomContentHeight}.
3335         */
3336        public int getCustomContentHeight() {
3337            return mCustomContentHeight;
3338        }
3339
3340        /**
3341         * Set whether the scrolling position for the contents of this notification should start
3342         * at the bottom of the contents instead of the top when the contents are too long to
3343         * display within the screen.  Default is false (start scroll at the top).
3344         */
3345        public WearableExtender setStartScrollBottom(boolean startScrollBottom) {
3346            setFlag(FLAG_START_SCROLL_BOTTOM, startScrollBottom);
3347            return this;
3348        }
3349
3350        /**
3351         * Get whether the scrolling position for the contents of this notification should start
3352         * at the bottom of the contents instead of the top when the contents are too long to
3353         * display within the screen. Default is false (start scroll at the top).
3354         */
3355        public boolean getStartScrollBottom() {
3356            return (mFlags & FLAG_START_SCROLL_BOTTOM) != 0;
3357        }
3358
3359        /**
3360         * Set whether the content intent is available when the wearable device is not connected
3361         * to a companion device.  The user can still trigger this intent when the wearable device
3362         * is offline, but a visual hint will indicate that the content intent may not be available.
3363         * Defaults to true.
3364         */
3365        public WearableExtender setContentIntentAvailableOffline(
3366                boolean contentIntentAvailableOffline) {
3367            setFlag(FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE, contentIntentAvailableOffline);
3368            return this;
3369        }
3370
3371        /**
3372         * Get whether the content intent is available when the wearable device is not connected
3373         * to a companion device.  The user can still trigger this intent when the wearable device
3374         * is offline, but a visual hint will indicate that the content intent may not be available.
3375         * Defaults to true.
3376         */
3377        public boolean getContentIntentAvailableOffline() {
3378            return (mFlags & FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE) != 0;
3379        }
3380
3381        /**
3382         * Set a hint that this notification's icon should not be displayed.
3383         * @param hintHideIcon {@code true} to hide the icon, {@code false} otherwise.
3384         * @return this object for method chaining
3385         */
3386        public WearableExtender setHintHideIcon(boolean hintHideIcon) {
3387            setFlag(FLAG_HINT_HIDE_ICON, hintHideIcon);
3388            return this;
3389        }
3390
3391        /**
3392         * Get a hint that this notification's icon should not be displayed.
3393         * @return {@code true} if this icon should not be displayed, false otherwise.
3394         * The default value is {@code false} if this was never set.
3395         */
3396        public boolean getHintHideIcon() {
3397            return (mFlags & FLAG_HINT_HIDE_ICON) != 0;
3398        }
3399
3400        /**
3401         * Set a visual hint that only the background image of this notification should be
3402         * displayed, and other semantic content should be hidden. This hint is only applicable
3403         * to sub-pages added using {@link #addPage}.
3404         */
3405        public WearableExtender setHintShowBackgroundOnly(boolean hintShowBackgroundOnly) {
3406            setFlag(FLAG_HINT_SHOW_BACKGROUND_ONLY, hintShowBackgroundOnly);
3407            return this;
3408        }
3409
3410        /**
3411         * Get a visual hint that only the background image of this notification should be
3412         * displayed, and other semantic content should be hidden. This hint is only applicable
3413         * to sub-pages added using {@link android.app.Notification.WearableExtender#addPage}.
3414         */
3415        public boolean getHintShowBackgroundOnly() {
3416            return (mFlags & FLAG_HINT_SHOW_BACKGROUND_ONLY) != 0;
3417        }
3418
3419        private void setFlag(int mask, boolean value) {
3420            if (value) {
3421                mFlags |= mask;
3422            } else {
3423                mFlags &= ~mask;
3424            }
3425        }
3426    }
3427
3428    /**
3429     * Get an array of Notification objects from a parcelable array bundle field.
3430     * Update the bundle to have a typed array so fetches in the future don't need
3431     * to do an array copy.
3432     */
3433    private static Notification[] getNotificationArrayFromBundle(Bundle bundle, String key) {
3434        Parcelable[] array = bundle.getParcelableArray(key);
3435        if (array instanceof Notification[] || array == null) {
3436            return (Notification[]) array;
3437        }
3438        Notification[] typedArray = Arrays.copyOf(array, array.length,
3439                Notification[].class);
3440        bundle.putParcelableArray(key, typedArray);
3441        return typedArray;
3442    }
3443}
3444