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