Notification.java revision d05aa3ee47579283a20f4e5957fc319c6e76a74a
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.annotation.IntDef;
20import android.annotation.SdkConstant;
21import android.annotation.SdkConstant.SdkConstantType;
22import android.content.Context;
23import android.content.Intent;
24import android.content.pm.PackageManager.NameNotFoundException;
25import android.content.res.Resources;
26import android.graphics.Bitmap;
27import android.graphics.Canvas;
28import android.graphics.PorterDuff;
29import android.graphics.drawable.Drawable;
30import android.media.AudioAttributes;
31import android.media.AudioManager;
32import android.media.session.MediaSession;
33import android.net.Uri;
34import android.os.BadParcelableException;
35import android.os.Build;
36import android.os.Bundle;
37import android.os.Parcel;
38import android.os.Parcelable;
39import android.os.SystemClock;
40import android.os.UserHandle;
41import android.os.UserManager;
42import android.text.TextUtils;
43import android.util.Log;
44import android.util.MathUtils;
45import android.util.TypedValue;
46import android.view.Gravity;
47import android.view.View;
48import android.widget.ProgressBar;
49import android.widget.RemoteViews;
50
51import com.android.internal.R;
52import com.android.internal.util.NotificationColorUtil;
53
54import java.lang.annotation.Retention;
55import java.lang.annotation.RetentionPolicy;
56import java.lang.reflect.Constructor;
57import java.text.NumberFormat;
58import java.util.ArrayList;
59import java.util.Arrays;
60import java.util.Collections;
61import java.util.List;
62
63/**
64 * A class that represents how a persistent notification is to be presented to
65 * the user using the {@link android.app.NotificationManager}.
66 *
67 * <p>The {@link Notification.Builder Notification.Builder} has been added to make it
68 * easier to construct Notifications.</p>
69 *
70 * <div class="special reference">
71 * <h3>Developer Guides</h3>
72 * <p>For a guide to creating notifications, read the
73 * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a>
74 * developer guide.</p>
75 * </div>
76 */
77public class Notification implements Parcelable
78{
79    private static final String TAG = "Notification";
80
81    /**
82     * An activity that provides a user interface for adjusting notification preferences for its
83     * containing application. Optional but recommended for apps that post
84     * {@link android.app.Notification Notifications}.
85     */
86    @SdkConstant(SdkConstantType.INTENT_CATEGORY)
87    public static final String INTENT_CATEGORY_NOTIFICATION_PREFERENCES
88            = "android.intent.category.NOTIFICATION_PREFERENCES";
89
90    /**
91     * Use all default values (where applicable).
92     */
93    public static final int DEFAULT_ALL = ~0;
94
95    /**
96     * Use the default notification sound. This will ignore any given
97     * {@link #sound}.
98     *
99     * <p>
100     * A notification that is noisy is more likely to be presented as a heads-up notification.
101     * </p>
102     *
103     * @see #defaults
104     */
105
106    public static final int DEFAULT_SOUND = 1;
107
108    /**
109     * Use the default notification vibrate. This will ignore any given
110     * {@link #vibrate}. Using phone vibration requires the
111     * {@link android.Manifest.permission#VIBRATE VIBRATE} permission.
112     *
113     * <p>
114     * A notification that vibrates is more likely to be presented as a heads-up notification.
115     * </p>
116     *
117     * @see #defaults
118     */
119
120    public static final int DEFAULT_VIBRATE = 2;
121
122    /**
123     * Use the default notification lights. This will ignore the
124     * {@link #FLAG_SHOW_LIGHTS} bit, and {@link #ledARGB}, {@link #ledOffMS}, or
125     * {@link #ledOnMS}.
126     *
127     * @see #defaults
128     */
129
130    public static final int DEFAULT_LIGHTS = 4;
131
132    /**
133     * A timestamp related to this notification, in milliseconds since the epoch.
134     *
135     * Default value: {@link System#currentTimeMillis() Now}.
136     *
137     * Choose a timestamp that will be most relevant to the user. For most finite events, this
138     * corresponds to the time the event happened (or will happen, in the case of events that have
139     * yet to occur but about which the user is being informed). Indefinite events should be
140     * timestamped according to when the activity began.
141     *
142     * Some examples:
143     *
144     * <ul>
145     *   <li>Notification of a new chat message should be stamped when the message was received.</li>
146     *   <li>Notification of an ongoing file download (with a progress bar, for example) should be stamped when the download started.</li>
147     *   <li>Notification of a completed file download should be stamped when the download finished.</li>
148     *   <li>Notification of an upcoming meeting should be stamped with the time the meeting will begin (that is, in the future).</li>
149     *   <li>Notification of an ongoing stopwatch (increasing timer) should be stamped with the watch's start time.
150     *   <li>Notification of an ongoing countdown timer should be stamped with the timer's end time.
151     * </ul>
152     *
153     */
154    public long when;
155
156    /**
157     * The resource id of a drawable to use as the icon in the status bar.
158     * This is required; notifications with an invalid icon resource will not be shown.
159     */
160    public int icon;
161
162    /**
163     * If the icon in the status bar is to have more than one level, you can set this.  Otherwise,
164     * leave it at its default value of 0.
165     *
166     * @see android.widget.ImageView#setImageLevel
167     * @see android.graphics.drawable.Drawable#setLevel
168     */
169    public int iconLevel;
170
171    /**
172     * The number of events that this notification represents. For example, in a new mail
173     * notification, this could be the number of unread messages.
174     *
175     * The system may or may not use this field to modify the appearance of the notification. For
176     * example, before {@link android.os.Build.VERSION_CODES#HONEYCOMB}, this number was
177     * superimposed over the icon in the status bar. Starting with
178     * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, the template used by
179     * {@link Notification.Builder} has displayed the number in the expanded notification view.
180     *
181     * If the number is 0 or negative, it is never shown.
182     */
183    public int number;
184
185    /**
186     * The intent to execute when the expanded status entry is clicked.  If
187     * this is an activity, it must include the
188     * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires
189     * that you take care of task management as described in the
190     * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back
191     * Stack</a> document.  In particular, make sure to read the notification section
192     * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html#HandlingNotifications">Handling
193     * Notifications</a> for the correct ways to launch an application from a
194     * notification.
195     */
196    public PendingIntent contentIntent;
197
198    /**
199     * The intent to execute when the notification is explicitly dismissed by the user, either with
200     * the "Clear All" button or by swiping it away individually.
201     *
202     * This probably shouldn't be launching an activity since several of those will be sent
203     * at the same time.
204     */
205    public PendingIntent deleteIntent;
206
207    /**
208     * An intent to launch instead of posting the notification to the status bar.
209     *
210     * <p>
211     * The system UI may choose to display a heads-up notification, instead of
212     * launching this intent, while the user is using the device.
213     * </p>
214     *
215     * @see Notification.Builder#setFullScreenIntent
216     */
217    public PendingIntent fullScreenIntent;
218
219    /**
220     * Text that summarizes this notification for accessibility services.
221     *
222     * As of the L release, this text is no longer shown on screen, but it is still useful to
223     * accessibility services (where it serves as an audible announcement of the notification's
224     * appearance).
225     *
226     * @see #tickerView
227     */
228    public CharSequence tickerText;
229
230    /**
231     * Formerly, a view showing the {@link #tickerText}.
232     *
233     * No longer displayed in the status bar as of API 21.
234     */
235    @Deprecated
236    public RemoteViews tickerView;
237
238    /**
239     * The view that will represent this notification in the expanded status bar.
240     */
241    public RemoteViews contentView;
242
243    /**
244     * A large-format version of {@link #contentView}, giving the Notification an
245     * opportunity to show more detail. The system UI may choose to show this
246     * instead of the normal content view at its discretion.
247     */
248    public RemoteViews bigContentView;
249
250
251    /**
252     * A medium-format version of {@link #contentView}, providing the Notification an
253     * opportunity to add action buttons to contentView. At its discretion, the system UI may
254     * choose to show this as a heads-up notification, which will pop up so the user can see
255     * it without leaving their current activity.
256     */
257    public RemoteViews headsUpContentView;
258
259    /**
260     * The bitmap that may escape the bounds of the panel and bar.
261     */
262    public Bitmap largeIcon;
263
264    /**
265     * The sound to play.
266     *
267     * <p>
268     * A notification that is noisy is more likely to be presented as a heads-up notification.
269     * </p>
270     *
271     * <p>
272     * To play the default notification sound, see {@link #defaults}.
273     * </p>
274     */
275    public Uri sound;
276
277    /**
278     * Use this constant as the value for audioStreamType to request that
279     * the default stream type for notifications be used.  Currently the
280     * default stream type is {@link AudioManager#STREAM_NOTIFICATION}.
281     *
282     * @deprecated Use {@link #audioAttributes} instead.
283     */
284    @Deprecated
285    public static final int STREAM_DEFAULT = -1;
286
287    /**
288     * The audio stream type to use when playing the sound.
289     * Should be one of the STREAM_ constants from
290     * {@link android.media.AudioManager}.
291     *
292     * @deprecated Use {@link #audioAttributes} instead.
293     */
294    @Deprecated
295    public int audioStreamType = STREAM_DEFAULT;
296
297    /**
298     * The default value of {@link #audioAttributes}.
299     */
300    public static final AudioAttributes AUDIO_ATTRIBUTES_DEFAULT = new AudioAttributes.Builder()
301            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
302            .setUsage(AudioAttributes.USAGE_NOTIFICATION)
303            .build();
304
305    /**
306     * The {@link AudioAttributes audio attributes} to use when playing the sound.
307     */
308    public AudioAttributes audioAttributes = AUDIO_ATTRIBUTES_DEFAULT;
309
310    /**
311     * The pattern with which to vibrate.
312     *
313     * <p>
314     * To vibrate the default pattern, see {@link #defaults}.
315     * </p>
316     *
317     * <p>
318     * A notification that vibrates is more likely to be presented as a heads-up notification.
319     * </p>
320     *
321     * @see android.os.Vibrator#vibrate(long[],int)
322     */
323    public long[] vibrate;
324
325    /**
326     * The color of the led.  The hardware will do its best approximation.
327     *
328     * @see #FLAG_SHOW_LIGHTS
329     * @see #flags
330     */
331    public int ledARGB;
332
333    /**
334     * The number of milliseconds for the LED to be on while it's flashing.
335     * The hardware will do its best approximation.
336     *
337     * @see #FLAG_SHOW_LIGHTS
338     * @see #flags
339     */
340    public int ledOnMS;
341
342    /**
343     * The number of milliseconds for the LED to be off while it's flashing.
344     * The hardware will do its best approximation.
345     *
346     * @see #FLAG_SHOW_LIGHTS
347     * @see #flags
348     */
349    public int ledOffMS;
350
351    /**
352     * Specifies which values should be taken from the defaults.
353     * <p>
354     * To set, OR the desired from {@link #DEFAULT_SOUND},
355     * {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}. For all default
356     * values, use {@link #DEFAULT_ALL}.
357     * </p>
358     */
359    public int defaults;
360
361    /**
362     * Bit to be bitwise-ored into the {@link #flags} field that should be
363     * set if you want the LED on for this notification.
364     * <ul>
365     * <li>To turn the LED off, pass 0 in the alpha channel for colorARGB
366     *      or 0 for both ledOnMS and ledOffMS.</li>
367     * <li>To turn the LED on, pass 1 for ledOnMS and 0 for ledOffMS.</li>
368     * <li>To flash the LED, pass the number of milliseconds that it should
369     *      be on and off to ledOnMS and ledOffMS.</li>
370     * </ul>
371     * <p>
372     * Since hardware varies, you are not guaranteed that any of the values
373     * you pass are honored exactly.  Use the system defaults (TODO) if possible
374     * because they will be set to values that work on any given hardware.
375     * <p>
376     * The alpha channel must be set for forward compatibility.
377     *
378     */
379    public static final int FLAG_SHOW_LIGHTS        = 0x00000001;
380
381    /**
382     * Bit to be bitwise-ored into the {@link #flags} field that should be
383     * set if this notification is in reference to something that is ongoing,
384     * like a phone call.  It should not be set if this notification is in
385     * reference to something that happened at a particular point in time,
386     * like a missed phone call.
387     */
388    public static final int FLAG_ONGOING_EVENT      = 0x00000002;
389
390    /**
391     * Bit to be bitwise-ored into the {@link #flags} field that if set,
392     * the audio will be repeated until the notification is
393     * cancelled or the notification window is opened.
394     */
395    public static final int FLAG_INSISTENT          = 0x00000004;
396
397    /**
398     * Bit to be bitwise-ored into the {@link #flags} field that should be
399     * set if you would only like the sound, vibrate and ticker to be played
400     * if the notification was not already showing.
401     */
402    public static final int FLAG_ONLY_ALERT_ONCE    = 0x00000008;
403
404    /**
405     * Bit to be bitwise-ored into the {@link #flags} field that should be
406     * set if the notification should be canceled when it is clicked by the
407     * user.
408
409     */
410    public static final int FLAG_AUTO_CANCEL        = 0x00000010;
411
412    /**
413     * Bit to be bitwise-ored into the {@link #flags} field that should be
414     * set if the notification should not be canceled when the user clicks
415     * the Clear all button.
416     */
417    public static final int FLAG_NO_CLEAR           = 0x00000020;
418
419    /**
420     * Bit to be bitwise-ored into the {@link #flags} field that should be
421     * set if this notification represents a currently running service.  This
422     * will normally be set for you by {@link Service#startForeground}.
423     */
424    public static final int FLAG_FOREGROUND_SERVICE = 0x00000040;
425
426    /**
427     * Obsolete flag indicating high-priority notifications; use the priority field instead.
428     *
429     * @deprecated Use {@link #priority} with a positive value.
430     */
431    public static final int FLAG_HIGH_PRIORITY      = 0x00000080;
432
433    /**
434     * Bit to be bitswise-ored into the {@link #flags} field that should be
435     * set if this notification is relevant to the current device only
436     * and it is not recommended that it bridge to other devices.
437     */
438    public static final int FLAG_LOCAL_ONLY         = 0x00000100;
439
440    /**
441     * Bit to be bitswise-ored into the {@link #flags} field that should be
442     * set if this notification is the group summary for a group of notifications.
443     * Grouped notifications may display in a cluster or stack on devices which
444     * support such rendering. Requires a group key also be set using {@link Builder#setGroup}.
445     */
446    public static final int FLAG_GROUP_SUMMARY      = 0x00000200;
447
448    public int flags;
449
450    /** @hide */
451    @IntDef({PRIORITY_DEFAULT,PRIORITY_LOW,PRIORITY_MIN,PRIORITY_HIGH,PRIORITY_MAX})
452    @Retention(RetentionPolicy.SOURCE)
453    public @interface Priority {}
454
455    /**
456     * Default notification {@link #priority}. If your application does not prioritize its own
457     * notifications, use this value for all notifications.
458     */
459    public static final int PRIORITY_DEFAULT = 0;
460
461    /**
462     * Lower {@link #priority}, for items that are less important. The UI may choose to show these
463     * items smaller, or at a different position in the list, compared with your app's
464     * {@link #PRIORITY_DEFAULT} items.
465     */
466    public static final int PRIORITY_LOW = -1;
467
468    /**
469     * Lowest {@link #priority}; these items might not be shown to the user except under special
470     * circumstances, such as detailed notification logs.
471     */
472    public static final int PRIORITY_MIN = -2;
473
474    /**
475     * Higher {@link #priority}, for more important notifications or alerts. The UI may choose to
476     * show these items larger, or at a different position in notification lists, compared with
477     * your app's {@link #PRIORITY_DEFAULT} items.
478     */
479    public static final int PRIORITY_HIGH = 1;
480
481    /**
482     * Highest {@link #priority}, for your application's most important items that require the
483     * user's prompt attention or input.
484     */
485    public static final int PRIORITY_MAX = 2;
486
487    /**
488     * Relative priority for this notification.
489     *
490     * Priority is an indication of how much of the user's valuable attention should be consumed by
491     * this notification. Low-priority notifications may be hidden from the user in certain
492     * situations, while the user might be interrupted for a higher-priority notification. The
493     * system will make a determination about how to interpret this priority when presenting
494     * the notification.
495     *
496     * <p>
497     * A notification that is at least {@link #PRIORITY_HIGH} is more likely to be presented
498     * as a heads-up notification.
499     * </p>
500     *
501     */
502    @Priority
503    public int priority;
504
505    /**
506     * Accent color (an ARGB integer like the constants in {@link android.graphics.Color})
507     * to be applied by the standard Style templates when presenting this notification.
508     *
509     * The current template design constructs a colorful header image by overlaying the
510     * {@link #icon} image (stenciled in white) atop a field of this color. Alpha components are
511     * ignored.
512     */
513    public int color = COLOR_DEFAULT;
514
515    /**
516     * Special value of {@link #color} telling the system not to decorate this notification with
517     * any special color but instead use default colors when presenting this notification.
518     */
519    public static final int COLOR_DEFAULT = 0; // AKA Color.TRANSPARENT
520
521    /**
522     * Sphere of visibility of this notification, which affects how and when the SystemUI reveals
523     * the notification's presence and contents in untrusted situations (namely, on the secure
524     * lockscreen).
525     *
526     * The default level, {@link #VISIBILITY_PRIVATE}, behaves exactly as notifications have always
527     * done on Android: The notification's {@link #icon} and {@link #tickerText} (if available) are
528     * shown in all situations, but the contents are only available if the device is unlocked for
529     * the appropriate user.
530     *
531     * A more permissive policy can be expressed by {@link #VISIBILITY_PUBLIC}; such a notification
532     * can be read even in an "insecure" context (that is, above a secure lockscreen).
533     * To modify the public version of this notification—for example, to redact some portions—see
534     * {@link Builder#setPublicVersion(Notification)}.
535     *
536     * Finally, a notification can be made {@link #VISIBILITY_SECRET}, which will suppress its icon
537     * and ticker until the user has bypassed the lockscreen.
538     */
539    public int visibility;
540
541    public static final int VISIBILITY_PUBLIC = 1;
542    public static final int VISIBILITY_PRIVATE = 0;
543    public static final int VISIBILITY_SECRET = -1;
544
545    /**
546     * Notification category: incoming call (voice or video) or similar synchronous communication request.
547     */
548    public static final String CATEGORY_CALL = "call";
549
550    /**
551     * Notification category: incoming direct message (SMS, instant message, etc.).
552     */
553    public static final String CATEGORY_MESSAGE = "msg";
554
555    /**
556     * Notification category: asynchronous bulk message (email).
557     */
558    public static final String CATEGORY_EMAIL = "email";
559
560    /**
561     * Notification category: calendar event.
562     */
563    public static final String CATEGORY_EVENT = "event";
564
565    /**
566     * Notification category: promotion or advertisement.
567     */
568    public static final String CATEGORY_PROMO = "promo";
569
570    /**
571     * Notification category: alarm or timer.
572     */
573    public static final String CATEGORY_ALARM = "alarm";
574
575    /**
576     * Notification category: progress of a long-running background operation.
577     */
578    public static final String CATEGORY_PROGRESS = "progress";
579
580    /**
581     * Notification category: social network or sharing update.
582     */
583    public static final String CATEGORY_SOCIAL = "social";
584
585    /**
586     * Notification category: error in background operation or authentication status.
587     */
588    public static final String CATEGORY_ERROR = "err";
589
590    /**
591     * Notification category: media transport control for playback.
592     */
593    public static final String CATEGORY_TRANSPORT = "transport";
594
595    /**
596     * Notification category: system or device status update.  Reserved for system use.
597     */
598    public static final String CATEGORY_SYSTEM = "sys";
599
600    /**
601     * Notification category: indication of running background service.
602     */
603    public static final String CATEGORY_SERVICE = "service";
604
605    /**
606     * Notification category: a specific, timely recommendation for a single thing.
607     * For example, a news app might want to recommend a news story it believes the user will
608     * want to read next.
609     */
610    public static final String CATEGORY_RECOMMENDATION = "recommendation";
611
612    /**
613     * Notification category: ongoing information about device or contextual status.
614     */
615    public static final String CATEGORY_STATUS = "status";
616
617    /**
618     * One of the predefined notification categories (see the <code>CATEGORY_*</code> constants)
619     * that best describes this Notification.  May be used by the system for ranking and filtering.
620     */
621    public String category;
622
623    private String mGroupKey;
624
625    /**
626     * Get the key used to group this notification into a cluster or stack
627     * with other notifications on devices which support such rendering.
628     */
629    public String getGroup() {
630        return mGroupKey;
631    }
632
633    private String mSortKey;
634
635    /**
636     * Get a sort key that orders this notification among other notifications from the
637     * same package. This can be useful if an external sort was already applied and an app
638     * would like to preserve this. Notifications will be sorted lexicographically using this
639     * value, although providing different priorities in addition to providing sort key may
640     * cause this value to be ignored.
641     *
642     * <p>This sort key can also be used to order members of a notification group. See
643     * {@link Builder#setGroup}.
644     *
645     * @see String#compareTo(String)
646     */
647    public String getSortKey() {
648        return mSortKey;
649    }
650
651    /**
652     * Additional semantic data to be carried around with this Notification.
653     * <p>
654     * The extras keys defined here are intended to capture the original inputs to {@link Builder}
655     * APIs, and are intended to be used by
656     * {@link android.service.notification.NotificationListenerService} implementations to extract
657     * detailed information from notification objects.
658     */
659    public Bundle extras = new Bundle();
660
661    /**
662     * {@link #extras} key: this is the title of the notification,
663     * as supplied to {@link Builder#setContentTitle(CharSequence)}.
664     */
665    public static final String EXTRA_TITLE = "android.title";
666
667    /**
668     * {@link #extras} key: this is the title of the notification when shown in expanded form,
669     * e.g. as supplied to {@link BigTextStyle#setBigContentTitle(CharSequence)}.
670     */
671    public static final String EXTRA_TITLE_BIG = EXTRA_TITLE + ".big";
672
673    /**
674     * {@link #extras} key: this is the main text payload, as supplied to
675     * {@link Builder#setContentText(CharSequence)}.
676     */
677    public static final String EXTRA_TEXT = "android.text";
678
679    /**
680     * {@link #extras} key: this is a third line of text, as supplied to
681     * {@link Builder#setSubText(CharSequence)}.
682     */
683    public static final String EXTRA_SUB_TEXT = "android.subText";
684
685    /**
686     * {@link #extras} key: this is a small piece of additional text as supplied to
687     * {@link Builder#setContentInfo(CharSequence)}.
688     */
689    public static final String EXTRA_INFO_TEXT = "android.infoText";
690
691    /**
692     * {@link #extras} key: this is a line of summary information intended to be shown
693     * alongside expanded notifications, as supplied to (e.g.)
694     * {@link BigTextStyle#setSummaryText(CharSequence)}.
695     */
696    public static final String EXTRA_SUMMARY_TEXT = "android.summaryText";
697
698    /**
699     * {@link #extras} key: this is the longer text shown in the big form of a
700     * {@link BigTextStyle} notification, as supplied to
701     * {@link BigTextStyle#bigText(CharSequence)}.
702     */
703    public static final String EXTRA_BIG_TEXT = "android.bigText";
704
705    /**
706     * {@link #extras} key: this is the resource ID of the notification's main small icon, as
707     * supplied to {@link Builder#setSmallIcon(int)}.
708     */
709    public static final String EXTRA_SMALL_ICON = "android.icon";
710
711    /**
712     * {@link #extras} key: this is a bitmap to be used instead of the small icon when showing the
713     * notification payload, as
714     * supplied to {@link Builder#setLargeIcon(android.graphics.Bitmap)}.
715     */
716    public static final String EXTRA_LARGE_ICON = "android.largeIcon";
717
718    /**
719     * {@link #extras} key: this is a bitmap to be used instead of the one from
720     * {@link Builder#setLargeIcon(android.graphics.Bitmap)} when the notification is
721     * shown in its expanded form, as supplied to
722     * {@link BigPictureStyle#bigLargeIcon(android.graphics.Bitmap)}.
723     */
724    public static final String EXTRA_LARGE_ICON_BIG = EXTRA_LARGE_ICON + ".big";
725
726    /**
727     * {@link #extras} key: this is the progress value supplied to
728     * {@link Builder#setProgress(int, int, boolean)}.
729     */
730    public static final String EXTRA_PROGRESS = "android.progress";
731
732    /**
733     * {@link #extras} key: this is the maximum value supplied to
734     * {@link Builder#setProgress(int, int, boolean)}.
735     */
736    public static final String EXTRA_PROGRESS_MAX = "android.progressMax";
737
738    /**
739     * {@link #extras} key: whether the progress bar is indeterminate, supplied to
740     * {@link Builder#setProgress(int, int, boolean)}.
741     */
742    public static final String EXTRA_PROGRESS_INDETERMINATE = "android.progressIndeterminate";
743
744    /**
745     * {@link #extras} key: whether {@link #when} should be shown as a count-up timer (specifically
746     * a {@link android.widget.Chronometer}) instead of a timestamp, as supplied to
747     * {@link Builder#setUsesChronometer(boolean)}.
748     */
749    public static final String EXTRA_SHOW_CHRONOMETER = "android.showChronometer";
750
751    /**
752     * {@link #extras} key: whether {@link #when} should be shown,
753     * as supplied to {@link Builder#setShowWhen(boolean)}.
754     */
755    public static final String EXTRA_SHOW_WHEN = "android.showWhen";
756
757    /**
758     * {@link #extras} key: this is a bitmap to be shown in {@link BigPictureStyle} expanded
759     * notifications, supplied to {@link BigPictureStyle#bigPicture(android.graphics.Bitmap)}.
760     */
761    public static final String EXTRA_PICTURE = "android.picture";
762
763    /**
764     * {@link #extras} key: An array of CharSequences to show in {@link InboxStyle} expanded
765     * notifications, each of which was supplied to {@link InboxStyle#addLine(CharSequence)}.
766     */
767    public static final String EXTRA_TEXT_LINES = "android.textLines";
768
769    /**
770     * {@link #extras} key: A string representing the name of the specific
771     * {@link android.app.Notification.Style} used to create this notification.
772     */
773    public static final String EXTRA_TEMPLATE = "android.template";
774
775    /**
776     * {@link #extras} key: An array of people that this notification relates to, specified
777     * by contacts provider contact URI.
778     */
779    public static final String EXTRA_PEOPLE = "android.people";
780
781    /**
782     * {@link #extras} key: used to provide hints about the appropriateness of
783     * displaying this notification as a heads-up notification.
784     * @hide
785     */
786    public static final String EXTRA_AS_HEADS_UP = "headsup";
787
788    /**
789     * Allow certain system-generated notifications to appear before the device is provisioned.
790     * Only available to notifications coming from the android package.
791     * @hide
792     */
793    public static final String EXTRA_ALLOW_DURING_SETUP = "android.allowDuringSetup";
794
795    /**
796     * {@link #extras} key: A
797     * {@link android.content.ContentUris content URI} pointing to an image that can be displayed
798     * in the background when the notification is selected. The URI must point to an image stream
799     * suitable for passing into
800     * {@link android.graphics.BitmapFactory#decodeStream(java.io.InputStream)
801     * BitmapFactory.decodeStream}; all other content types will be ignored. The content provider
802     * URI used for this purpose must require no permissions to read the image data.
803     */
804    public static final String EXTRA_BACKGROUND_IMAGE_URI = "android.backgroundImageUri";
805
806    /**
807     * {@link #extras} key: A
808     * {@link android.media.session.MediaSession.Token} associated with a
809     * {@link android.app.Notification.MediaStyle} notification.
810     */
811    public static final String EXTRA_MEDIA_SESSION = "android.mediaSession";
812
813    /**
814     * {@link #extras} key: the indices of actions to be shown in the compact view,
815     * as supplied to (e.g.) {@link MediaStyle#setShowActionsInCompactView(int...)}.
816     */
817    public static final String EXTRA_COMPACT_ACTIONS = "android.compactActions";
818
819    /**
820     * {@link #extras} key: the user that built the notification.
821     *
822     * @hide
823     */
824    public static final String EXTRA_ORIGINATING_USERID = "android.originatingUserId";
825
826    /**
827     * Value for {@link #EXTRA_AS_HEADS_UP} that indicates this notification should not be
828     * displayed in the heads up space.
829     *
830     * <p>
831     * If this notification has a {@link #fullScreenIntent}, then it will always launch the
832     * full-screen intent when posted.
833     * </p>
834     * @hide
835     */
836    public static final int HEADS_UP_NEVER = 0;
837
838    /**
839     * Default value for {@link #EXTRA_AS_HEADS_UP} that indicates this notification may be
840     * displayed as a heads up.
841     * @hide
842     */
843    public static final int HEADS_UP_ALLOWED = 1;
844
845    /**
846     * Value for {@link #EXTRA_AS_HEADS_UP} that indicates this notification is a
847     * good candidate for display as a heads up.
848     * @hide
849     */
850    public static final int HEADS_UP_REQUESTED = 2;
851
852    /**
853     * Structure to encapsulate a named action that can be shown as part of this notification.
854     * It must include an icon, a label, and a {@link PendingIntent} to be fired when the action is
855     * selected by the user.
856     * <p>
857     * Apps should use {@link Notification.Builder#addAction(int, CharSequence, PendingIntent)}
858     * or {@link Notification.Builder#addAction(Notification.Action)}
859     * to attach actions.
860     */
861    public static class Action implements Parcelable {
862        private final Bundle mExtras;
863        private final RemoteInput[] mRemoteInputs;
864
865        /**
866         * Small icon representing the action.
867         */
868        public int icon;
869
870        /**
871         * Title of the action.
872         */
873        public CharSequence title;
874
875        /**
876         * Intent to send when the user invokes this action. May be null, in which case the action
877         * may be rendered in a disabled presentation by the system UI.
878         */
879        public PendingIntent actionIntent;
880
881        private Action(Parcel in) {
882            icon = in.readInt();
883            title = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
884            if (in.readInt() == 1) {
885                actionIntent = PendingIntent.CREATOR.createFromParcel(in);
886            }
887            mExtras = in.readBundle();
888            mRemoteInputs = in.createTypedArray(RemoteInput.CREATOR);
889        }
890
891        /**
892         * Use {@link Notification.Builder#addAction(int, CharSequence, PendingIntent)}.
893         */
894        public Action(int icon, CharSequence title, PendingIntent intent) {
895            this(icon, title, intent, new Bundle(), null);
896        }
897
898        private Action(int icon, CharSequence title, PendingIntent intent, Bundle extras,
899                RemoteInput[] remoteInputs) {
900            this.icon = icon;
901            this.title = title;
902            this.actionIntent = intent;
903            this.mExtras = extras != null ? extras : new Bundle();
904            this.mRemoteInputs = remoteInputs;
905        }
906
907        /**
908         * Get additional metadata carried around with this Action.
909         */
910        public Bundle getExtras() {
911            return mExtras;
912        }
913
914        /**
915         * Get the list of inputs to be collected from the user when this action is sent.
916         * May return null if no remote inputs were added.
917         */
918        public RemoteInput[] getRemoteInputs() {
919            return mRemoteInputs;
920        }
921
922        /**
923         * Builder class for {@link Action} objects.
924         */
925        public static final class Builder {
926            private final int mIcon;
927            private final CharSequence mTitle;
928            private final PendingIntent mIntent;
929            private final Bundle mExtras;
930            private ArrayList<RemoteInput> mRemoteInputs;
931
932            /**
933             * Construct a new builder for {@link Action} object.
934             * @param icon icon to show for this action
935             * @param title the title of the action
936             * @param intent the {@link PendingIntent} to fire when users trigger this action
937             */
938            public Builder(int icon, CharSequence title, PendingIntent intent) {
939                this(icon, title, intent, new Bundle(), null);
940            }
941
942            /**
943             * Construct a new builder for {@link Action} object using the fields from an
944             * {@link Action}.
945             * @param action the action to read fields from.
946             */
947            public Builder(Action action) {
948                this(action.icon, action.title, action.actionIntent, new Bundle(action.mExtras),
949                        action.getRemoteInputs());
950            }
951
952            private Builder(int icon, CharSequence title, PendingIntent intent, Bundle extras,
953                    RemoteInput[] remoteInputs) {
954                mIcon = icon;
955                mTitle = title;
956                mIntent = intent;
957                mExtras = extras;
958                if (remoteInputs != null) {
959                    mRemoteInputs = new ArrayList<RemoteInput>(remoteInputs.length);
960                    Collections.addAll(mRemoteInputs, remoteInputs);
961                }
962            }
963
964            /**
965             * Merge additional metadata into this builder.
966             *
967             * <p>Values within the Bundle will replace existing extras values in this Builder.
968             *
969             * @see Notification.Action#extras
970             */
971            public Builder addExtras(Bundle extras) {
972                if (extras != null) {
973                    mExtras.putAll(extras);
974                }
975                return this;
976            }
977
978            /**
979             * Get the metadata Bundle used by this Builder.
980             *
981             * <p>The returned Bundle is shared with this Builder.
982             */
983            public Bundle getExtras() {
984                return mExtras;
985            }
986
987            /**
988             * Add an input to be collected from the user when this action is sent.
989             * Response values can be retrieved from the fired intent by using the
990             * {@link RemoteInput#getResultsFromIntent} function.
991             * @param remoteInput a {@link RemoteInput} to add to the action
992             * @return this object for method chaining
993             */
994            public Builder addRemoteInput(RemoteInput remoteInput) {
995                if (mRemoteInputs == null) {
996                    mRemoteInputs = new ArrayList<RemoteInput>();
997                }
998                mRemoteInputs.add(remoteInput);
999                return this;
1000            }
1001
1002            /**
1003             * Apply an extender to this action builder. Extenders may be used to add
1004             * metadata or change options on this builder.
1005             */
1006            public Builder extend(Extender extender) {
1007                extender.extend(this);
1008                return this;
1009            }
1010
1011            /**
1012             * Combine all of the options that have been set and return a new {@link Action}
1013             * object.
1014             * @return the built action
1015             */
1016            public Action build() {
1017                RemoteInput[] remoteInputs = mRemoteInputs != null
1018                        ? mRemoteInputs.toArray(new RemoteInput[mRemoteInputs.size()]) : null;
1019                return new Action(mIcon, mTitle, mIntent, mExtras, remoteInputs);
1020            }
1021        }
1022
1023        @Override
1024        public Action clone() {
1025            return new Action(
1026                    icon,
1027                    title,
1028                    actionIntent, // safe to alias
1029                    new Bundle(mExtras),
1030                    getRemoteInputs());
1031        }
1032        @Override
1033        public int describeContents() {
1034            return 0;
1035        }
1036        @Override
1037        public void writeToParcel(Parcel out, int flags) {
1038            out.writeInt(icon);
1039            TextUtils.writeToParcel(title, out, flags);
1040            if (actionIntent != null) {
1041                out.writeInt(1);
1042                actionIntent.writeToParcel(out, flags);
1043            } else {
1044                out.writeInt(0);
1045            }
1046            out.writeBundle(mExtras);
1047            out.writeTypedArray(mRemoteInputs, flags);
1048        }
1049        public static final Parcelable.Creator<Action> CREATOR =
1050                new Parcelable.Creator<Action>() {
1051            public Action createFromParcel(Parcel in) {
1052                return new Action(in);
1053            }
1054            public Action[] newArray(int size) {
1055                return new Action[size];
1056            }
1057        };
1058
1059        /**
1060         * Extender interface for use with {@link Builder#extend}. Extenders may be used to add
1061         * metadata or change options on an action builder.
1062         */
1063        public interface Extender {
1064            /**
1065             * Apply this extender to a notification action builder.
1066             * @param builder the builder to be modified.
1067             * @return the build object for chaining.
1068             */
1069            public Builder extend(Builder builder);
1070        }
1071
1072        /**
1073         * Wearable extender for notification actions. To add extensions to an action,
1074         * create a new {@link android.app.Notification.Action.WearableExtender} object using
1075         * the {@code WearableExtender()} constructor and apply it to a
1076         * {@link android.app.Notification.Action.Builder} using
1077         * {@link android.app.Notification.Action.Builder#extend}.
1078         *
1079         * <pre class="prettyprint">
1080         * Notification.Action action = new Notification.Action.Builder(
1081         *         R.drawable.archive_all, "Archive all", actionIntent)
1082         *         .extend(new Notification.Action.WearableExtender()
1083         *                 .setAvailableOffline(false))
1084         *         .build();</pre>
1085         */
1086        public static final class WearableExtender implements Extender {
1087            /** Notification action extra which contains wearable extensions */
1088            private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS";
1089
1090            private static final String KEY_FLAGS = "flags";
1091
1092            // Flags bitwise-ored to mFlags
1093            private static final int FLAG_AVAILABLE_OFFLINE = 0x1;
1094
1095            // Default value for flags integer
1096            private static final int DEFAULT_FLAGS = FLAG_AVAILABLE_OFFLINE;
1097
1098            private int mFlags = DEFAULT_FLAGS;
1099
1100            /**
1101             * Create a {@link android.app.Notification.Action.WearableExtender} with default
1102             * options.
1103             */
1104            public WearableExtender() {
1105            }
1106
1107            /**
1108             * Create a {@link android.app.Notification.Action.WearableExtender} by reading
1109             * wearable options present in an existing notification action.
1110             * @param action the notification action to inspect.
1111             */
1112            public WearableExtender(Action action) {
1113                Bundle wearableBundle = action.getExtras().getBundle(EXTRA_WEARABLE_EXTENSIONS);
1114                if (wearableBundle != null) {
1115                    mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS);
1116                }
1117            }
1118
1119            /**
1120             * Apply wearable extensions to a notification action that is being built. This is
1121             * typically called by the {@link android.app.Notification.Action.Builder#extend}
1122             * method of {@link android.app.Notification.Action.Builder}.
1123             */
1124            @Override
1125            public Action.Builder extend(Action.Builder builder) {
1126                Bundle wearableBundle = new Bundle();
1127
1128                if (mFlags != DEFAULT_FLAGS) {
1129                    wearableBundle.putInt(KEY_FLAGS, mFlags);
1130                }
1131
1132                builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle);
1133                return builder;
1134            }
1135
1136            @Override
1137            public WearableExtender clone() {
1138                WearableExtender that = new WearableExtender();
1139                that.mFlags = this.mFlags;
1140                return that;
1141            }
1142
1143            /**
1144             * Set whether this action is available when the wearable device is not connected to
1145             * a companion device. The user can still trigger this action when the wearable device is
1146             * offline, but a visual hint will indicate that the action may not be available.
1147             * Defaults to true.
1148             */
1149            public WearableExtender setAvailableOffline(boolean availableOffline) {
1150                setFlag(FLAG_AVAILABLE_OFFLINE, availableOffline);
1151                return this;
1152            }
1153
1154            /**
1155             * Get whether this action is available when the wearable device is not connected to
1156             * a companion device. The user can still trigger this action when the wearable device is
1157             * offline, but a visual hint will indicate that the action may not be available.
1158             * Defaults to true.
1159             */
1160            public boolean isAvailableOffline() {
1161                return (mFlags & FLAG_AVAILABLE_OFFLINE) != 0;
1162            }
1163
1164            private void setFlag(int mask, boolean value) {
1165                if (value) {
1166                    mFlags |= mask;
1167                } else {
1168                    mFlags &= ~mask;
1169                }
1170            }
1171        }
1172    }
1173
1174    /**
1175     * Array of all {@link Action} structures attached to this notification by
1176     * {@link Builder#addAction(int, CharSequence, PendingIntent)}. Mostly useful for instances of
1177     * {@link android.service.notification.NotificationListenerService} that provide an alternative
1178     * interface for invoking actions.
1179     */
1180    public Action[] actions;
1181
1182    /**
1183     * Replacement version of this notification whose content will be shown
1184     * in an insecure context such as atop a secure keyguard. See {@link #visibility}
1185     * and {@link #VISIBILITY_PUBLIC}.
1186     */
1187    public Notification publicVersion;
1188
1189    /**
1190     * Constructs a Notification object with default values.
1191     * You might want to consider using {@link Builder} instead.
1192     */
1193    public Notification()
1194    {
1195        this.when = System.currentTimeMillis();
1196        this.priority = PRIORITY_DEFAULT;
1197    }
1198
1199    /**
1200     * @hide
1201     */
1202    public Notification(Context context, int icon, CharSequence tickerText, long when,
1203            CharSequence contentTitle, CharSequence contentText, Intent contentIntent)
1204    {
1205        this.when = when;
1206        this.icon = icon;
1207        this.tickerText = tickerText;
1208        setLatestEventInfo(context, contentTitle, contentText,
1209                PendingIntent.getActivity(context, 0, contentIntent, 0));
1210    }
1211
1212    /**
1213     * Constructs a Notification object with the information needed to
1214     * have a status bar icon without the standard expanded view.
1215     *
1216     * @param icon          The resource id of the icon to put in the status bar.
1217     * @param tickerText    The text that flows by in the status bar when the notification first
1218     *                      activates.
1219     * @param when          The time to show in the time field.  In the System.currentTimeMillis
1220     *                      timebase.
1221     *
1222     * @deprecated Use {@link Builder} instead.
1223     */
1224    @Deprecated
1225    public Notification(int icon, CharSequence tickerText, long when)
1226    {
1227        this.icon = icon;
1228        this.tickerText = tickerText;
1229        this.when = when;
1230    }
1231
1232    /**
1233     * Unflatten the notification from a parcel.
1234     */
1235    public Notification(Parcel parcel)
1236    {
1237        int version = parcel.readInt();
1238
1239        when = parcel.readLong();
1240        icon = parcel.readInt();
1241        number = parcel.readInt();
1242        if (parcel.readInt() != 0) {
1243            contentIntent = PendingIntent.CREATOR.createFromParcel(parcel);
1244        }
1245        if (parcel.readInt() != 0) {
1246            deleteIntent = PendingIntent.CREATOR.createFromParcel(parcel);
1247        }
1248        if (parcel.readInt() != 0) {
1249            tickerText = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(parcel);
1250        }
1251        if (parcel.readInt() != 0) {
1252            tickerView = RemoteViews.CREATOR.createFromParcel(parcel);
1253        }
1254        if (parcel.readInt() != 0) {
1255            contentView = RemoteViews.CREATOR.createFromParcel(parcel);
1256        }
1257        if (parcel.readInt() != 0) {
1258            largeIcon = Bitmap.CREATOR.createFromParcel(parcel);
1259        }
1260        defaults = parcel.readInt();
1261        flags = parcel.readInt();
1262        if (parcel.readInt() != 0) {
1263            sound = Uri.CREATOR.createFromParcel(parcel);
1264        }
1265
1266        audioStreamType = parcel.readInt();
1267        if (parcel.readInt() != 0) {
1268            audioAttributes = AudioAttributes.CREATOR.createFromParcel(parcel);
1269        }
1270        vibrate = parcel.createLongArray();
1271        ledARGB = parcel.readInt();
1272        ledOnMS = parcel.readInt();
1273        ledOffMS = parcel.readInt();
1274        iconLevel = parcel.readInt();
1275
1276        if (parcel.readInt() != 0) {
1277            fullScreenIntent = PendingIntent.CREATOR.createFromParcel(parcel);
1278        }
1279
1280        priority = parcel.readInt();
1281
1282        category = parcel.readString();
1283
1284        mGroupKey = parcel.readString();
1285
1286        mSortKey = parcel.readString();
1287
1288        extras = parcel.readBundle(); // may be null
1289
1290        actions = parcel.createTypedArray(Action.CREATOR); // may be null
1291
1292        if (parcel.readInt() != 0) {
1293            bigContentView = RemoteViews.CREATOR.createFromParcel(parcel);
1294        }
1295
1296        if (parcel.readInt() != 0) {
1297            headsUpContentView = RemoteViews.CREATOR.createFromParcel(parcel);
1298        }
1299
1300        visibility = parcel.readInt();
1301
1302        if (parcel.readInt() != 0) {
1303            publicVersion = Notification.CREATOR.createFromParcel(parcel);
1304        }
1305
1306        color = parcel.readInt();
1307    }
1308
1309    @Override
1310    public Notification clone() {
1311        Notification that = new Notification();
1312        cloneInto(that, true);
1313        return that;
1314    }
1315
1316    /**
1317     * Copy all (or if heavy is false, all except Bitmaps and RemoteViews) members
1318     * of this into that.
1319     * @hide
1320     */
1321    public void cloneInto(Notification that, boolean heavy) {
1322        that.when = this.when;
1323        that.icon = this.icon;
1324        that.number = this.number;
1325
1326        // PendingIntents are global, so there's no reason (or way) to clone them.
1327        that.contentIntent = this.contentIntent;
1328        that.deleteIntent = this.deleteIntent;
1329        that.fullScreenIntent = this.fullScreenIntent;
1330
1331        if (this.tickerText != null) {
1332            that.tickerText = this.tickerText.toString();
1333        }
1334        if (heavy && this.tickerView != null) {
1335            that.tickerView = this.tickerView.clone();
1336        }
1337        if (heavy && this.contentView != null) {
1338            that.contentView = this.contentView.clone();
1339        }
1340        if (heavy && this.largeIcon != null) {
1341            that.largeIcon = Bitmap.createBitmap(this.largeIcon);
1342        }
1343        that.iconLevel = this.iconLevel;
1344        that.sound = this.sound; // android.net.Uri is immutable
1345        that.audioStreamType = this.audioStreamType;
1346        if (this.audioAttributes != null) {
1347            that.audioAttributes = new AudioAttributes.Builder(this.audioAttributes).build();
1348        }
1349
1350        final long[] vibrate = this.vibrate;
1351        if (vibrate != null) {
1352            final int N = vibrate.length;
1353            final long[] vib = that.vibrate = new long[N];
1354            System.arraycopy(vibrate, 0, vib, 0, N);
1355        }
1356
1357        that.ledARGB = this.ledARGB;
1358        that.ledOnMS = this.ledOnMS;
1359        that.ledOffMS = this.ledOffMS;
1360        that.defaults = this.defaults;
1361
1362        that.flags = this.flags;
1363
1364        that.priority = this.priority;
1365
1366        that.category = this.category;
1367
1368        that.mGroupKey = this.mGroupKey;
1369
1370        that.mSortKey = this.mSortKey;
1371
1372        if (this.extras != null) {
1373            try {
1374                that.extras = new Bundle(this.extras);
1375                // will unparcel
1376                that.extras.size();
1377            } catch (BadParcelableException e) {
1378                Log.e(TAG, "could not unparcel extras from notification: " + this, e);
1379                that.extras = null;
1380            }
1381        }
1382
1383        if (this.actions != null) {
1384            that.actions = new Action[this.actions.length];
1385            for(int i=0; i<this.actions.length; i++) {
1386                that.actions[i] = this.actions[i].clone();
1387            }
1388        }
1389
1390        if (heavy && this.bigContentView != null) {
1391            that.bigContentView = this.bigContentView.clone();
1392        }
1393
1394        if (heavy && this.headsUpContentView != null) {
1395            that.headsUpContentView = this.headsUpContentView.clone();
1396        }
1397
1398        that.visibility = this.visibility;
1399
1400        if (this.publicVersion != null) {
1401            that.publicVersion = new Notification();
1402            this.publicVersion.cloneInto(that.publicVersion, heavy);
1403        }
1404
1405        that.color = this.color;
1406
1407        if (!heavy) {
1408            that.lightenPayload(); // will clean out extras
1409        }
1410    }
1411
1412    /**
1413     * Removes heavyweight parts of the Notification object for archival or for sending to
1414     * listeners when the full contents are not necessary.
1415     * @hide
1416     */
1417    public final void lightenPayload() {
1418        tickerView = null;
1419        contentView = null;
1420        bigContentView = null;
1421        headsUpContentView = null;
1422        largeIcon = null;
1423        if (extras != null) {
1424            extras.remove(Notification.EXTRA_LARGE_ICON);
1425            extras.remove(Notification.EXTRA_LARGE_ICON_BIG);
1426            extras.remove(Notification.EXTRA_PICTURE);
1427        }
1428    }
1429
1430    /**
1431     * Make sure this CharSequence is safe to put into a bundle, which basically
1432     * means it had better not be some custom Parcelable implementation.
1433     * @hide
1434     */
1435    public static CharSequence safeCharSequence(CharSequence cs) {
1436        if (cs instanceof Parcelable) {
1437            Log.e(TAG, "warning: " + cs.getClass().getCanonicalName()
1438                    + " instance is a custom Parcelable and not allowed in Notification");
1439            return cs.toString();
1440        }
1441
1442        return cs;
1443    }
1444
1445    public int describeContents() {
1446        return 0;
1447    }
1448
1449    /**
1450     * Flatten this notification from a parcel.
1451     */
1452    public void writeToParcel(Parcel parcel, int flags)
1453    {
1454        parcel.writeInt(1);
1455
1456        parcel.writeLong(when);
1457        parcel.writeInt(icon);
1458        parcel.writeInt(number);
1459        if (contentIntent != null) {
1460            parcel.writeInt(1);
1461            contentIntent.writeToParcel(parcel, 0);
1462        } else {
1463            parcel.writeInt(0);
1464        }
1465        if (deleteIntent != null) {
1466            parcel.writeInt(1);
1467            deleteIntent.writeToParcel(parcel, 0);
1468        } else {
1469            parcel.writeInt(0);
1470        }
1471        if (tickerText != null) {
1472            parcel.writeInt(1);
1473            TextUtils.writeToParcel(tickerText, parcel, flags);
1474        } else {
1475            parcel.writeInt(0);
1476        }
1477        if (tickerView != null) {
1478            parcel.writeInt(1);
1479            tickerView.writeToParcel(parcel, 0);
1480        } else {
1481            parcel.writeInt(0);
1482        }
1483        if (contentView != null) {
1484            parcel.writeInt(1);
1485            contentView.writeToParcel(parcel, 0);
1486        } else {
1487            parcel.writeInt(0);
1488        }
1489        if (largeIcon != null) {
1490            parcel.writeInt(1);
1491            largeIcon.writeToParcel(parcel, 0);
1492        } else {
1493            parcel.writeInt(0);
1494        }
1495
1496        parcel.writeInt(defaults);
1497        parcel.writeInt(this.flags);
1498
1499        if (sound != null) {
1500            parcel.writeInt(1);
1501            sound.writeToParcel(parcel, 0);
1502        } else {
1503            parcel.writeInt(0);
1504        }
1505        parcel.writeInt(audioStreamType);
1506
1507        if (audioAttributes != null) {
1508            parcel.writeInt(1);
1509            audioAttributes.writeToParcel(parcel, 0);
1510        } else {
1511            parcel.writeInt(0);
1512        }
1513
1514        parcel.writeLongArray(vibrate);
1515        parcel.writeInt(ledARGB);
1516        parcel.writeInt(ledOnMS);
1517        parcel.writeInt(ledOffMS);
1518        parcel.writeInt(iconLevel);
1519
1520        if (fullScreenIntent != null) {
1521            parcel.writeInt(1);
1522            fullScreenIntent.writeToParcel(parcel, 0);
1523        } else {
1524            parcel.writeInt(0);
1525        }
1526
1527        parcel.writeInt(priority);
1528
1529        parcel.writeString(category);
1530
1531        parcel.writeString(mGroupKey);
1532
1533        parcel.writeString(mSortKey);
1534
1535        parcel.writeBundle(extras); // null ok
1536
1537        parcel.writeTypedArray(actions, 0); // null ok
1538
1539        if (bigContentView != null) {
1540            parcel.writeInt(1);
1541            bigContentView.writeToParcel(parcel, 0);
1542        } else {
1543            parcel.writeInt(0);
1544        }
1545
1546        if (headsUpContentView != null) {
1547            parcel.writeInt(1);
1548            headsUpContentView.writeToParcel(parcel, 0);
1549        } else {
1550            parcel.writeInt(0);
1551        }
1552
1553        parcel.writeInt(visibility);
1554
1555        if (publicVersion != null) {
1556            parcel.writeInt(1);
1557            publicVersion.writeToParcel(parcel, 0);
1558        } else {
1559            parcel.writeInt(0);
1560        }
1561
1562        parcel.writeInt(color);
1563    }
1564
1565    /**
1566     * Parcelable.Creator that instantiates Notification objects
1567     */
1568    public static final Parcelable.Creator<Notification> CREATOR
1569            = new Parcelable.Creator<Notification>()
1570    {
1571        public Notification createFromParcel(Parcel parcel)
1572        {
1573            return new Notification(parcel);
1574        }
1575
1576        public Notification[] newArray(int size)
1577        {
1578            return new Notification[size];
1579        }
1580    };
1581
1582    /**
1583     * Sets the {@link #contentView} field to be a view with the standard "Latest Event"
1584     * layout.
1585     *
1586     * <p>Uses the {@link #icon} and {@link #when} fields to set the icon and time fields
1587     * in the view.</p>
1588     * @param context       The context for your application / activity.
1589     * @param contentTitle The title that goes in the expanded entry.
1590     * @param contentText  The text that goes in the expanded entry.
1591     * @param contentIntent The intent to launch when the user clicks the expanded notification.
1592     * If this is an activity, it must include the
1593     * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires
1594     * that you take care of task management as described in the
1595     * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back
1596     * Stack</a> document.
1597     *
1598     * @deprecated Use {@link Builder} instead.
1599     */
1600    @Deprecated
1601    public void setLatestEventInfo(Context context,
1602            CharSequence contentTitle, CharSequence contentText, PendingIntent contentIntent) {
1603        Notification.Builder builder = new Notification.Builder(context);
1604
1605        // First, ensure that key pieces of information that may have been set directly
1606        // are preserved
1607        builder.setWhen(this.when);
1608        builder.setSmallIcon(this.icon);
1609        builder.setPriority(this.priority);
1610        builder.setTicker(this.tickerText);
1611        builder.setNumber(this.number);
1612        builder.setColor(this.color);
1613        builder.mFlags = this.flags;
1614        builder.setSound(this.sound, this.audioStreamType);
1615        builder.setDefaults(this.defaults);
1616        builder.setVibrate(this.vibrate);
1617
1618        // now apply the latestEventInfo fields
1619        if (contentTitle != null) {
1620            builder.setContentTitle(contentTitle);
1621        }
1622        if (contentText != null) {
1623            builder.setContentText(contentText);
1624        }
1625        builder.setContentIntent(contentIntent);
1626        builder.buildInto(this);
1627    }
1628
1629    @Override
1630    public String toString() {
1631        StringBuilder sb = new StringBuilder();
1632        sb.append("Notification(pri=");
1633        sb.append(priority);
1634        sb.append(" contentView=");
1635        if (contentView != null) {
1636            sb.append(contentView.getPackage());
1637            sb.append("/0x");
1638            sb.append(Integer.toHexString(contentView.getLayoutId()));
1639        } else {
1640            sb.append("null");
1641        }
1642        sb.append(" vibrate=");
1643        if ((this.defaults & DEFAULT_VIBRATE) != 0) {
1644            sb.append("default");
1645        } else if (this.vibrate != null) {
1646            int N = this.vibrate.length-1;
1647            sb.append("[");
1648            for (int i=0; i<N; i++) {
1649                sb.append(this.vibrate[i]);
1650                sb.append(',');
1651            }
1652            if (N != -1) {
1653                sb.append(this.vibrate[N]);
1654            }
1655            sb.append("]");
1656        } else {
1657            sb.append("null");
1658        }
1659        sb.append(" sound=");
1660        if ((this.defaults & DEFAULT_SOUND) != 0) {
1661            sb.append("default");
1662        } else if (this.sound != null) {
1663            sb.append(this.sound.toString());
1664        } else {
1665            sb.append("null");
1666        }
1667        sb.append(" defaults=0x");
1668        sb.append(Integer.toHexString(this.defaults));
1669        sb.append(" flags=0x");
1670        sb.append(Integer.toHexString(this.flags));
1671        sb.append(String.format(" color=0x%08x", this.color));
1672        if (this.category != null) {
1673            sb.append(" category=");
1674            sb.append(this.category);
1675        }
1676        if (this.mGroupKey != null) {
1677            sb.append(" groupKey=");
1678            sb.append(this.mGroupKey);
1679        }
1680        if (this.mSortKey != null) {
1681            sb.append(" sortKey=");
1682            sb.append(this.mSortKey);
1683        }
1684        if (actions != null) {
1685            sb.append(" actions=");
1686            sb.append(actions.length);
1687        }
1688        sb.append(" vis=");
1689        sb.append(visibilityToString(this.visibility));
1690        if (this.publicVersion != null) {
1691            sb.append(" publicVersion=");
1692            sb.append(publicVersion.toString());
1693        }
1694        sb.append(")");
1695        return sb.toString();
1696    }
1697
1698    /**
1699     * {@hide}
1700     */
1701    public static String visibilityToString(int vis) {
1702        switch (vis) {
1703            case VISIBILITY_PRIVATE:
1704                return "PRIVATE";
1705            case VISIBILITY_PUBLIC:
1706                return "PUBLIC";
1707            case VISIBILITY_SECRET:
1708                return "SECRET";
1709            default:
1710                return "UNKNOWN(" + String.valueOf(vis) + ")";
1711        }
1712    }
1713
1714    /**
1715     * @hide
1716     */
1717    public boolean isValid() {
1718        // Would like to check for icon!=0 here, too, but NotificationManagerService accepts that
1719        // for legacy reasons.
1720        return contentView != null || extras.getBoolean(Builder.EXTRA_REBUILD_CONTENT_VIEW);
1721    }
1722
1723    /**
1724     * @hide
1725     */
1726    public boolean isGroupSummary() {
1727        return mGroupKey != null && (flags & FLAG_GROUP_SUMMARY) != 0;
1728    }
1729
1730    /**
1731     * @hide
1732     */
1733    public boolean isGroupChild() {
1734        return mGroupKey != null && (flags & FLAG_GROUP_SUMMARY) == 0;
1735    }
1736
1737    /**
1738     * Builder class for {@link Notification} objects.
1739     *
1740     * Provides a convenient way to set the various fields of a {@link Notification} and generate
1741     * content views using the platform's notification layout template. If your app supports
1742     * versions of Android as old as API level 4, you can instead use
1743     * {@link android.support.v4.app.NotificationCompat.Builder NotificationCompat.Builder},
1744     * available in the <a href="{@docRoot}tools/extras/support-library.html">Android Support
1745     * library</a>.
1746     *
1747     * <p>Example:
1748     *
1749     * <pre class="prettyprint">
1750     * Notification noti = new Notification.Builder(mContext)
1751     *         .setContentTitle(&quot;New mail from &quot; + sender.toString())
1752     *         .setContentText(subject)
1753     *         .setSmallIcon(R.drawable.new_mail)
1754     *         .setLargeIcon(aBitmap)
1755     *         .build();
1756     * </pre>
1757     */
1758    public static class Builder {
1759        private static final int MAX_ACTION_BUTTONS = 3;
1760        private static final float LARGE_TEXT_SCALE = 1.3f;
1761
1762        /**
1763         * @hide
1764         */
1765        public static final String EXTRA_NEEDS_REBUILD = "android.rebuild";
1766
1767        /**
1768         * @hide
1769         */
1770        public static final String EXTRA_REBUILD_LARGE_ICON = "android.rebuild.largeIcon";
1771        /**
1772         * @hide
1773         */
1774        public static final String EXTRA_REBUILD_CONTENT_VIEW = "android.rebuild.contentView";
1775        /**
1776         * @hide
1777         */
1778        public static final String EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT =
1779                "android.rebuild.contentViewActionCount";
1780        /**
1781         * @hide
1782         */
1783        public static final String EXTRA_REBUILD_BIG_CONTENT_VIEW
1784                = "android.rebuild.bigView";
1785        /**
1786         * @hide
1787         */
1788        public static final String EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT
1789                = "android.rebuild.bigViewActionCount";
1790        /**
1791         * @hide
1792         */
1793        public static final String EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW
1794                = "android.rebuild.hudView";
1795        /**
1796         * @hide
1797         */
1798        public static final String EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT
1799                = "android.rebuild.hudViewActionCount";
1800
1801        /**
1802         * The package name of the context used to create the notification via a Builder.
1803         */
1804        private static final String EXTRA_REBUILD_CONTEXT_PACKAGE =
1805                "android.rebuild.contextPackage";
1806
1807        // Whether to enable stripping (at post time) & rebuilding (at listener receive time) of
1808        // memory intensive resources.
1809        private static final boolean STRIP_AND_REBUILD = true;
1810
1811        private Context mContext;
1812
1813        private long mWhen;
1814        private int mSmallIcon;
1815        private int mSmallIconLevel;
1816        private int mNumber;
1817        private CharSequence mContentTitle;
1818        private CharSequence mContentText;
1819        private CharSequence mContentInfo;
1820        private CharSequence mSubText;
1821        private PendingIntent mContentIntent;
1822        private RemoteViews mContentView;
1823        private PendingIntent mDeleteIntent;
1824        private PendingIntent mFullScreenIntent;
1825        private CharSequence mTickerText;
1826        private RemoteViews mTickerView;
1827        private Bitmap mLargeIcon;
1828        private Uri mSound;
1829        private int mAudioStreamType;
1830        private AudioAttributes mAudioAttributes;
1831        private long[] mVibrate;
1832        private int mLedArgb;
1833        private int mLedOnMs;
1834        private int mLedOffMs;
1835        private int mDefaults;
1836        private int mFlags;
1837        private int mProgressMax;
1838        private int mProgress;
1839        private boolean mProgressIndeterminate;
1840        private String mCategory;
1841        private String mGroupKey;
1842        private String mSortKey;
1843        private Bundle mExtras;
1844        private int mPriority;
1845        private ArrayList<Action> mActions = new ArrayList<Action>(MAX_ACTION_BUTTONS);
1846        private boolean mUseChronometer;
1847        private Style mStyle;
1848        private boolean mShowWhen = true;
1849        private int mVisibility = VISIBILITY_PRIVATE;
1850        private Notification mPublicVersion = null;
1851        private final NotificationColorUtil mColorUtil;
1852        private ArrayList<String> mPeople;
1853        private int mColor = COLOR_DEFAULT;
1854
1855        /**
1856         * The user that built the notification originally.
1857         */
1858        private int mOriginatingUserId;
1859
1860        /**
1861         * Contains extras related to rebuilding during the build phase.
1862         */
1863        private Bundle mRebuildBundle = new Bundle();
1864        /**
1865         * Contains the notification to rebuild when this Builder is in "rebuild" mode.
1866         * Null otherwise.
1867         */
1868        private Notification mRebuildNotification = null;
1869
1870        /**
1871         * Whether the build notification has three lines. This is used to make the top padding for
1872         * both the contracted and expanded layout consistent.
1873         *
1874         * <p>
1875         * This field is only valid during the build phase.
1876         */
1877        private boolean mHasThreeLines;
1878
1879        /**
1880         * Constructs a new Builder with the defaults:
1881         *
1882
1883         * <table>
1884         * <tr><th align=right>priority</th>
1885         *     <td>{@link #PRIORITY_DEFAULT}</td></tr>
1886         * <tr><th align=right>when</th>
1887         *     <td>now ({@link System#currentTimeMillis()})</td></tr>
1888         * <tr><th align=right>audio stream</th>
1889         *     <td>{@link #STREAM_DEFAULT}</td></tr>
1890         * </table>
1891         *
1892
1893         * @param context
1894         *            A {@link Context} that will be used by the Builder to construct the
1895         *            RemoteViews. The Context will not be held past the lifetime of this Builder
1896         *            object.
1897         */
1898        public Builder(Context context) {
1899            /*
1900             * Important compatibility note!
1901             * Some apps out in the wild create a Notification.Builder in their Activity subclass
1902             * constructor for later use. At this point Activities - themselves subclasses of
1903             * ContextWrapper - do not have their inner Context populated yet. This means that
1904             * any calls to Context methods from within this constructor can cause NPEs in existing
1905             * apps. Any data populated from mContext should therefore be populated lazily to
1906             * preserve compatibility.
1907             */
1908            mContext = context;
1909
1910            // Set defaults to match the defaults of a Notification
1911            mWhen = System.currentTimeMillis();
1912            mAudioStreamType = STREAM_DEFAULT;
1913            mAudioAttributes = AUDIO_ATTRIBUTES_DEFAULT;
1914            mPriority = PRIORITY_DEFAULT;
1915            mPeople = new ArrayList<String>();
1916
1917            mColorUtil = context.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.L ?
1918                    NotificationColorUtil.getInstance() : null;
1919        }
1920
1921        /**
1922         * Creates a Builder for rebuilding the given Notification.
1923         * <p>
1924         * Call {@link #rebuild()} to retrieve the rebuilt version of 'n'.
1925         */
1926        private Builder(Context context, Notification n) {
1927            this(context);
1928            mRebuildNotification = n;
1929            restoreFromNotification(n);
1930
1931            Style style = null;
1932            Bundle extras = n.extras;
1933            String templateClass = extras.getString(EXTRA_TEMPLATE);
1934            if (!TextUtils.isEmpty(templateClass)) {
1935                Class<? extends Style> styleClass = getNotificationStyleClass(templateClass);
1936                if (styleClass == null) {
1937                    Log.d(TAG, "Unknown style class: " + styleClass);
1938                    return;
1939                }
1940
1941                try {
1942                    Constructor<? extends Style> constructor = styleClass.getConstructor();
1943                    style = constructor.newInstance();
1944                    style.restoreFromExtras(extras);
1945                } catch (Throwable t) {
1946                    Log.e(TAG, "Could not create Style", t);
1947                    return;
1948                }
1949            }
1950            if (style != null) {
1951                setStyle(style);
1952            }
1953        }
1954
1955        /**
1956         * Add a timestamp pertaining to the notification (usually the time the event occurred).
1957         * It will be shown in the notification content view by default; use
1958         * {@link #setShowWhen(boolean) setShowWhen} to control this.
1959         *
1960         * @see Notification#when
1961         */
1962        public Builder setWhen(long when) {
1963            mWhen = when;
1964            return this;
1965        }
1966
1967        /**
1968         * Control whether the timestamp set with {@link #setWhen(long) setWhen} is shown
1969         * in the content view.
1970         */
1971        public Builder setShowWhen(boolean show) {
1972            mShowWhen = show;
1973            return this;
1974        }
1975
1976        /**
1977         * Show the {@link Notification#when} field as a stopwatch.
1978         *
1979         * Instead of presenting <code>when</code> as a timestamp, the notification will show an
1980         * automatically updating display of the minutes and seconds since <code>when</code>.
1981         *
1982         * Useful when showing an elapsed time (like an ongoing phone call).
1983         *
1984         * @see android.widget.Chronometer
1985         * @see Notification#when
1986         */
1987        public Builder setUsesChronometer(boolean b) {
1988            mUseChronometer = b;
1989            return this;
1990        }
1991
1992        /**
1993         * Set the small icon resource, which will be used to represent the notification in the
1994         * status bar.
1995         *
1996
1997         * The platform template for the expanded view will draw this icon in the left, unless a
1998         * {@link #setLargeIcon(Bitmap) large icon} has also been specified, in which case the small
1999         * icon will be moved to the right-hand side.
2000         *
2001
2002         * @param icon
2003         *            A resource ID in the application's package of the drawable to use.
2004         * @see Notification#icon
2005         */
2006        public Builder setSmallIcon(int icon) {
2007            mSmallIcon = icon;
2008            return this;
2009        }
2010
2011        /**
2012         * A variant of {@link #setSmallIcon(int) setSmallIcon(int)} that takes an additional
2013         * level parameter for when the icon is a {@link android.graphics.drawable.LevelListDrawable
2014         * LevelListDrawable}.
2015         *
2016         * @param icon A resource ID in the application's package of the drawable to use.
2017         * @param level The level to use for the icon.
2018         *
2019         * @see Notification#icon
2020         * @see Notification#iconLevel
2021         */
2022        public Builder setSmallIcon(int icon, int level) {
2023            mSmallIcon = icon;
2024            mSmallIconLevel = level;
2025            return this;
2026        }
2027
2028        /**
2029         * Set the first line of text in the platform notification template.
2030         */
2031        public Builder setContentTitle(CharSequence title) {
2032            mContentTitle = safeCharSequence(title);
2033            return this;
2034        }
2035
2036        /**
2037         * Set the second line of text in the platform notification template.
2038         */
2039        public Builder setContentText(CharSequence text) {
2040            mContentText = safeCharSequence(text);
2041            return this;
2042        }
2043
2044        /**
2045         * Set the third line of text in the platform notification template.
2046         * Don't use if you're also using {@link #setProgress(int, int, boolean)}; they occupy the
2047         * same location in the standard template.
2048         */
2049        public Builder setSubText(CharSequence text) {
2050            mSubText = safeCharSequence(text);
2051            return this;
2052        }
2053
2054        /**
2055         * Set the large number at the right-hand side of the notification.  This is
2056         * equivalent to setContentInfo, although it might show the number in a different
2057         * font size for readability.
2058         */
2059        public Builder setNumber(int number) {
2060            mNumber = number;
2061            return this;
2062        }
2063
2064        /**
2065         * A small piece of additional information pertaining to this notification.
2066         *
2067         * The platform template will draw this on the last line of the notification, at the far
2068         * right (to the right of a smallIcon if it has been placed there).
2069         */
2070        public Builder setContentInfo(CharSequence info) {
2071            mContentInfo = safeCharSequence(info);
2072            return this;
2073        }
2074
2075        /**
2076         * Set the progress this notification represents.
2077         *
2078         * The platform template will represent this using a {@link ProgressBar}.
2079         */
2080        public Builder setProgress(int max, int progress, boolean indeterminate) {
2081            mProgressMax = max;
2082            mProgress = progress;
2083            mProgressIndeterminate = indeterminate;
2084            return this;
2085        }
2086
2087        /**
2088         * Supply a custom RemoteViews to use instead of the platform template.
2089         *
2090         * @see Notification#contentView
2091         */
2092        public Builder setContent(RemoteViews views) {
2093            mContentView = views;
2094            return this;
2095        }
2096
2097        /**
2098         * Supply a {@link PendingIntent} to be sent when the notification is clicked.
2099         *
2100         * As of {@link android.os.Build.VERSION_CODES#HONEYCOMB}, if this field is unset and you
2101         * have specified a custom RemoteViews with {@link #setContent(RemoteViews)}, you can use
2102         * {@link RemoteViews#setOnClickPendingIntent RemoteViews.setOnClickPendingIntent(int,PendingIntent)}
2103         * to assign PendingIntents to individual views in that custom layout (i.e., to create
2104         * clickable buttons inside the notification view).
2105         *
2106         * @see Notification#contentIntent Notification.contentIntent
2107         */
2108        public Builder setContentIntent(PendingIntent intent) {
2109            mContentIntent = intent;
2110            return this;
2111        }
2112
2113        /**
2114         * Supply a {@link PendingIntent} to send when the notification is cleared explicitly by the user.
2115         *
2116         * @see Notification#deleteIntent
2117         */
2118        public Builder setDeleteIntent(PendingIntent intent) {
2119            mDeleteIntent = intent;
2120            return this;
2121        }
2122
2123        /**
2124         * An intent to launch instead of posting the notification to the status bar.
2125         * Only for use with extremely high-priority notifications demanding the user's
2126         * <strong>immediate</strong> attention, such as an incoming phone call or
2127         * alarm clock that the user has explicitly set to a particular time.
2128         * If this facility is used for something else, please give the user an option
2129         * to turn it off and use a normal notification, as this can be extremely
2130         * disruptive.
2131         *
2132         * <p>
2133         * The system UI may choose to display a heads-up notification, instead of
2134         * launching this intent, while the user is using the device.
2135         * </p>
2136         *
2137         * @param intent The pending intent to launch.
2138         * @param highPriority Passing true will cause this notification to be sent
2139         *          even if other notifications are suppressed.
2140         *
2141         * @see Notification#fullScreenIntent
2142         */
2143        public Builder setFullScreenIntent(PendingIntent intent, boolean highPriority) {
2144            mFullScreenIntent = intent;
2145            setFlag(FLAG_HIGH_PRIORITY, highPriority);
2146            return this;
2147        }
2148
2149        /**
2150         * Set the "ticker" text which is sent to accessibility services.
2151         *
2152         * @see Notification#tickerText
2153         */
2154        public Builder setTicker(CharSequence tickerText) {
2155            mTickerText = safeCharSequence(tickerText);
2156            return this;
2157        }
2158
2159        /**
2160         * Obsolete version of {@link #setTicker(CharSequence)}.
2161         *
2162         */
2163        @Deprecated
2164        public Builder setTicker(CharSequence tickerText, RemoteViews views) {
2165            mTickerText = safeCharSequence(tickerText);
2166            mTickerView = views; // we'll save it for you anyway
2167            return this;
2168        }
2169
2170        /**
2171         * Add a large icon to the notification (and the ticker on some devices).
2172         *
2173         * In the platform template, this image will be shown on the left of the notification view
2174         * in place of the {@link #setSmallIcon(int) small icon} (which will move to the right side).
2175         *
2176         * @see Notification#largeIcon
2177         */
2178        public Builder setLargeIcon(Bitmap icon) {
2179            mLargeIcon = icon;
2180            return this;
2181        }
2182
2183        /**
2184         * Set the sound to play.
2185         *
2186         * It will be played using the {@link #AUDIO_ATTRIBUTES_DEFAULT default audio attributes}
2187         * for notifications.
2188         *
2189         * <p>
2190         * A notification that is noisy is more likely to be presented as a heads-up notification.
2191         * </p>
2192         *
2193         * @see Notification#sound
2194         */
2195        public Builder setSound(Uri sound) {
2196            mSound = sound;
2197            mAudioAttributes = AUDIO_ATTRIBUTES_DEFAULT;
2198            return this;
2199        }
2200
2201        /**
2202         * Set the sound to play, along with a specific stream on which to play it.
2203         *
2204         * See {@link android.media.AudioManager} for the <code>STREAM_</code> constants.
2205         *
2206         * <p>
2207         * A notification that is noisy is more likely to be presented as a heads-up notification.
2208         * </p>
2209         * @deprecated use {@link #setSound(Uri, AudioAttributes)} instead.
2210         * @see Notification#sound
2211         */
2212        @Deprecated
2213        public Builder setSound(Uri sound, int streamType) {
2214            mSound = sound;
2215            mAudioStreamType = streamType;
2216            return this;
2217        }
2218
2219        /**
2220         * Set the sound to play, along with specific {@link AudioAttributes audio attributes} to
2221         * use during playback.
2222         *
2223         * <p>
2224         * A notification that is noisy is more likely to be presented as a heads-up notification.
2225         * </p>
2226         *
2227         * @see Notification#sound
2228         */
2229        public Builder setSound(Uri sound, AudioAttributes audioAttributes) {
2230            mSound = sound;
2231            mAudioAttributes = audioAttributes;
2232            return this;
2233        }
2234
2235        /**
2236         * Set the vibration pattern to use.
2237         *
2238         * See {@link android.os.Vibrator#vibrate(long[], int)} for a discussion of the
2239         * <code>pattern</code> parameter.
2240         *
2241         * <p>
2242         * A notification that vibrates is more likely to be presented as a heads-up notification.
2243         * </p>
2244         *
2245         * @see Notification#vibrate
2246         */
2247        public Builder setVibrate(long[] pattern) {
2248            mVibrate = pattern;
2249            return this;
2250        }
2251
2252        /**
2253         * Set the desired color for the indicator LED on the device, as well as the
2254         * blink duty cycle (specified in milliseconds).
2255         *
2256
2257         * Not all devices will honor all (or even any) of these values.
2258         *
2259
2260         * @see Notification#ledARGB
2261         * @see Notification#ledOnMS
2262         * @see Notification#ledOffMS
2263         */
2264        public Builder setLights(int argb, int onMs, int offMs) {
2265            mLedArgb = argb;
2266            mLedOnMs = onMs;
2267            mLedOffMs = offMs;
2268            return this;
2269        }
2270
2271        /**
2272         * Set whether this is an "ongoing" notification.
2273         *
2274
2275         * Ongoing notifications cannot be dismissed by the user, so your application or service
2276         * must take care of canceling them.
2277         *
2278
2279         * They are typically used to indicate a background task that the user is actively engaged
2280         * with (e.g., playing music) or is pending in some way and therefore occupying the device
2281         * (e.g., a file download, sync operation, active network connection).
2282         *
2283
2284         * @see Notification#FLAG_ONGOING_EVENT
2285         * @see Service#setForeground(boolean)
2286         */
2287        public Builder setOngoing(boolean ongoing) {
2288            setFlag(FLAG_ONGOING_EVENT, ongoing);
2289            return this;
2290        }
2291
2292        /**
2293         * Set this flag if you would only like the sound, vibrate
2294         * and ticker to be played if the notification is not already showing.
2295         *
2296         * @see Notification#FLAG_ONLY_ALERT_ONCE
2297         */
2298        public Builder setOnlyAlertOnce(boolean onlyAlertOnce) {
2299            setFlag(FLAG_ONLY_ALERT_ONCE, onlyAlertOnce);
2300            return this;
2301        }
2302
2303        /**
2304         * Make this notification automatically dismissed when the user touches it. The
2305         * PendingIntent set with {@link #setDeleteIntent} will be sent when this happens.
2306         *
2307         * @see Notification#FLAG_AUTO_CANCEL
2308         */
2309        public Builder setAutoCancel(boolean autoCancel) {
2310            setFlag(FLAG_AUTO_CANCEL, autoCancel);
2311            return this;
2312        }
2313
2314        /**
2315         * Set whether or not this notification should not bridge to other devices.
2316         *
2317         * <p>Some notifications can be bridged to other devices for remote display.
2318         * This hint can be set to recommend this notification not be bridged.
2319         */
2320        public Builder setLocalOnly(boolean localOnly) {
2321            setFlag(FLAG_LOCAL_ONLY, localOnly);
2322            return this;
2323        }
2324
2325        /**
2326         * Set which notification properties will be inherited from system defaults.
2327         * <p>
2328         * The value should be one or more of the following fields combined with
2329         * bitwise-or:
2330         * {@link #DEFAULT_SOUND}, {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}.
2331         * <p>
2332         * For all default values, use {@link #DEFAULT_ALL}.
2333         */
2334        public Builder setDefaults(int defaults) {
2335            mDefaults = defaults;
2336            return this;
2337        }
2338
2339        /**
2340         * Set the priority of this notification.
2341         *
2342         * @see Notification#priority
2343         */
2344        public Builder setPriority(@Priority int pri) {
2345            mPriority = pri;
2346            return this;
2347        }
2348
2349        /**
2350         * Set the notification category.
2351         *
2352         * @see Notification#category
2353         */
2354        public Builder setCategory(String category) {
2355            mCategory = category;
2356            return this;
2357        }
2358
2359        /**
2360         * Add a person that is relevant to this notification.
2361         *
2362         * @see Notification#EXTRA_PEOPLE
2363         */
2364        public Builder addPerson(String handle) {
2365            mPeople.add(handle);
2366            return this;
2367        }
2368
2369        /**
2370         * Set this notification to be part of a group of notifications sharing the same key.
2371         * Grouped notifications may display in a cluster or stack on devices which
2372         * support such rendering.
2373         *
2374         * <p>To make this notification the summary for its group, also call
2375         * {@link #setGroupSummary}. A sort order can be specified for group members by using
2376         * {@link #setSortKey}.
2377         * @param groupKey The group key of the group.
2378         * @return this object for method chaining
2379         */
2380        public Builder setGroup(String groupKey) {
2381            mGroupKey = groupKey;
2382            return this;
2383        }
2384
2385        /**
2386         * Set this notification to be the group summary for a group of notifications.
2387         * Grouped notifications may display in a cluster or stack on devices which
2388         * support such rendering. Requires a group key also be set using {@link #setGroup}.
2389         * @param isGroupSummary Whether this notification should be a group summary.
2390         * @return this object for method chaining
2391         */
2392        public Builder setGroupSummary(boolean isGroupSummary) {
2393            setFlag(FLAG_GROUP_SUMMARY, isGroupSummary);
2394            return this;
2395        }
2396
2397        /**
2398         * Set a sort key that orders this notification among other notifications from the
2399         * same package. This can be useful if an external sort was already applied and an app
2400         * would like to preserve this. Notifications will be sorted lexicographically using this
2401         * value, although providing different priorities in addition to providing sort key may
2402         * cause this value to be ignored.
2403         *
2404         * <p>This sort key can also be used to order members of a notification group. See
2405         * {@link #setGroup}.
2406         *
2407         * @see String#compareTo(String)
2408         */
2409        public Builder setSortKey(String sortKey) {
2410            mSortKey = sortKey;
2411            return this;
2412        }
2413
2414        /**
2415         * Merge additional metadata into this notification.
2416         *
2417         * <p>Values within the Bundle will replace existing extras values in this Builder.
2418         *
2419         * @see Notification#extras
2420         */
2421        public Builder addExtras(Bundle extras) {
2422            if (extras != null) {
2423                if (mExtras == null) {
2424                    mExtras = new Bundle(extras);
2425                } else {
2426                    mExtras.putAll(extras);
2427                }
2428            }
2429            return this;
2430        }
2431
2432        /**
2433         * Set metadata for this notification.
2434         *
2435         * <p>A reference to the Bundle is held for the lifetime of this Builder, and the Bundle's
2436         * current contents are copied into the Notification each time {@link #build()} is
2437         * called.
2438         *
2439         * <p>Replaces any existing extras values with those from the provided Bundle.
2440         * Use {@link #addExtras} to merge in metadata instead.
2441         *
2442         * @see Notification#extras
2443         */
2444        public Builder setExtras(Bundle extras) {
2445            mExtras = extras;
2446            return this;
2447        }
2448
2449        /**
2450         * Get the current metadata Bundle used by this notification Builder.
2451         *
2452         * <p>The returned Bundle is shared with this Builder.
2453         *
2454         * <p>The current contents of this Bundle are copied into the Notification each time
2455         * {@link #build()} is called.
2456         *
2457         * @see Notification#extras
2458         */
2459        public Bundle getExtras() {
2460            if (mExtras == null) {
2461                mExtras = new Bundle();
2462            }
2463            return mExtras;
2464        }
2465
2466        /**
2467         * Add an action to this notification. Actions are typically displayed by
2468         * the system as a button adjacent to the notification content.
2469         * <p>
2470         * Every action must have an icon (32dp square and matching the
2471         * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo
2472         * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}.
2473         * <p>
2474         * A notification in its expanded form can display up to 3 actions, from left to right in
2475         * the order they were added. Actions will not be displayed when the notification is
2476         * collapsed, however, so be sure that any essential functions may be accessed by the user
2477         * in some other way (for example, in the Activity pointed to by {@link #contentIntent}).
2478         *
2479         * @param icon Resource ID of a drawable that represents the action.
2480         * @param title Text describing the action.
2481         * @param intent PendingIntent to be fired when the action is invoked.
2482         */
2483        public Builder addAction(int icon, CharSequence title, PendingIntent intent) {
2484            mActions.add(new Action(icon, safeCharSequence(title), intent));
2485            return this;
2486        }
2487
2488        /**
2489         * Add an action to this notification. Actions are typically displayed by
2490         * the system as a button adjacent to the notification content.
2491         * <p>
2492         * Every action must have an icon (32dp square and matching the
2493         * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo
2494         * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}.
2495         * <p>
2496         * A notification in its expanded form can display up to 3 actions, from left to right in
2497         * the order they were added. Actions will not be displayed when the notification is
2498         * collapsed, however, so be sure that any essential functions may be accessed by the user
2499         * in some other way (for example, in the Activity pointed to by {@link #contentIntent}).
2500         *
2501         * @param action The action to add.
2502         */
2503        public Builder addAction(Action action) {
2504            mActions.add(action);
2505            return this;
2506        }
2507
2508        /**
2509         * Add a rich notification style to be applied at build time.
2510         *
2511         * @param style Object responsible for modifying the notification style.
2512         */
2513        public Builder setStyle(Style style) {
2514            if (mStyle != style) {
2515                mStyle = style;
2516                if (mStyle != null) {
2517                    mStyle.setBuilder(this);
2518                }
2519            }
2520            return this;
2521        }
2522
2523        /**
2524         * Specify the value of {@link #visibility}.
2525         *
2526         * @param visibility One of {@link #VISIBILITY_PRIVATE} (the default),
2527         * {@link #VISIBILITY_SECRET}, or {@link #VISIBILITY_PUBLIC}.
2528         *
2529         * @return The same Builder.
2530         */
2531        public Builder setVisibility(int visibility) {
2532            mVisibility = visibility;
2533            return this;
2534        }
2535
2536        /**
2537         * Supply a replacement Notification whose contents should be shown in insecure contexts
2538         * (i.e. atop the secure lockscreen). See {@link #visibility} and {@link #VISIBILITY_PUBLIC}.
2539         * @param n A replacement notification, presumably with some or all info redacted.
2540         * @return The same Builder.
2541         */
2542        public Builder setPublicVersion(Notification n) {
2543            mPublicVersion = n;
2544            return this;
2545        }
2546
2547        /**
2548         * Apply an extender to this notification builder. Extenders may be used to add
2549         * metadata or change options on this builder.
2550         */
2551        public Builder extend(Extender extender) {
2552            extender.extend(this);
2553            return this;
2554        }
2555
2556        private void setFlag(int mask, boolean value) {
2557            if (value) {
2558                mFlags |= mask;
2559            } else {
2560                mFlags &= ~mask;
2561            }
2562        }
2563
2564        /**
2565         * Sets {@link Notification#color}.
2566         *
2567         * @param argb The accent color to use
2568         *
2569         * @return The same Builder.
2570         */
2571        public Builder setColor(int argb) {
2572            mColor = argb;
2573            return this;
2574        }
2575
2576        private Drawable getProfileBadgeDrawable() {
2577            // Note: This assumes that the current user can read the profile badge of the
2578            // originating user.
2579            UserManager userManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
2580            return userManager.getBadgeForUser(new UserHandle(mOriginatingUserId), 0);
2581        }
2582
2583        private Bitmap getProfileBadge() {
2584            Drawable badge = getProfileBadgeDrawable();
2585            if (badge == null) {
2586                return null;
2587            }
2588            final int size = mContext.getResources().getDimensionPixelSize(
2589                    R.dimen.notification_badge_size);
2590            Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
2591            Canvas canvas = new Canvas(bitmap);
2592            badge.setBounds(0, 0, size, size);
2593            badge.draw(canvas);
2594            return bitmap;
2595        }
2596
2597        private boolean addProfileBadge(RemoteViews contentView, int resId) {
2598            Bitmap profileBadge = getProfileBadge();
2599
2600            contentView.setViewVisibility(R.id.profile_badge_large_template, View.GONE);
2601            contentView.setViewVisibility(R.id.profile_badge_line2, View.GONE);
2602            contentView.setViewVisibility(R.id.profile_badge_line3, View.GONE);
2603
2604            if (profileBadge != null) {
2605                contentView.setImageViewBitmap(resId, profileBadge);
2606                contentView.setViewVisibility(resId, View.VISIBLE);
2607
2608                // Make sure Line 3 is visible. As badge will be here if there
2609                // is no text to display.
2610                if (resId == R.id.profile_badge_line3) {
2611                    contentView.setViewVisibility(R.id.line3, View.VISIBLE);
2612                }
2613                return true;
2614            }
2615            return false;
2616        }
2617
2618        private void shrinkLine3Text(RemoteViews contentView) {
2619            float subTextSize = mContext.getResources().getDimensionPixelSize(
2620                    R.dimen.notification_subtext_size);
2621            contentView.setTextViewTextSize(R.id.text, TypedValue.COMPLEX_UNIT_PX, subTextSize);
2622        }
2623
2624        private RemoteViews applyStandardTemplate(int resId) {
2625            RemoteViews contentView = new BuilderRemoteViews(mContext.getPackageName(),
2626                    mOriginatingUserId, resId);
2627
2628            boolean showLine3 = false;
2629            boolean showLine2 = false;
2630            boolean contentTextInLine2 = false;
2631
2632            if (mLargeIcon != null) {
2633                contentView.setImageViewBitmap(R.id.icon, mLargeIcon);
2634                processLargeLegacyIcon(mLargeIcon, contentView);
2635                contentView.setImageViewResource(R.id.right_icon, mSmallIcon);
2636                contentView.setViewVisibility(R.id.right_icon, View.VISIBLE);
2637                processSmallRightIcon(mSmallIcon, contentView);
2638            } else { // small icon at left
2639                contentView.setImageViewResource(R.id.icon, mSmallIcon);
2640                contentView.setViewVisibility(R.id.icon, View.VISIBLE);
2641                processSmallIconAsLarge(mSmallIcon, contentView);
2642            }
2643            if (mContentTitle != null) {
2644                contentView.setTextViewText(R.id.title, processLegacyText(mContentTitle));
2645            }
2646            if (mContentText != null) {
2647                contentView.setTextViewText(R.id.text, processLegacyText(mContentText));
2648                showLine3 = true;
2649            }
2650            if (mContentInfo != null) {
2651                contentView.setTextViewText(R.id.info, processLegacyText(mContentInfo));
2652                contentView.setViewVisibility(R.id.info, View.VISIBLE);
2653                showLine3 = true;
2654            } else if (mNumber > 0) {
2655                final int tooBig = mContext.getResources().getInteger(
2656                        R.integer.status_bar_notification_info_maxnum);
2657                if (mNumber > tooBig) {
2658                    contentView.setTextViewText(R.id.info, processLegacyText(
2659                            mContext.getResources().getString(
2660                                    R.string.status_bar_notification_info_overflow)));
2661                } else {
2662                    NumberFormat f = NumberFormat.getIntegerInstance();
2663                    contentView.setTextViewText(R.id.info, processLegacyText(f.format(mNumber)));
2664                }
2665                contentView.setViewVisibility(R.id.info, View.VISIBLE);
2666                showLine3 = true;
2667            } else {
2668                contentView.setViewVisibility(R.id.info, View.GONE);
2669            }
2670
2671            // Need to show three lines?
2672            if (mSubText != null) {
2673                contentView.setTextViewText(R.id.text, processLegacyText(mSubText));
2674                if (mContentText != null) {
2675                    contentView.setTextViewText(R.id.text2, processLegacyText(mContentText));
2676                    contentView.setViewVisibility(R.id.text2, View.VISIBLE);
2677                    showLine2 = true;
2678                    contentTextInLine2 = true;
2679                } else {
2680                    contentView.setViewVisibility(R.id.text2, View.GONE);
2681                }
2682            } else {
2683                contentView.setViewVisibility(R.id.text2, View.GONE);
2684                if (mProgressMax != 0 || mProgressIndeterminate) {
2685                    contentView.setProgressBar(
2686                            R.id.progress, mProgressMax, mProgress, mProgressIndeterminate);
2687                    contentView.setViewVisibility(R.id.progress, View.VISIBLE);
2688                    showLine2 = true;
2689                } else {
2690                    contentView.setViewVisibility(R.id.progress, View.GONE);
2691                }
2692            }
2693            if (showLine2) {
2694
2695                // need to shrink all the type to make sure everything fits
2696                shrinkLine3Text(contentView);
2697            }
2698
2699            if (mWhen != 0 && mShowWhen) {
2700                if (mUseChronometer) {
2701                    contentView.setViewVisibility(R.id.chronometer, View.VISIBLE);
2702                    contentView.setLong(R.id.chronometer, "setBase",
2703                            mWhen + (SystemClock.elapsedRealtime() - System.currentTimeMillis()));
2704                    contentView.setBoolean(R.id.chronometer, "setStarted", true);
2705                } else {
2706                    contentView.setViewVisibility(R.id.time, View.VISIBLE);
2707                    contentView.setLong(R.id.time, "setTime", mWhen);
2708                }
2709            } else {
2710                contentView.setViewVisibility(R.id.time, View.GONE);
2711            }
2712
2713            // Adjust padding depending on line count and font size.
2714            contentView.setViewPadding(R.id.line1, 0, calculateTopPadding(mContext,
2715                    mHasThreeLines, mContext.getResources().getConfiguration().fontScale),
2716                    0, 0);
2717
2718            // We want to add badge to first line of text.
2719            boolean addedBadge = addProfileBadge(contentView,
2720                    contentTextInLine2 ? R.id.profile_badge_line2 : R.id.profile_badge_line3);
2721            // If we added the badge to line 3 then we should show line 3.
2722            if (addedBadge && !contentTextInLine2) {
2723                showLine3 = true;
2724            }
2725
2726            // Note getStandardView may hide line 3 again.
2727            contentView.setViewVisibility(R.id.line3, showLine3 ? View.VISIBLE : View.GONE);
2728            contentView.setViewVisibility(R.id.overflow_divider, showLine3 ? View.VISIBLE : View.GONE);
2729            return contentView;
2730        }
2731
2732        /**
2733         * Logic to find out whether the notification is going to have three lines in the contracted
2734         * layout. This is used to adjust the top padding.
2735         *
2736         * @return true if the notification is going to have three lines; false if the notification
2737         *         is going to have one or two lines
2738         */
2739        private boolean hasThreeLines() {
2740            boolean contentTextInLine2 = mSubText != null && mContentText != null;
2741
2742            // If we have content text in line 2, badge goes into line 2, or line 3 otherwise
2743            boolean badgeInLine3 = getProfileBadgeDrawable() != null && !contentTextInLine2;
2744            boolean hasLine3 = mContentText != null || mContentInfo != null || mNumber > 0
2745                    || badgeInLine3;
2746            boolean hasLine2 = (mSubText != null && mContentText != null) ||
2747                    (mSubText == null && (mProgressMax != 0 || mProgressIndeterminate));
2748            return hasLine2 && hasLine3;
2749        }
2750
2751        /**
2752         * @hide
2753         */
2754        public static int calculateTopPadding(Context ctx, boolean hasThreeLines,
2755                float fontScale) {
2756            int padding = ctx.getResources().getDimensionPixelSize(hasThreeLines
2757                    ? R.dimen.notification_top_pad_narrow
2758                    : R.dimen.notification_top_pad);
2759            int largePadding = ctx.getResources().getDimensionPixelSize(hasThreeLines
2760                    ? R.dimen.notification_top_pad_large_text_narrow
2761                    : R.dimen.notification_top_pad_large_text);
2762            float largeFactor = (MathUtils.constrain(fontScale, 1.0f, LARGE_TEXT_SCALE) - 1f)
2763                    / (LARGE_TEXT_SCALE - 1f);
2764
2765            // Linearly interpolate the padding between large and normal with the font scale ranging
2766            // from 1f to LARGE_TEXT_SCALE
2767            return Math.round((1 - largeFactor) * padding + largeFactor * largePadding);
2768        }
2769
2770        private RemoteViews applyStandardTemplateWithActions(int layoutId) {
2771            RemoteViews big = applyStandardTemplate(layoutId);
2772
2773            int N = mActions.size();
2774            if (N > 0) {
2775                big.setViewVisibility(R.id.actions, View.VISIBLE);
2776                big.setViewVisibility(R.id.action_divider, View.VISIBLE);
2777                if (N>MAX_ACTION_BUTTONS) N=MAX_ACTION_BUTTONS;
2778                big.removeAllViews(R.id.actions);
2779                for (int i=0; i<N; i++) {
2780                    final RemoteViews button = generateActionButton(mActions.get(i));
2781                    big.addView(R.id.actions, button);
2782                }
2783            }
2784            return big;
2785        }
2786
2787        private RemoteViews makeContentView() {
2788            if (mContentView != null) {
2789                return mContentView;
2790            } else {
2791                return applyStandardTemplate(getBaseLayoutResource());
2792            }
2793        }
2794
2795        private RemoteViews makeTickerView() {
2796            if (mTickerView != null) {
2797                return mTickerView;
2798            }
2799            return null; // tickers are not created by default anymore
2800        }
2801
2802        private RemoteViews makeBigContentView() {
2803            if (mActions.size() == 0) return null;
2804
2805            return applyStandardTemplateWithActions(getBigBaseLayoutResource());
2806        }
2807
2808        private RemoteViews makeHeadsUpContentView() {
2809            if (mActions.size() == 0) return null;
2810
2811            return applyStandardTemplateWithActions(getBigBaseLayoutResource());
2812        }
2813
2814
2815        private RemoteViews generateActionButton(Action action) {
2816            final boolean tombstone = (action.actionIntent == null);
2817            RemoteViews button = new RemoteViews(mContext.getPackageName(),
2818                    tombstone ? getActionTombstoneLayoutResource()
2819                              : getActionLayoutResource());
2820            button.setTextViewCompoundDrawablesRelative(R.id.action0, action.icon, 0, 0, 0);
2821            button.setTextViewText(R.id.action0, processLegacyText(action.title));
2822            if (!tombstone) {
2823                button.setOnClickPendingIntent(R.id.action0, action.actionIntent);
2824            }
2825            button.setContentDescription(R.id.action0, action.title);
2826            processLegacyAction(action, button);
2827            return button;
2828        }
2829
2830        /**
2831         * @return Whether we are currently building a notification from a legacy (an app that
2832         *         doesn't create material notifications by itself) app.
2833         */
2834        private boolean isLegacy() {
2835            return mColorUtil != null;
2836        }
2837
2838        private void processLegacyAction(Action action, RemoteViews button) {
2839            if (!isLegacy() || mColorUtil.isGrayscale(mContext, action.icon)) {
2840                button.setTextViewCompoundDrawablesRelativeColorFilter(R.id.action0, 0,
2841                        mContext.getResources().getColor(R.color.notification_action_color_filter),
2842                        PorterDuff.Mode.MULTIPLY);
2843            }
2844        }
2845
2846        private CharSequence processLegacyText(CharSequence charSequence) {
2847            if (isLegacy()) {
2848                return mColorUtil.invertCharSequenceColors(charSequence);
2849            } else {
2850                return charSequence;
2851            }
2852        }
2853
2854        /**
2855         * Apply any necessary background to smallIcons being used in the largeIcon spot.
2856         */
2857        private void processSmallIconAsLarge(int largeIconId, RemoteViews contentView) {
2858            if (!isLegacy() || mColorUtil.isGrayscale(mContext, largeIconId)) {
2859                applyLargeIconBackground(contentView);
2860            }
2861        }
2862
2863        /**
2864         * Apply any necessary background to a largeIcon if it's a fake smallIcon (that is,
2865         * if it's grayscale).
2866         */
2867        // TODO: also check bounds, transparency, that sort of thing.
2868        private void processLargeLegacyIcon(Bitmap largeIcon, RemoteViews contentView) {
2869            if (isLegacy() && mColorUtil.isGrayscale(largeIcon)) {
2870                applyLargeIconBackground(contentView);
2871            } else {
2872                removeLargeIconBackground(contentView);
2873            }
2874        }
2875
2876        /**
2877         * Add a colored circle behind the largeIcon slot.
2878         */
2879        private void applyLargeIconBackground(RemoteViews contentView) {
2880            contentView.setInt(R.id.icon, "setBackgroundResource",
2881                    R.drawable.notification_icon_legacy_bg);
2882
2883            contentView.setDrawableParameters(
2884                    R.id.icon,
2885                    true,
2886                    -1,
2887                    resolveColor(),
2888                    PorterDuff.Mode.SRC_ATOP,
2889                    -1);
2890
2891            int padding = mContext.getResources().getDimensionPixelSize(
2892                    R.dimen.notification_large_icon_circle_padding);
2893            contentView.setViewPadding(R.id.icon, padding, padding, padding, padding);
2894        }
2895
2896        private void removeLargeIconBackground(RemoteViews contentView) {
2897            contentView.setInt(R.id.icon, "setBackgroundResource", 0);
2898        }
2899
2900        /**
2901         * Recolor small icons when used in the R.id.right_icon slot.
2902         */
2903        private void processSmallRightIcon(int smallIconDrawableId,
2904                RemoteViews contentView) {
2905            if (!isLegacy() || mColorUtil.isGrayscale(mContext, smallIconDrawableId)) {
2906                contentView.setDrawableParameters(R.id.right_icon, false, -1,
2907                        0xFFFFFFFF,
2908                        PorterDuff.Mode.SRC_ATOP, -1);
2909
2910                contentView.setInt(R.id.right_icon,
2911                        "setBackgroundResource",
2912                        R.drawable.notification_icon_legacy_bg);
2913
2914                contentView.setDrawableParameters(
2915                        R.id.right_icon,
2916                        true,
2917                        -1,
2918                        resolveColor(),
2919                        PorterDuff.Mode.SRC_ATOP,
2920                        -1);
2921            }
2922        }
2923
2924        private int sanitizeColor() {
2925            if (mColor != COLOR_DEFAULT) {
2926                mColor |= 0xFF000000; // no alpha for custom colors
2927            }
2928            return mColor;
2929        }
2930
2931        private int resolveColor() {
2932            if (mColor == COLOR_DEFAULT) {
2933                return mContext.getResources().getColor(R.color.notification_icon_bg_color);
2934            }
2935            return mColor;
2936        }
2937
2938        /**
2939         * Apply the unstyled operations and return a new {@link Notification} object.
2940         * @hide
2941         */
2942        public Notification buildUnstyled() {
2943            Notification n = new Notification();
2944            n.when = mWhen;
2945            n.icon = mSmallIcon;
2946            n.iconLevel = mSmallIconLevel;
2947            n.number = mNumber;
2948
2949            n.color = sanitizeColor();
2950
2951            setBuilderContentView(n, makeContentView());
2952            n.contentIntent = mContentIntent;
2953            n.deleteIntent = mDeleteIntent;
2954            n.fullScreenIntent = mFullScreenIntent;
2955            n.tickerText = mTickerText;
2956            n.tickerView = makeTickerView();
2957            n.largeIcon = mLargeIcon;
2958            n.sound = mSound;
2959            n.audioStreamType = mAudioStreamType;
2960            n.audioAttributes = mAudioAttributes;
2961            n.vibrate = mVibrate;
2962            n.ledARGB = mLedArgb;
2963            n.ledOnMS = mLedOnMs;
2964            n.ledOffMS = mLedOffMs;
2965            n.defaults = mDefaults;
2966            n.flags = mFlags;
2967            setBuilderBigContentView(n, makeBigContentView());
2968            setBuilderHeadsUpContentView(n, makeHeadsUpContentView());
2969            if (mLedOnMs != 0 || mLedOffMs != 0) {
2970                n.flags |= FLAG_SHOW_LIGHTS;
2971            }
2972            if ((mDefaults & DEFAULT_LIGHTS) != 0) {
2973                n.flags |= FLAG_SHOW_LIGHTS;
2974            }
2975            n.category = mCategory;
2976            n.mGroupKey = mGroupKey;
2977            n.mSortKey = mSortKey;
2978            n.priority = mPriority;
2979            if (mActions.size() > 0) {
2980                n.actions = new Action[mActions.size()];
2981                mActions.toArray(n.actions);
2982            }
2983            n.visibility = mVisibility;
2984
2985            if (mPublicVersion != null) {
2986                n.publicVersion = new Notification();
2987                mPublicVersion.cloneInto(n.publicVersion, true);
2988            }
2989            // Note: If you're adding new fields, also update restoreFromNotitification().
2990            return n;
2991        }
2992
2993        /**
2994         * Capture, in the provided bundle, semantic information used in the construction of
2995         * this Notification object.
2996         * @hide
2997         */
2998        public void populateExtras(Bundle extras) {
2999            // Store original information used in the construction of this object
3000            extras.putInt(EXTRA_ORIGINATING_USERID, mOriginatingUserId);
3001            extras.putString(EXTRA_REBUILD_CONTEXT_PACKAGE, mContext.getPackageName());
3002            extras.putCharSequence(EXTRA_TITLE, mContentTitle);
3003            extras.putCharSequence(EXTRA_TEXT, mContentText);
3004            extras.putCharSequence(EXTRA_SUB_TEXT, mSubText);
3005            extras.putCharSequence(EXTRA_INFO_TEXT, mContentInfo);
3006            extras.putInt(EXTRA_SMALL_ICON, mSmallIcon);
3007            extras.putInt(EXTRA_PROGRESS, mProgress);
3008            extras.putInt(EXTRA_PROGRESS_MAX, mProgressMax);
3009            extras.putBoolean(EXTRA_PROGRESS_INDETERMINATE, mProgressIndeterminate);
3010            extras.putBoolean(EXTRA_SHOW_CHRONOMETER, mUseChronometer);
3011            extras.putBoolean(EXTRA_SHOW_WHEN, mShowWhen);
3012            if (mLargeIcon != null) {
3013                extras.putParcelable(EXTRA_LARGE_ICON, mLargeIcon);
3014            }
3015            if (!mPeople.isEmpty()) {
3016                extras.putStringArray(EXTRA_PEOPLE, mPeople.toArray(new String[mPeople.size()]));
3017            }
3018            // NOTE: If you're adding new extras also update restoreFromNotification().
3019        }
3020
3021
3022        /**
3023         * @hide
3024         */
3025        public static void stripForDelivery(Notification n) {
3026            if (!STRIP_AND_REBUILD) {
3027                return;
3028            }
3029
3030            String templateClass = n.extras.getString(EXTRA_TEMPLATE);
3031            // Only strip views for known Styles because we won't know how to
3032            // re-create them otherwise.
3033            boolean stripViews = TextUtils.isEmpty(templateClass) ||
3034                    getNotificationStyleClass(templateClass) != null;
3035
3036            boolean isStripped = false;
3037
3038            if (n.largeIcon != null && n.extras.containsKey(EXTRA_LARGE_ICON)) {
3039                // TODO: Would like to check for equality here, but if the notification
3040                // has been cloned, we can't.
3041                n.largeIcon = null;
3042                n.extras.putBoolean(EXTRA_REBUILD_LARGE_ICON, true);
3043                isStripped = true;
3044            }
3045            // Get rid of unmodified BuilderRemoteViews.
3046
3047            if (stripViews &&
3048                    n.contentView instanceof BuilderRemoteViews &&
3049                    n.extras.getInt(EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT, -1) ==
3050                            n.contentView.getSequenceNumber()) {
3051                n.contentView = null;
3052                n.extras.putBoolean(EXTRA_REBUILD_CONTENT_VIEW, true);
3053                n.extras.remove(EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT);
3054                isStripped = true;
3055            }
3056            if (stripViews &&
3057                    n.bigContentView instanceof BuilderRemoteViews &&
3058                    n.extras.getInt(EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT, -1) ==
3059                            n.bigContentView.getSequenceNumber()) {
3060                n.bigContentView = null;
3061                n.extras.putBoolean(EXTRA_REBUILD_BIG_CONTENT_VIEW, true);
3062                n.extras.remove(EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT);
3063                isStripped = true;
3064            }
3065            if (stripViews &&
3066                    n.headsUpContentView instanceof BuilderRemoteViews &&
3067                    n.extras.getInt(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT, -1) ==
3068                            n.headsUpContentView.getSequenceNumber()) {
3069                n.headsUpContentView = null;
3070                n.extras.putBoolean(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW, true);
3071                n.extras.remove(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT);
3072                isStripped = true;
3073            }
3074
3075            if (isStripped) {
3076                n.extras.putBoolean(EXTRA_NEEDS_REBUILD, true);
3077            }
3078        }
3079
3080        /**
3081         * @hide
3082         */
3083        public static Notification rebuild(Context context, Notification n) {
3084            Bundle extras = n.extras;
3085            if (!extras.getBoolean(EXTRA_NEEDS_REBUILD)) return n;
3086            extras.remove(EXTRA_NEEDS_REBUILD);
3087
3088            // Re-create notification context so we can access app resources.
3089            String packageName = extras.getString(EXTRA_REBUILD_CONTEXT_PACKAGE);
3090            Context builderContext;
3091            try {
3092                builderContext = context.createPackageContext(packageName,
3093                        Context.CONTEXT_RESTRICTED);
3094            } catch (NameNotFoundException e) {
3095                Log.e(TAG, "Package name " + packageName + " not found");
3096                builderContext = context;  // try with our context
3097            }
3098
3099            Builder b = new Builder(builderContext, n);
3100            return b.rebuild();
3101        }
3102
3103        /**
3104         * Rebuilds the notification passed in to the rebuild-constructor
3105         * {@link #Builder(Context, Notification)}.
3106         *
3107         * <p>
3108         * Throws IllegalStateException when invoked on a Builder that isn't in rebuild mode.
3109         *
3110         * @hide
3111         */
3112        private Notification rebuild() {
3113            if (mRebuildNotification == null) {
3114                throw new IllegalStateException("rebuild() only valid when in 'rebuild' mode.");
3115            }
3116            mHasThreeLines = hasThreeLines();
3117
3118            Bundle extras = mRebuildNotification.extras;
3119
3120            if (extras.getBoolean(EXTRA_REBUILD_LARGE_ICON)) {
3121                mRebuildNotification.largeIcon = extras.getParcelable(EXTRA_LARGE_ICON);
3122            }
3123            extras.remove(EXTRA_REBUILD_LARGE_ICON);
3124
3125            if (extras.getBoolean(EXTRA_REBUILD_CONTENT_VIEW)) {
3126                setBuilderContentView(mRebuildNotification, makeContentView());
3127                if (mStyle != null) {
3128                    mStyle.populateContentView(mRebuildNotification);
3129                }
3130            }
3131            extras.remove(EXTRA_REBUILD_CONTENT_VIEW);
3132
3133            if (extras.getBoolean(EXTRA_REBUILD_BIG_CONTENT_VIEW)) {
3134                setBuilderBigContentView(mRebuildNotification, makeBigContentView());
3135                if (mStyle != null) {
3136                    mStyle.populateBigContentView(mRebuildNotification);
3137                }
3138            }
3139            extras.remove(EXTRA_REBUILD_BIG_CONTENT_VIEW);
3140
3141            if (extras.getBoolean(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW)) {
3142                setBuilderHeadsUpContentView(mRebuildNotification, makeHeadsUpContentView());
3143                if (mStyle != null) {
3144                    mStyle.populateHeadsUpContentView(mRebuildNotification);
3145                }
3146            }
3147            extras.remove(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW);
3148
3149            mHasThreeLines = false;
3150            return mRebuildNotification;
3151        }
3152
3153        private static Class<? extends Style> getNotificationStyleClass(String templateClass) {
3154            Class<? extends Style>[] classes = new Class[]{
3155                    BigTextStyle.class, BigPictureStyle.class, InboxStyle.class, MediaStyle.class};
3156            for (Class<? extends Style> innerClass : classes) {
3157                if (templateClass.equals(innerClass.getName())) {
3158                    return innerClass;
3159                }
3160            }
3161            return null;
3162        }
3163
3164        private void setBuilderContentView(Notification n, RemoteViews contentView) {
3165            n.contentView = contentView;
3166            if (contentView instanceof BuilderRemoteViews) {
3167                mRebuildBundle.putInt(Builder.EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT,
3168                        contentView.getSequenceNumber());
3169            }
3170        }
3171
3172        private void setBuilderBigContentView(Notification n, RemoteViews bigContentView) {
3173            n.bigContentView = bigContentView;
3174            if (bigContentView instanceof BuilderRemoteViews) {
3175                mRebuildBundle.putInt(Builder.EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT,
3176                        bigContentView.getSequenceNumber());
3177            }
3178        }
3179
3180        private void setBuilderHeadsUpContentView(Notification n,
3181                RemoteViews headsUpContentView) {
3182            n.headsUpContentView = headsUpContentView;
3183            if (headsUpContentView instanceof BuilderRemoteViews) {
3184                mRebuildBundle.putInt(Builder.EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT,
3185                        headsUpContentView.getSequenceNumber());
3186            }
3187        }
3188
3189        private void restoreFromNotification(Notification n) {
3190
3191            // Notification fields.
3192            mWhen = n.when;
3193            mSmallIcon = n.icon;
3194            mSmallIconLevel = n.iconLevel;
3195            mNumber = n.number;
3196
3197            mColor = n.color;
3198
3199            mContentView = n.contentView;
3200            mDeleteIntent = n.deleteIntent;
3201            mFullScreenIntent = n.fullScreenIntent;
3202            mTickerText = n.tickerText;
3203            mTickerView = n.tickerView;
3204            mLargeIcon = n.largeIcon;
3205            mSound = n.sound;
3206            mAudioStreamType = n.audioStreamType;
3207            mAudioAttributes = n.audioAttributes;
3208
3209            mVibrate = n.vibrate;
3210            mLedArgb = n.ledARGB;
3211            mLedOnMs = n.ledOnMS;
3212            mLedOffMs = n.ledOffMS;
3213            mDefaults = n.defaults;
3214            mFlags = n.flags;
3215
3216            mCategory = n.category;
3217            mGroupKey = n.mGroupKey;
3218            mSortKey = n.mSortKey;
3219            mPriority = n.priority;
3220            mActions.clear();
3221            if (n.actions != null) {
3222                Collections.addAll(mActions, n.actions);
3223            }
3224            mVisibility = n.visibility;
3225
3226            mPublicVersion = n.publicVersion;
3227
3228            // Extras.
3229            Bundle extras = n.extras;
3230            mOriginatingUserId = extras.getInt(EXTRA_ORIGINATING_USERID);
3231            mContentTitle = extras.getCharSequence(EXTRA_TITLE);
3232            mContentText = extras.getCharSequence(EXTRA_TEXT);
3233            mSubText = extras.getCharSequence(EXTRA_SUB_TEXT);
3234            mContentInfo = extras.getCharSequence(EXTRA_INFO_TEXT);
3235            mSmallIcon = extras.getInt(EXTRA_SMALL_ICON);
3236            mProgress = extras.getInt(EXTRA_PROGRESS);
3237            mProgressMax = extras.getInt(EXTRA_PROGRESS_MAX);
3238            mProgressIndeterminate = extras.getBoolean(EXTRA_PROGRESS_INDETERMINATE);
3239            mUseChronometer = extras.getBoolean(EXTRA_SHOW_CHRONOMETER);
3240            mShowWhen = extras.getBoolean(EXTRA_SHOW_WHEN);
3241            if (extras.containsKey(EXTRA_LARGE_ICON)) {
3242                mLargeIcon = extras.getParcelable(EXTRA_LARGE_ICON);
3243            }
3244            if (extras.containsKey(EXTRA_PEOPLE)) {
3245                mPeople.clear();
3246                Collections.addAll(mPeople, extras.getStringArray(EXTRA_PEOPLE));
3247            }
3248        }
3249
3250        /**
3251         * @deprecated Use {@link #build()} instead.
3252         */
3253        @Deprecated
3254        public Notification getNotification() {
3255            return build();
3256        }
3257
3258        /**
3259         * Combine all of the options that have been set and return a new {@link Notification}
3260         * object.
3261         */
3262        public Notification build() {
3263            mOriginatingUserId = mContext.getUserId();
3264            mHasThreeLines = hasThreeLines();
3265
3266            Notification n = buildUnstyled();
3267
3268            if (mStyle != null) {
3269                n = mStyle.buildStyled(n);
3270            }
3271
3272            if (mExtras != null) {
3273                n.extras.putAll(mExtras);
3274            }
3275
3276            if (mRebuildBundle.size() > 0) {
3277                n.extras.putAll(mRebuildBundle);
3278                mRebuildBundle.clear();
3279            }
3280
3281            populateExtras(n.extras);
3282            if (mStyle != null) {
3283                mStyle.addExtras(n.extras);
3284            }
3285
3286            mHasThreeLines = false;
3287            return n;
3288        }
3289
3290        /**
3291         * Apply this Builder to an existing {@link Notification} object.
3292         *
3293         * @hide
3294         */
3295        public Notification buildInto(Notification n) {
3296            build().cloneInto(n, true);
3297            return n;
3298        }
3299
3300        private int getBaseLayoutResource() {
3301            return R.layout.notification_template_material_base;
3302        }
3303
3304        private int getBigBaseLayoutResource() {
3305            return R.layout.notification_template_material_big_base;
3306        }
3307
3308        private int getBigPictureLayoutResource() {
3309            return R.layout.notification_template_material_big_picture;
3310        }
3311
3312        private int getBigTextLayoutResource() {
3313            return R.layout.notification_template_material_big_text;
3314        }
3315
3316        private int getInboxLayoutResource() {
3317            return R.layout.notification_template_material_inbox;
3318        }
3319
3320        private int getActionLayoutResource() {
3321            return R.layout.notification_material_action;
3322        }
3323
3324        private int getActionTombstoneLayoutResource() {
3325            return R.layout.notification_material_action_tombstone;
3326        }
3327    }
3328
3329    /**
3330     * An object that can apply a rich notification style to a {@link Notification.Builder}
3331     * object.
3332     */
3333    public static abstract class Style {
3334        private CharSequence mBigContentTitle;
3335        private CharSequence mSummaryText = null;
3336        private boolean mSummaryTextSet = false;
3337
3338        protected Builder mBuilder;
3339
3340        /**
3341         * Overrides ContentTitle in the big form of the template.
3342         * This defaults to the value passed to setContentTitle().
3343         */
3344        protected void internalSetBigContentTitle(CharSequence title) {
3345            mBigContentTitle = title;
3346        }
3347
3348        /**
3349         * Set the first line of text after the detail section in the big form of the template.
3350         */
3351        protected void internalSetSummaryText(CharSequence cs) {
3352            mSummaryText = cs;
3353            mSummaryTextSet = true;
3354        }
3355
3356        public void setBuilder(Builder builder) {
3357            if (mBuilder != builder) {
3358                mBuilder = builder;
3359                if (mBuilder != null) {
3360                    mBuilder.setStyle(this);
3361                }
3362            }
3363        }
3364
3365        protected void checkBuilder() {
3366            if (mBuilder == null) {
3367                throw new IllegalArgumentException("Style requires a valid Builder object");
3368            }
3369        }
3370
3371        protected RemoteViews getStandardView(int layoutId) {
3372            checkBuilder();
3373
3374            // Nasty.
3375            CharSequence oldBuilderContentTitle = mBuilder.mContentTitle;
3376            if (mBigContentTitle != null) {
3377                mBuilder.setContentTitle(mBigContentTitle);
3378            }
3379
3380            RemoteViews contentView = mBuilder.applyStandardTemplateWithActions(layoutId);
3381
3382            mBuilder.mContentTitle = oldBuilderContentTitle;
3383
3384            if (mBigContentTitle != null && mBigContentTitle.equals("")) {
3385                contentView.setViewVisibility(R.id.line1, View.GONE);
3386            } else {
3387                contentView.setViewVisibility(R.id.line1, View.VISIBLE);
3388            }
3389
3390            // The last line defaults to the subtext, but can be replaced by mSummaryText
3391            final CharSequence overflowText =
3392                    mSummaryTextSet ? mSummaryText
3393                                    : mBuilder.mSubText;
3394            if (overflowText != null) {
3395                contentView.setTextViewText(R.id.text, mBuilder.processLegacyText(overflowText));
3396                contentView.setViewVisibility(R.id.overflow_divider, View.VISIBLE);
3397                contentView.setViewVisibility(R.id.line3, View.VISIBLE);
3398            } else {
3399                // Clear text in case we use the line to show the profile badge.
3400                contentView.setTextViewText(R.id.text, "");
3401                contentView.setViewVisibility(R.id.overflow_divider, View.GONE);
3402                contentView.setViewVisibility(R.id.line3, View.GONE);
3403            }
3404
3405            return contentView;
3406        }
3407
3408        /**
3409         * Changes the padding of the first line such that the big and small content view have the
3410         * same top padding.
3411         *
3412         * @hide
3413         */
3414        protected void applyTopPadding(RemoteViews contentView) {
3415            int topPadding = Builder.calculateTopPadding(mBuilder.mContext,
3416                    mBuilder.mHasThreeLines,
3417                    mBuilder.mContext.getResources().getConfiguration().fontScale);
3418            contentView.setViewPadding(R.id.line1, 0, topPadding, 0, 0);
3419        }
3420
3421        /**
3422         * @hide
3423         */
3424        public void addExtras(Bundle extras) {
3425            if (mSummaryTextSet) {
3426                extras.putCharSequence(EXTRA_SUMMARY_TEXT, mSummaryText);
3427            }
3428            if (mBigContentTitle != null) {
3429                extras.putCharSequence(EXTRA_TITLE_BIG, mBigContentTitle);
3430            }
3431            extras.putString(EXTRA_TEMPLATE, this.getClass().getName());
3432        }
3433
3434        /**
3435         * @hide
3436         */
3437        protected void restoreFromExtras(Bundle extras) {
3438            if (extras.containsKey(EXTRA_SUMMARY_TEXT)) {
3439                mSummaryText = extras.getCharSequence(EXTRA_SUMMARY_TEXT);
3440                mSummaryTextSet = true;
3441            }
3442            if (extras.containsKey(EXTRA_TITLE_BIG)) {
3443                mBigContentTitle = extras.getCharSequence(EXTRA_TITLE_BIG);
3444            }
3445        }
3446
3447
3448        /**
3449         * @hide
3450         */
3451        public Notification buildStyled(Notification wip) {
3452            populateTickerView(wip);
3453            populateContentView(wip);
3454            populateBigContentView(wip);
3455            populateHeadsUpContentView(wip);
3456            return wip;
3457        }
3458
3459        // The following methods are split out so we can re-create notification partially.
3460        /**
3461         * @hide
3462         */
3463        protected void populateTickerView(Notification wip) {}
3464        /**
3465         * @hide
3466         */
3467        protected void populateContentView(Notification wip) {}
3468
3469        /**
3470         * @hide
3471         */
3472        protected void populateBigContentView(Notification wip) {}
3473
3474        /**
3475         * @hide
3476         */
3477        protected void populateHeadsUpContentView(Notification wip) {}
3478
3479        /**
3480         * Calls {@link android.app.Notification.Builder#build()} on the Builder this Style is
3481         * attached to.
3482         *
3483         * @return the fully constructed Notification.
3484         */
3485        public Notification build() {
3486            checkBuilder();
3487            return mBuilder.build();
3488        }
3489    }
3490
3491    /**
3492     * Helper class for generating large-format notifications that include a large image attachment.
3493     *
3494     * Here's how you'd set the <code>BigPictureStyle</code> on a notification:
3495     * <pre class="prettyprint">
3496     * Notification notif = new Notification.Builder(mContext)
3497     *     .setContentTitle(&quot;New photo from &quot; + sender.toString())
3498     *     .setContentText(subject)
3499     *     .setSmallIcon(R.drawable.new_post)
3500     *     .setLargeIcon(aBitmap)
3501     *     .setStyle(new Notification.BigPictureStyle()
3502     *         .bigPicture(aBigBitmap))
3503     *     .build();
3504     * </pre>
3505     *
3506     * @see Notification#bigContentView
3507     */
3508    public static class BigPictureStyle extends Style {
3509        private Bitmap mPicture;
3510        private Bitmap mBigLargeIcon;
3511        private boolean mBigLargeIconSet = false;
3512
3513        public BigPictureStyle() {
3514        }
3515
3516        public BigPictureStyle(Builder builder) {
3517            setBuilder(builder);
3518        }
3519
3520        /**
3521         * Overrides ContentTitle in the big form of the template.
3522         * This defaults to the value passed to setContentTitle().
3523         */
3524        public BigPictureStyle setBigContentTitle(CharSequence title) {
3525            internalSetBigContentTitle(safeCharSequence(title));
3526            return this;
3527        }
3528
3529        /**
3530         * Set the first line of text after the detail section in the big form of the template.
3531         */
3532        public BigPictureStyle setSummaryText(CharSequence cs) {
3533            internalSetSummaryText(safeCharSequence(cs));
3534            return this;
3535        }
3536
3537        /**
3538         * Provide the bitmap to be used as the payload for the BigPicture notification.
3539         */
3540        public BigPictureStyle bigPicture(Bitmap b) {
3541            mPicture = b;
3542            return this;
3543        }
3544
3545        /**
3546         * Override the large icon when the big notification is shown.
3547         */
3548        public BigPictureStyle bigLargeIcon(Bitmap b) {
3549            mBigLargeIconSet = true;
3550            mBigLargeIcon = b;
3551            return this;
3552        }
3553
3554        private RemoteViews makeBigContentView() {
3555            RemoteViews contentView = getStandardView(mBuilder.getBigPictureLayoutResource());
3556
3557            contentView.setImageViewBitmap(R.id.big_picture, mPicture);
3558
3559            applyTopPadding(contentView);
3560
3561            boolean twoTextLines = mBuilder.mSubText != null && mBuilder.mContentText != null;
3562            mBuilder.addProfileBadge(contentView,
3563                    twoTextLines ? R.id.profile_badge_line2 : R.id.profile_badge_line3);
3564            return contentView;
3565        }
3566
3567        /**
3568         * @hide
3569         */
3570        public void addExtras(Bundle extras) {
3571            super.addExtras(extras);
3572
3573            if (mBigLargeIconSet) {
3574                extras.putParcelable(EXTRA_LARGE_ICON_BIG, mBigLargeIcon);
3575            }
3576            extras.putParcelable(EXTRA_PICTURE, mPicture);
3577        }
3578
3579        /**
3580         * @hide
3581         */
3582        @Override
3583        protected void restoreFromExtras(Bundle extras) {
3584            super.restoreFromExtras(extras);
3585
3586            if (extras.containsKey(EXTRA_LARGE_ICON_BIG)) {
3587                mBigLargeIcon = extras.getParcelable(EXTRA_LARGE_ICON_BIG);
3588            }
3589            mPicture = extras.getParcelable(EXTRA_PICTURE);
3590        }
3591
3592        /**
3593         * @hide
3594         */
3595        @Override
3596        public void populateBigContentView(Notification wip) {
3597            mBuilder.setBuilderBigContentView(wip, makeBigContentView());
3598        }
3599    }
3600
3601    /**
3602     * Helper class for generating large-format notifications that include a lot of text.
3603     *
3604     * Here's how you'd set the <code>BigTextStyle</code> on a notification:
3605     * <pre class="prettyprint">
3606     * Notification notif = new Notification.Builder(mContext)
3607     *     .setContentTitle(&quot;New mail from &quot; + sender.toString())
3608     *     .setContentText(subject)
3609     *     .setSmallIcon(R.drawable.new_mail)
3610     *     .setLargeIcon(aBitmap)
3611     *     .setStyle(new Notification.BigTextStyle()
3612     *         .bigText(aVeryLongString))
3613     *     .build();
3614     * </pre>
3615     *
3616     * @see Notification#bigContentView
3617     */
3618    public static class BigTextStyle extends Style {
3619        private CharSequence mBigText;
3620
3621        public BigTextStyle() {
3622        }
3623
3624        public BigTextStyle(Builder builder) {
3625            setBuilder(builder);
3626        }
3627
3628        /**
3629         * Overrides ContentTitle in the big form of the template.
3630         * This defaults to the value passed to setContentTitle().
3631         */
3632        public BigTextStyle setBigContentTitle(CharSequence title) {
3633            internalSetBigContentTitle(safeCharSequence(title));
3634            return this;
3635        }
3636
3637        /**
3638         * Set the first line of text after the detail section in the big form of the template.
3639         */
3640        public BigTextStyle setSummaryText(CharSequence cs) {
3641            internalSetSummaryText(safeCharSequence(cs));
3642            return this;
3643        }
3644
3645        /**
3646         * Provide the longer text to be displayed in the big form of the
3647         * template in place of the content text.
3648         */
3649        public BigTextStyle bigText(CharSequence cs) {
3650            mBigText = safeCharSequence(cs);
3651            return this;
3652        }
3653
3654        /**
3655         * @hide
3656         */
3657        public void addExtras(Bundle extras) {
3658            super.addExtras(extras);
3659
3660            extras.putCharSequence(EXTRA_BIG_TEXT, mBigText);
3661        }
3662
3663        /**
3664         * @hide
3665         */
3666        @Override
3667        protected void restoreFromExtras(Bundle extras) {
3668            super.restoreFromExtras(extras);
3669
3670            mBigText = extras.getCharSequence(EXTRA_BIG_TEXT);
3671        }
3672
3673        private RemoteViews makeBigContentView() {
3674
3675            // Nasty
3676            CharSequence oldBuilderContentText = mBuilder.mContentText;
3677            mBuilder.mContentText = null;
3678
3679            RemoteViews contentView = getStandardView(mBuilder.getBigTextLayoutResource());
3680
3681            mBuilder.mContentText = oldBuilderContentText;
3682
3683            contentView.setTextViewText(R.id.big_text, mBuilder.processLegacyText(mBigText));
3684            contentView.setViewVisibility(R.id.big_text, View.VISIBLE);
3685            contentView.setViewVisibility(R.id.text2, View.GONE);
3686
3687            applyTopPadding(contentView);
3688
3689            mBuilder.shrinkLine3Text(contentView);
3690
3691            mBuilder.addProfileBadge(contentView, R.id.profile_badge_large_template);
3692
3693            return contentView;
3694        }
3695
3696        /**
3697         * @hide
3698         */
3699        @Override
3700        public void populateBigContentView(Notification wip) {
3701            mBuilder.setBuilderBigContentView(wip, makeBigContentView());
3702        }
3703    }
3704
3705    /**
3706     * Helper class for generating large-format notifications that include a list of (up to 5) strings.
3707     *
3708     * Here's how you'd set the <code>InboxStyle</code> on a notification:
3709     * <pre class="prettyprint">
3710     * Notification notif = new Notification.Builder(mContext)
3711     *     .setContentTitle(&quot;5 New mails from &quot; + sender.toString())
3712     *     .setContentText(subject)
3713     *     .setSmallIcon(R.drawable.new_mail)
3714     *     .setLargeIcon(aBitmap)
3715     *     .setStyle(new Notification.InboxStyle()
3716     *         .addLine(str1)
3717     *         .addLine(str2)
3718     *         .setContentTitle(&quot;&quot;)
3719     *         .setSummaryText(&quot;+3 more&quot;))
3720     *     .build();
3721     * </pre>
3722     *
3723     * @see Notification#bigContentView
3724     */
3725    public static class InboxStyle extends Style {
3726        private ArrayList<CharSequence> mTexts = new ArrayList<CharSequence>(5);
3727
3728        public InboxStyle() {
3729        }
3730
3731        public InboxStyle(Builder builder) {
3732            setBuilder(builder);
3733        }
3734
3735        /**
3736         * Overrides ContentTitle in the big form of the template.
3737         * This defaults to the value passed to setContentTitle().
3738         */
3739        public InboxStyle setBigContentTitle(CharSequence title) {
3740            internalSetBigContentTitle(safeCharSequence(title));
3741            return this;
3742        }
3743
3744        /**
3745         * Set the first line of text after the detail section in the big form of the template.
3746         */
3747        public InboxStyle setSummaryText(CharSequence cs) {
3748            internalSetSummaryText(safeCharSequence(cs));
3749            return this;
3750        }
3751
3752        /**
3753         * Append a line to the digest section of the Inbox notification.
3754         */
3755        public InboxStyle addLine(CharSequence cs) {
3756            mTexts.add(safeCharSequence(cs));
3757            return this;
3758        }
3759
3760        /**
3761         * @hide
3762         */
3763        public void addExtras(Bundle extras) {
3764            super.addExtras(extras);
3765
3766            CharSequence[] a = new CharSequence[mTexts.size()];
3767            extras.putCharSequenceArray(EXTRA_TEXT_LINES, mTexts.toArray(a));
3768        }
3769
3770        /**
3771         * @hide
3772         */
3773        @Override
3774        protected void restoreFromExtras(Bundle extras) {
3775            super.restoreFromExtras(extras);
3776
3777            mTexts.clear();
3778            if (extras.containsKey(EXTRA_TEXT_LINES)) {
3779                Collections.addAll(mTexts, extras.getCharSequenceArray(EXTRA_TEXT_LINES));
3780            }
3781        }
3782
3783        private RemoteViews makeBigContentView() {
3784            // Remove the content text so line3 disappears unless you have a summary
3785
3786            // Nasty
3787            CharSequence oldBuilderContentText = mBuilder.mContentText;
3788            mBuilder.mContentText = null;
3789
3790            RemoteViews contentView = getStandardView(mBuilder.getInboxLayoutResource());
3791
3792            mBuilder.mContentText = oldBuilderContentText;
3793
3794            contentView.setViewVisibility(R.id.text2, View.GONE);
3795
3796            int[] rowIds = {R.id.inbox_text0, R.id.inbox_text1, R.id.inbox_text2, R.id.inbox_text3,
3797                    R.id.inbox_text4, R.id.inbox_text5, R.id.inbox_text6};
3798
3799            // Make sure all rows are gone in case we reuse a view.
3800            for (int rowId : rowIds) {
3801                contentView.setViewVisibility(rowId, View.GONE);
3802            }
3803
3804            final boolean largeText =
3805                    mBuilder.mContext.getResources().getConfiguration().fontScale > 1f;
3806            final float subTextSize = mBuilder.mContext.getResources().getDimensionPixelSize(
3807                    R.dimen.notification_subtext_size);
3808            int i=0;
3809            while (i < mTexts.size() && i < rowIds.length) {
3810                CharSequence str = mTexts.get(i);
3811                if (str != null && !str.equals("")) {
3812                    contentView.setViewVisibility(rowIds[i], View.VISIBLE);
3813                    contentView.setTextViewText(rowIds[i], mBuilder.processLegacyText(str));
3814                    if (largeText) {
3815                        contentView.setTextViewTextSize(rowIds[i], TypedValue.COMPLEX_UNIT_PX,
3816                                subTextSize);
3817                    }
3818                }
3819                i++;
3820            }
3821
3822            contentView.setViewVisibility(R.id.inbox_end_pad,
3823                    mTexts.size() > 0 ? View.VISIBLE : View.GONE);
3824
3825            contentView.setViewVisibility(R.id.inbox_more,
3826                    mTexts.size() > rowIds.length ? View.VISIBLE : View.GONE);
3827
3828            applyTopPadding(contentView);
3829
3830            mBuilder.shrinkLine3Text(contentView);
3831
3832            mBuilder.addProfileBadge(contentView, R.id.profile_badge_large_template);
3833
3834            return contentView;
3835        }
3836
3837        /**
3838         * @hide
3839         */
3840        @Override
3841        public void populateBigContentView(Notification wip) {
3842            mBuilder.setBuilderBigContentView(wip, makeBigContentView());
3843        }
3844    }
3845
3846    /**
3847     * Notification style for media playback notifications.
3848     *
3849     * In the expanded form, {@link Notification#bigContentView}, up to 5
3850     * {@link Notification.Action}s specified with
3851     * {@link Notification.Builder#addAction(int, CharSequence, PendingIntent) addAction} will be
3852     * shown as icon-only pushbuttons, suitable for transport controls. The Bitmap given to
3853     * {@link Notification.Builder#setLargeIcon(android.graphics.Bitmap) setLargeIcon()} will be
3854     * treated as album artwork.
3855     *
3856     * Unlike the other styles provided here, MediaStyle can also modify the standard-size
3857     * {@link Notification#contentView}; by providing action indices to
3858     * {@link #setShowActionsInCompactView(int...)} you can promote up to 2 actions to be displayed
3859     * in the standard view alongside the usual content.
3860     *
3861     * Notifications created with MediaStyle will have their category set to
3862     * {@link Notification#CATEGORY_TRANSPORT CATEGORY_TRANSPORT} unless you set a different
3863     * category using {@link Notification.Builder#setCategory(String) setCategory()}.
3864     *
3865     * Finally, if you attach a {@link android.media.session.MediaSession.Token} using
3866     * {@link android.app.Notification.MediaStyle#setMediaSession(MediaSession.Token)},
3867     * the System UI can identify this as a notification representing an active media session
3868     * and respond accordingly (by showing album artwork in the lockscreen, for example).
3869     *
3870     * To use this style with your Notification, feed it to
3871     * {@link Notification.Builder#setStyle(android.app.Notification.Style)} like so:
3872     * <pre class="prettyprint">
3873     * Notification noti = new Notification.Builder()
3874     *     .setSmallIcon(R.drawable.ic_stat_player)
3875     *     .setContentTitle(&quot;Track title&quot;)     // these three lines are optional
3876     *     .setContentText(&quot;Artist - Album&quot;)   // if you use
3877     *     .setLargeIcon(albumArtBitmap))      // setMediaSession(token)
3878     *     .setStyle(<b>new Notification.MediaStyle()</b>
3879     *         .setMediaSession(mySession))
3880     *     .build();
3881     * </pre>
3882     *
3883     * @see Notification#bigContentView
3884     */
3885    public static class MediaStyle extends Style {
3886        static final int MAX_MEDIA_BUTTONS_IN_COMPACT = 2;
3887        static final int MAX_MEDIA_BUTTONS = 5;
3888
3889        private int[] mActionsToShowInCompact = null;
3890        private MediaSession.Token mToken;
3891
3892        public MediaStyle() {
3893        }
3894
3895        public MediaStyle(Builder builder) {
3896            setBuilder(builder);
3897        }
3898
3899        /**
3900         * Request up to 2 actions (by index in the order of addition) to be shown in the compact
3901         * notification view.
3902         */
3903        public MediaStyle setShowActionsInCompactView(int...actions) {
3904            mActionsToShowInCompact = actions;
3905            return this;
3906        }
3907
3908        /**
3909         * Attach a {@link android.media.session.MediaSession.Token} to this Notification
3910         * to provide additional playback information and control to the SystemUI.
3911         */
3912        public MediaStyle setMediaSession(MediaSession.Token token) {
3913            mToken = token;
3914            return this;
3915        }
3916
3917        /**
3918         * @hide
3919         */
3920        @Override
3921        public Notification buildStyled(Notification wip) {
3922            super.buildStyled(wip);
3923            if (wip.category == null) {
3924                wip.category = Notification.CATEGORY_TRANSPORT;
3925            }
3926            return wip;
3927        }
3928
3929        /**
3930         * @hide
3931         */
3932        @Override
3933        public void populateContentView(Notification wip) {
3934            mBuilder.setBuilderContentView(wip, makeMediaContentView());
3935        }
3936
3937        /**
3938         * @hide
3939         */
3940        @Override
3941        public void populateBigContentView(Notification wip) {
3942            mBuilder.setBuilderBigContentView(wip, makeMediaBigContentView());
3943        }
3944
3945        /** @hide */
3946        @Override
3947        public void addExtras(Bundle extras) {
3948            super.addExtras(extras);
3949
3950            if (mToken != null) {
3951                extras.putParcelable(EXTRA_MEDIA_SESSION, mToken);
3952            }
3953            if (mActionsToShowInCompact != null) {
3954                extras.putIntArray(EXTRA_COMPACT_ACTIONS, mActionsToShowInCompact);
3955            }
3956        }
3957
3958        /**
3959         * @hide
3960         */
3961        @Override
3962        protected void restoreFromExtras(Bundle extras) {
3963            super.restoreFromExtras(extras);
3964
3965            if (extras.containsKey(EXTRA_MEDIA_SESSION)) {
3966                mToken = extras.getParcelable(EXTRA_MEDIA_SESSION);
3967            }
3968            if (extras.containsKey(EXTRA_COMPACT_ACTIONS)) {
3969                mActionsToShowInCompact = extras.getIntArray(EXTRA_COMPACT_ACTIONS);
3970            }
3971        }
3972
3973        private RemoteViews generateMediaActionButton(Action action) {
3974            final boolean tombstone = (action.actionIntent == null);
3975            RemoteViews button = new RemoteViews(mBuilder.mContext.getPackageName(),
3976                    R.layout.notification_material_media_action);
3977            button.setImageViewResource(R.id.action0, action.icon);
3978            if (!tombstone) {
3979                button.setOnClickPendingIntent(R.id.action0, action.actionIntent);
3980            }
3981            button.setContentDescription(R.id.action0, action.title);
3982            return button;
3983        }
3984
3985        private RemoteViews makeMediaContentView() {
3986            RemoteViews view = mBuilder.applyStandardTemplate(
3987                    R.layout.notification_template_material_media);
3988
3989            final int numActions = mBuilder.mActions.size();
3990            final int N = mActionsToShowInCompact == null
3991                    ? 0
3992                    : Math.min(mActionsToShowInCompact.length, MAX_MEDIA_BUTTONS_IN_COMPACT);
3993            if (N > 0) {
3994                view.removeAllViews(R.id.actions);
3995                for (int i = 0; i < N; i++) {
3996                    if (i >= numActions) {
3997                        throw new IllegalArgumentException(String.format(
3998                                "setShowActionsInCompactView: action %d out of bounds (max %d)",
3999                                i, numActions - 1));
4000                    }
4001
4002                    final Action action = mBuilder.mActions.get(mActionsToShowInCompact[i]);
4003                    final RemoteViews button = generateMediaActionButton(action);
4004                    view.addView(R.id.actions, button);
4005                }
4006            }
4007            return view;
4008        }
4009
4010        private RemoteViews makeMediaBigContentView() {
4011            RemoteViews big = mBuilder.applyStandardTemplate(
4012                    R.layout.notification_template_material_big_media);
4013
4014            final int N = Math.min(mBuilder.mActions.size(), MAX_MEDIA_BUTTONS);
4015            if (N > 0) {
4016                big.removeAllViews(R.id.actions);
4017                for (int i=0; i<N; i++) {
4018                    final RemoteViews button = generateMediaActionButton(mBuilder.mActions.get(i));
4019                    big.addView(R.id.actions, button);
4020                }
4021            }
4022            return big;
4023        }
4024    }
4025
4026    // When adding a new Style subclass here, don't forget to update
4027    // Builder.getNotificationStyleClass.
4028
4029    /**
4030     * Extender interface for use with {@link Builder#extend}. Extenders may be used to add
4031     * metadata or change options on a notification builder.
4032     */
4033    public interface Extender {
4034        /**
4035         * Apply this extender to a notification builder.
4036         * @param builder the builder to be modified.
4037         * @return the build object for chaining.
4038         */
4039        public Builder extend(Builder builder);
4040    }
4041
4042    /**
4043     * Helper class to add wearable extensions to notifications.
4044     * <p class="note"> See
4045     * <a href="{@docRoot}wear/notifications/creating.html">Creating Notifications
4046     * for Android Wear</a> for more information on how to use this class.
4047     * <p>
4048     * To create a notification with wearable extensions:
4049     * <ol>
4050     *   <li>Create a {@link android.app.Notification.Builder}, setting any desired
4051     *   properties.
4052     *   <li>Create a {@link android.app.Notification.WearableExtender}.
4053     *   <li>Set wearable-specific properties using the
4054     *   {@code add} and {@code set} methods of {@link android.app.Notification.WearableExtender}.
4055     *   <li>Call {@link android.app.Notification.Builder#extend} to apply the extensions to a
4056     *   notification.
4057     *   <li>Post the notification to the notification system with the
4058     *   {@code NotificationManager.notify(...)} methods.
4059     * </ol>
4060     *
4061     * <pre class="prettyprint">
4062     * Notification notif = new Notification.Builder(mContext)
4063     *         .setContentTitle(&quot;New mail from &quot; + sender.toString())
4064     *         .setContentText(subject)
4065     *         .setSmallIcon(R.drawable.new_mail)
4066     *         .extend(new Notification.WearableExtender()
4067     *                 .setContentIcon(R.drawable.new_mail))
4068     *         .build();
4069     * NotificationManager notificationManger =
4070     *         (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
4071     * notificationManger.notify(0, notif);</pre>
4072     *
4073     * <p>Wearable extensions can be accessed on an existing notification by using the
4074     * {@code WearableExtender(Notification)} constructor,
4075     * and then using the {@code get} methods to access values.
4076     *
4077     * <pre class="prettyprint">
4078     * Notification.WearableExtender wearableExtender = new Notification.WearableExtender(
4079     *         notification);
4080     * List&lt;Notification&gt; pages = wearableExtender.getPages();</pre>
4081     */
4082    public static final class WearableExtender implements Extender {
4083        /**
4084         * Sentinel value for an action index that is unset.
4085         */
4086        public static final int UNSET_ACTION_INDEX = -1;
4087
4088        /**
4089         * Size value for use with {@link #setCustomSizePreset} to show this notification with
4090         * default sizing.
4091         * <p>For custom display notifications created using {@link #setDisplayIntent},
4092         * the default is {@link #SIZE_LARGE}. All other notifications size automatically based
4093         * on their content.
4094         */
4095        public static final int SIZE_DEFAULT = 0;
4096
4097        /**
4098         * Size value for use with {@link #setCustomSizePreset} to show this notification
4099         * with an extra small size.
4100         * <p>This value is only applicable for custom display notifications created using
4101         * {@link #setDisplayIntent}.
4102         */
4103        public static final int SIZE_XSMALL = 1;
4104
4105        /**
4106         * Size value for use with {@link #setCustomSizePreset} to show this notification
4107         * with a small size.
4108         * <p>This value is only applicable for custom display notifications created using
4109         * {@link #setDisplayIntent}.
4110         */
4111        public static final int SIZE_SMALL = 2;
4112
4113        /**
4114         * Size value for use with {@link #setCustomSizePreset} to show this notification
4115         * with a medium size.
4116         * <p>This value is only applicable for custom display notifications created using
4117         * {@link #setDisplayIntent}.
4118         */
4119        public static final int SIZE_MEDIUM = 3;
4120
4121        /**
4122         * Size value for use with {@link #setCustomSizePreset} to show this notification
4123         * with a large size.
4124         * <p>This value is only applicable for custom display notifications created using
4125         * {@link #setDisplayIntent}.
4126         */
4127        public static final int SIZE_LARGE = 4;
4128
4129        /**
4130         * Size value for use with {@link #setCustomSizePreset} to show this notification
4131         * full screen.
4132         * <p>This value is only applicable for custom display notifications created using
4133         * {@link #setDisplayIntent}.
4134         */
4135        public static final int SIZE_FULL_SCREEN = 5;
4136
4137        /** Notification extra which contains wearable extensions */
4138        private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS";
4139
4140        // Keys within EXTRA_WEARABLE_OPTIONS for wearable options.
4141        private static final String KEY_ACTIONS = "actions";
4142        private static final String KEY_FLAGS = "flags";
4143        private static final String KEY_DISPLAY_INTENT = "displayIntent";
4144        private static final String KEY_PAGES = "pages";
4145        private static final String KEY_BACKGROUND = "background";
4146        private static final String KEY_CONTENT_ICON = "contentIcon";
4147        private static final String KEY_CONTENT_ICON_GRAVITY = "contentIconGravity";
4148        private static final String KEY_CONTENT_ACTION_INDEX = "contentActionIndex";
4149        private static final String KEY_CUSTOM_SIZE_PRESET = "customSizePreset";
4150        private static final String KEY_CUSTOM_CONTENT_HEIGHT = "customContentHeight";
4151        private static final String KEY_GRAVITY = "gravity";
4152
4153        // Flags bitwise-ored to mFlags
4154        private static final int FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE = 0x1;
4155        private static final int FLAG_HINT_HIDE_ICON = 1 << 1;
4156        private static final int FLAG_HINT_SHOW_BACKGROUND_ONLY = 1 << 2;
4157        private static final int FLAG_START_SCROLL_BOTTOM = 1 << 3;
4158
4159        // Default value for flags integer
4160        private static final int DEFAULT_FLAGS = FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE;
4161
4162        private static final int DEFAULT_CONTENT_ICON_GRAVITY = Gravity.END;
4163        private static final int DEFAULT_GRAVITY = Gravity.BOTTOM;
4164
4165        private ArrayList<Action> mActions = new ArrayList<Action>();
4166        private int mFlags = DEFAULT_FLAGS;
4167        private PendingIntent mDisplayIntent;
4168        private ArrayList<Notification> mPages = new ArrayList<Notification>();
4169        private Bitmap mBackground;
4170        private int mContentIcon;
4171        private int mContentIconGravity = DEFAULT_CONTENT_ICON_GRAVITY;
4172        private int mContentActionIndex = UNSET_ACTION_INDEX;
4173        private int mCustomSizePreset = SIZE_DEFAULT;
4174        private int mCustomContentHeight;
4175        private int mGravity = DEFAULT_GRAVITY;
4176
4177        /**
4178         * Create a {@link android.app.Notification.WearableExtender} with default
4179         * options.
4180         */
4181        public WearableExtender() {
4182        }
4183
4184        public WearableExtender(Notification notif) {
4185            Bundle wearableBundle = notif.extras.getBundle(EXTRA_WEARABLE_EXTENSIONS);
4186            if (wearableBundle != null) {
4187                List<Action> actions = wearableBundle.getParcelableArrayList(KEY_ACTIONS);
4188                if (actions != null) {
4189                    mActions.addAll(actions);
4190                }
4191
4192                mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS);
4193                mDisplayIntent = wearableBundle.getParcelable(KEY_DISPLAY_INTENT);
4194
4195                Notification[] pages = getNotificationArrayFromBundle(
4196                        wearableBundle, KEY_PAGES);
4197                if (pages != null) {
4198                    Collections.addAll(mPages, pages);
4199                }
4200
4201                mBackground = wearableBundle.getParcelable(KEY_BACKGROUND);
4202                mContentIcon = wearableBundle.getInt(KEY_CONTENT_ICON);
4203                mContentIconGravity = wearableBundle.getInt(KEY_CONTENT_ICON_GRAVITY,
4204                        DEFAULT_CONTENT_ICON_GRAVITY);
4205                mContentActionIndex = wearableBundle.getInt(KEY_CONTENT_ACTION_INDEX,
4206                        UNSET_ACTION_INDEX);
4207                mCustomSizePreset = wearableBundle.getInt(KEY_CUSTOM_SIZE_PRESET,
4208                        SIZE_DEFAULT);
4209                mCustomContentHeight = wearableBundle.getInt(KEY_CUSTOM_CONTENT_HEIGHT);
4210                mGravity = wearableBundle.getInt(KEY_GRAVITY, DEFAULT_GRAVITY);
4211            }
4212        }
4213
4214        /**
4215         * Apply wearable extensions to a notification that is being built. This is typically
4216         * called by the {@link android.app.Notification.Builder#extend} method of
4217         * {@link android.app.Notification.Builder}.
4218         */
4219        @Override
4220        public Notification.Builder extend(Notification.Builder builder) {
4221            Bundle wearableBundle = new Bundle();
4222
4223            if (!mActions.isEmpty()) {
4224                wearableBundle.putParcelableArrayList(KEY_ACTIONS, mActions);
4225            }
4226            if (mFlags != DEFAULT_FLAGS) {
4227                wearableBundle.putInt(KEY_FLAGS, mFlags);
4228            }
4229            if (mDisplayIntent != null) {
4230                wearableBundle.putParcelable(KEY_DISPLAY_INTENT, mDisplayIntent);
4231            }
4232            if (!mPages.isEmpty()) {
4233                wearableBundle.putParcelableArray(KEY_PAGES, mPages.toArray(
4234                        new Notification[mPages.size()]));
4235            }
4236            if (mBackground != null) {
4237                wearableBundle.putParcelable(KEY_BACKGROUND, mBackground);
4238            }
4239            if (mContentIcon != 0) {
4240                wearableBundle.putInt(KEY_CONTENT_ICON, mContentIcon);
4241            }
4242            if (mContentIconGravity != DEFAULT_CONTENT_ICON_GRAVITY) {
4243                wearableBundle.putInt(KEY_CONTENT_ICON_GRAVITY, mContentIconGravity);
4244            }
4245            if (mContentActionIndex != UNSET_ACTION_INDEX) {
4246                wearableBundle.putInt(KEY_CONTENT_ACTION_INDEX,
4247                        mContentActionIndex);
4248            }
4249            if (mCustomSizePreset != SIZE_DEFAULT) {
4250                wearableBundle.putInt(KEY_CUSTOM_SIZE_PRESET, mCustomSizePreset);
4251            }
4252            if (mCustomContentHeight != 0) {
4253                wearableBundle.putInt(KEY_CUSTOM_CONTENT_HEIGHT, mCustomContentHeight);
4254            }
4255            if (mGravity != DEFAULT_GRAVITY) {
4256                wearableBundle.putInt(KEY_GRAVITY, mGravity);
4257            }
4258
4259            builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle);
4260            return builder;
4261        }
4262
4263        @Override
4264        public WearableExtender clone() {
4265            WearableExtender that = new WearableExtender();
4266            that.mActions = new ArrayList<Action>(this.mActions);
4267            that.mFlags = this.mFlags;
4268            that.mDisplayIntent = this.mDisplayIntent;
4269            that.mPages = new ArrayList<Notification>(this.mPages);
4270            that.mBackground = this.mBackground;
4271            that.mContentIcon = this.mContentIcon;
4272            that.mContentIconGravity = this.mContentIconGravity;
4273            that.mContentActionIndex = this.mContentActionIndex;
4274            that.mCustomSizePreset = this.mCustomSizePreset;
4275            that.mCustomContentHeight = this.mCustomContentHeight;
4276            that.mGravity = this.mGravity;
4277            return that;
4278        }
4279
4280        /**
4281         * Add a wearable action to this notification.
4282         *
4283         * <p>When wearable actions are added using this method, the set of actions that
4284         * show on a wearable device splits from devices that only show actions added
4285         * using {@link android.app.Notification.Builder#addAction}. This allows for customization
4286         * of which actions display on different devices.
4287         *
4288         * @param action the action to add to this notification
4289         * @return this object for method chaining
4290         * @see android.app.Notification.Action
4291         */
4292        public WearableExtender addAction(Action action) {
4293            mActions.add(action);
4294            return this;
4295        }
4296
4297        /**
4298         * Adds wearable actions to this notification.
4299         *
4300         * <p>When wearable actions are added using this method, the set of actions that
4301         * show on a wearable device splits from devices that only show actions added
4302         * using {@link android.app.Notification.Builder#addAction}. This allows for customization
4303         * of which actions display on different devices.
4304         *
4305         * @param actions the actions to add to this notification
4306         * @return this object for method chaining
4307         * @see android.app.Notification.Action
4308         */
4309        public WearableExtender addActions(List<Action> actions) {
4310            mActions.addAll(actions);
4311            return this;
4312        }
4313
4314        /**
4315         * Clear all wearable actions present on this builder.
4316         * @return this object for method chaining.
4317         * @see #addAction
4318         */
4319        public WearableExtender clearActions() {
4320            mActions.clear();
4321            return this;
4322        }
4323
4324        /**
4325         * Get the wearable actions present on this notification.
4326         */
4327        public List<Action> getActions() {
4328            return mActions;
4329        }
4330
4331        /**
4332         * Set an intent to launch inside of an activity view when displaying
4333         * this notification. The {@link PendingIntent} provided should be for an activity.
4334         *
4335         * <pre class="prettyprint">
4336         * Intent displayIntent = new Intent(context, MyDisplayActivity.class);
4337         * PendingIntent displayPendingIntent = PendingIntent.getActivity(context,
4338         *         0, displayIntent, PendingIntent.FLAG_UPDATE_CURRENT);
4339         * Notification notif = new Notification.Builder(context)
4340         *         .extend(new Notification.WearableExtender()
4341         *                 .setDisplayIntent(displayPendingIntent)
4342         *                 .setCustomSizePreset(Notification.WearableExtender.SIZE_MEDIUM))
4343         *         .build();</pre>
4344         *
4345         * <p>The activity to launch needs to allow embedding, must be exported, and
4346         * should have an empty task affinity. It is also recommended to use the device
4347         * default light theme.
4348         *
4349         * <p>Example AndroidManifest.xml entry:
4350         * <pre class="prettyprint">
4351         * &lt;activity android:name=&quot;com.example.MyDisplayActivity&quot;
4352         *     android:exported=&quot;true&quot;
4353         *     android:allowEmbedded=&quot;true&quot;
4354         *     android:taskAffinity=&quot;&quot;
4355         *     android:theme=&quot;@android:style/Theme.DeviceDefault.Light&quot; /&gt;</pre>
4356         *
4357         * @param intent the {@link PendingIntent} for an activity
4358         * @return this object for method chaining
4359         * @see android.app.Notification.WearableExtender#getDisplayIntent
4360         */
4361        public WearableExtender setDisplayIntent(PendingIntent intent) {
4362            mDisplayIntent = intent;
4363            return this;
4364        }
4365
4366        /**
4367         * Get the intent to launch inside of an activity view when displaying this
4368         * notification. This {@code PendingIntent} should be for an activity.
4369         */
4370        public PendingIntent getDisplayIntent() {
4371            return mDisplayIntent;
4372        }
4373
4374        /**
4375         * Add an additional page of content to display with this notification. The current
4376         * notification forms the first page, and pages added using this function form
4377         * subsequent pages. This field can be used to separate a notification into multiple
4378         * sections.
4379         *
4380         * @param page the notification to add as another page
4381         * @return this object for method chaining
4382         * @see android.app.Notification.WearableExtender#getPages
4383         */
4384        public WearableExtender addPage(Notification page) {
4385            mPages.add(page);
4386            return this;
4387        }
4388
4389        /**
4390         * Add additional pages of content to display with this notification. The current
4391         * notification forms the first page, and pages added using this function form
4392         * subsequent pages. This field can be used to separate a notification into multiple
4393         * sections.
4394         *
4395         * @param pages a list of notifications
4396         * @return this object for method chaining
4397         * @see android.app.Notification.WearableExtender#getPages
4398         */
4399        public WearableExtender addPages(List<Notification> pages) {
4400            mPages.addAll(pages);
4401            return this;
4402        }
4403
4404        /**
4405         * Clear all additional pages present on this builder.
4406         * @return this object for method chaining.
4407         * @see #addPage
4408         */
4409        public WearableExtender clearPages() {
4410            mPages.clear();
4411            return this;
4412        }
4413
4414        /**
4415         * Get the array of additional pages of content for displaying this notification. The
4416         * current notification forms the first page, and elements within this array form
4417         * subsequent pages. This field can be used to separate a notification into multiple
4418         * sections.
4419         * @return the pages for this notification
4420         */
4421        public List<Notification> getPages() {
4422            return mPages;
4423        }
4424
4425        /**
4426         * Set a background image to be displayed behind the notification content.
4427         * Contrary to the {@link android.app.Notification.BigPictureStyle}, this background
4428         * will work with any notification style.
4429         *
4430         * @param background the background bitmap
4431         * @return this object for method chaining
4432         * @see android.app.Notification.WearableExtender#getBackground
4433         */
4434        public WearableExtender setBackground(Bitmap background) {
4435            mBackground = background;
4436            return this;
4437        }
4438
4439        /**
4440         * Get a background image to be displayed behind the notification content.
4441         * Contrary to the {@link android.app.Notification.BigPictureStyle}, this background
4442         * will work with any notification style.
4443         *
4444         * @return the background image
4445         * @see android.app.Notification.WearableExtender#setBackground
4446         */
4447        public Bitmap getBackground() {
4448            return mBackground;
4449        }
4450
4451        /**
4452         * Set an icon that goes with the content of this notification.
4453         */
4454        public WearableExtender setContentIcon(int icon) {
4455            mContentIcon = icon;
4456            return this;
4457        }
4458
4459        /**
4460         * Get an icon that goes with the content of this notification.
4461         */
4462        public int getContentIcon() {
4463            return mContentIcon;
4464        }
4465
4466        /**
4467         * Set the gravity that the content icon should have within the notification display.
4468         * Supported values include {@link android.view.Gravity#START} and
4469         * {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}.
4470         * @see #setContentIcon
4471         */
4472        public WearableExtender setContentIconGravity(int contentIconGravity) {
4473            mContentIconGravity = contentIconGravity;
4474            return this;
4475        }
4476
4477        /**
4478         * Get the gravity that the content icon should have within the notification display.
4479         * Supported values include {@link android.view.Gravity#START} and
4480         * {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}.
4481         * @see #getContentIcon
4482         */
4483        public int getContentIconGravity() {
4484            return mContentIconGravity;
4485        }
4486
4487        /**
4488         * Set an action from this notification's actions to be clickable with the content of
4489         * this notification. This action will no longer display separately from the
4490         * notification's content.
4491         *
4492         * <p>For notifications with multiple pages, child pages can also have content actions
4493         * set, although the list of available actions comes from the main notification and not
4494         * from the child page's notification.
4495         *
4496         * @param actionIndex The index of the action to hoist onto the current notification page.
4497         *                    If wearable actions were added to the main notification, this index
4498         *                    will apply to that list, otherwise it will apply to the regular
4499         *                    actions list.
4500         */
4501        public WearableExtender setContentAction(int actionIndex) {
4502            mContentActionIndex = actionIndex;
4503            return this;
4504        }
4505
4506        /**
4507         * Get the index of the notification action, if any, that was specified as being clickable
4508         * with the content of this notification. This action will no longer display separately
4509         * from the notification's content.
4510         *
4511         * <p>For notifications with multiple pages, child pages can also have content actions
4512         * set, although the list of available actions comes from the main notification and not
4513         * from the child page's notification.
4514         *
4515         * <p>If wearable specific actions were added to the main notification, this index will
4516         * apply to that list, otherwise it will apply to the regular actions list.
4517         *
4518         * @return the action index or {@link #UNSET_ACTION_INDEX} if no action was selected.
4519         */
4520        public int getContentAction() {
4521            return mContentActionIndex;
4522        }
4523
4524        /**
4525         * Set the gravity that this notification should have within the available viewport space.
4526         * Supported values include {@link android.view.Gravity#TOP},
4527         * {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}.
4528         * The default value is {@link android.view.Gravity#BOTTOM}.
4529         */
4530        public WearableExtender setGravity(int gravity) {
4531            mGravity = gravity;
4532            return this;
4533        }
4534
4535        /**
4536         * Get the gravity that this notification should have within the available viewport space.
4537         * Supported values include {@link android.view.Gravity#TOP},
4538         * {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}.
4539         * The default value is {@link android.view.Gravity#BOTTOM}.
4540         */
4541        public int getGravity() {
4542            return mGravity;
4543        }
4544
4545        /**
4546         * Set the custom size preset for the display of this notification out of the available
4547         * presets found in {@link android.app.Notification.WearableExtender}, e.g.
4548         * {@link #SIZE_LARGE}.
4549         * <p>Some custom size presets are only applicable for custom display notifications created
4550         * using {@link android.app.Notification.WearableExtender#setDisplayIntent}. Check the
4551         * documentation for the preset in question. See also
4552         * {@link #setCustomContentHeight} and {@link #getCustomSizePreset}.
4553         */
4554        public WearableExtender setCustomSizePreset(int sizePreset) {
4555            mCustomSizePreset = sizePreset;
4556            return this;
4557        }
4558
4559        /**
4560         * Get the custom size preset for the display of this notification out of the available
4561         * presets found in {@link android.app.Notification.WearableExtender}, e.g.
4562         * {@link #SIZE_LARGE}.
4563         * <p>Some custom size presets are only applicable for custom display notifications created
4564         * using {@link #setDisplayIntent}. Check the documentation for the preset in question.
4565         * See also {@link #setCustomContentHeight} and {@link #setCustomSizePreset}.
4566         */
4567        public int getCustomSizePreset() {
4568            return mCustomSizePreset;
4569        }
4570
4571        /**
4572         * Set the custom height in pixels for the display of this notification's content.
4573         * <p>This option is only available for custom display notifications created
4574         * using {@link android.app.Notification.WearableExtender#setDisplayIntent}. See also
4575         * {@link android.app.Notification.WearableExtender#setCustomSizePreset} and
4576         * {@link #getCustomContentHeight}.
4577         */
4578        public WearableExtender setCustomContentHeight(int height) {
4579            mCustomContentHeight = height;
4580            return this;
4581        }
4582
4583        /**
4584         * Get the custom height in pixels for the display of this notification's content.
4585         * <p>This option is only available for custom display notifications created
4586         * using {@link #setDisplayIntent}. See also {@link #setCustomSizePreset} and
4587         * {@link #setCustomContentHeight}.
4588         */
4589        public int getCustomContentHeight() {
4590            return mCustomContentHeight;
4591        }
4592
4593        /**
4594         * Set whether the scrolling position for the contents of this notification should start
4595         * at the bottom of the contents instead of the top when the contents are too long to
4596         * display within the screen.  Default is false (start scroll at the top).
4597         */
4598        public WearableExtender setStartScrollBottom(boolean startScrollBottom) {
4599            setFlag(FLAG_START_SCROLL_BOTTOM, startScrollBottom);
4600            return this;
4601        }
4602
4603        /**
4604         * Get whether the scrolling position for the contents of this notification should start
4605         * at the bottom of the contents instead of the top when the contents are too long to
4606         * display within the screen. Default is false (start scroll at the top).
4607         */
4608        public boolean getStartScrollBottom() {
4609            return (mFlags & FLAG_START_SCROLL_BOTTOM) != 0;
4610        }
4611
4612        /**
4613         * Set whether the content intent is available when the wearable device is not connected
4614         * to a companion device.  The user can still trigger this intent when the wearable device
4615         * is offline, but a visual hint will indicate that the content intent may not be available.
4616         * Defaults to true.
4617         */
4618        public WearableExtender setContentIntentAvailableOffline(
4619                boolean contentIntentAvailableOffline) {
4620            setFlag(FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE, contentIntentAvailableOffline);
4621            return this;
4622        }
4623
4624        /**
4625         * Get whether the content intent is available when the wearable device is not connected
4626         * to a companion device.  The user can still trigger this intent when the wearable device
4627         * is offline, but a visual hint will indicate that the content intent may not be available.
4628         * Defaults to true.
4629         */
4630        public boolean getContentIntentAvailableOffline() {
4631            return (mFlags & FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE) != 0;
4632        }
4633
4634        /**
4635         * Set a hint that this notification's icon should not be displayed.
4636         * @param hintHideIcon {@code true} to hide the icon, {@code false} otherwise.
4637         * @return this object for method chaining
4638         */
4639        public WearableExtender setHintHideIcon(boolean hintHideIcon) {
4640            setFlag(FLAG_HINT_HIDE_ICON, hintHideIcon);
4641            return this;
4642        }
4643
4644        /**
4645         * Get a hint that this notification's icon should not be displayed.
4646         * @return {@code true} if this icon should not be displayed, false otherwise.
4647         * The default value is {@code false} if this was never set.
4648         */
4649        public boolean getHintHideIcon() {
4650            return (mFlags & FLAG_HINT_HIDE_ICON) != 0;
4651        }
4652
4653        /**
4654         * Set a visual hint that only the background image of this notification should be
4655         * displayed, and other semantic content should be hidden. This hint is only applicable
4656         * to sub-pages added using {@link #addPage}.
4657         */
4658        public WearableExtender setHintShowBackgroundOnly(boolean hintShowBackgroundOnly) {
4659            setFlag(FLAG_HINT_SHOW_BACKGROUND_ONLY, hintShowBackgroundOnly);
4660            return this;
4661        }
4662
4663        /**
4664         * Get a visual hint that only the background image of this notification should be
4665         * displayed, and other semantic content should be hidden. This hint is only applicable
4666         * to sub-pages added using {@link android.app.Notification.WearableExtender#addPage}.
4667         */
4668        public boolean getHintShowBackgroundOnly() {
4669            return (mFlags & FLAG_HINT_SHOW_BACKGROUND_ONLY) != 0;
4670        }
4671
4672        private void setFlag(int mask, boolean value) {
4673            if (value) {
4674                mFlags |= mask;
4675            } else {
4676                mFlags &= ~mask;
4677            }
4678        }
4679    }
4680
4681    /**
4682     * Get an array of Notification objects from a parcelable array bundle field.
4683     * Update the bundle to have a typed array so fetches in the future don't need
4684     * to do an array copy.
4685     */
4686    private static Notification[] getNotificationArrayFromBundle(Bundle bundle, String key) {
4687        Parcelable[] array = bundle.getParcelableArray(key);
4688        if (array instanceof Notification[] || array == null) {
4689            return (Notification[]) array;
4690        }
4691        Notification[] typedArray = Arrays.copyOf(array, array.length,
4692                Notification[].class);
4693        bundle.putParcelableArray(key, typedArray);
4694        return typedArray;
4695    }
4696
4697    private static class BuilderRemoteViews extends RemoteViews {
4698        public BuilderRemoteViews(Parcel parcel) {
4699            super(parcel);
4700        }
4701
4702        public BuilderRemoteViews(String packageName, int userId, int layoutId) {
4703            super(packageName, userId, layoutId);
4704        }
4705
4706        @Override
4707        public BuilderRemoteViews clone() {
4708            Parcel p = Parcel.obtain();
4709            writeToParcel(p, 0);
4710            p.setDataPosition(0);
4711            BuilderRemoteViews brv = new BuilderRemoteViews(p);
4712            p.recycle();
4713            return brv;
4714        }
4715    }
4716}
4717