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