Notification.java revision 78f525b6742c78ef3aa7048aa8679a9aea6e6e12
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.ColorInt;
20import android.annotation.DrawableRes;
21import android.annotation.IntDef;
22import android.annotation.SdkConstant;
23import android.annotation.SdkConstant.SdkConstantType;
24import android.annotation.SystemApi;
25import android.content.Context;
26import android.content.Intent;
27import android.content.pm.ApplicationInfo;
28import android.content.pm.PackageManager;
29import android.content.pm.PackageManager.NameNotFoundException;
30import android.content.res.ColorStateList;
31import android.graphics.Bitmap;
32import android.graphics.Canvas;
33import android.graphics.Color;
34import android.graphics.PorterDuff;
35import android.graphics.drawable.Drawable;
36import android.graphics.drawable.Icon;
37import android.media.AudioAttributes;
38import android.media.AudioManager;
39import android.media.session.MediaSession;
40import android.net.Uri;
41import android.os.BadParcelableException;
42import android.os.BaseBundle;
43import android.os.Build;
44import android.os.Bundle;
45import android.os.Parcel;
46import android.os.Parcelable;
47import android.os.SystemClock;
48import android.os.UserHandle;
49import android.text.BidiFormatter;
50import android.text.SpannableStringBuilder;
51import android.text.Spanned;
52import android.text.TextUtils;
53import android.text.style.AbsoluteSizeSpan;
54import android.text.style.CharacterStyle;
55import android.text.style.RelativeSizeSpan;
56import android.text.style.TextAppearanceSpan;
57import android.util.ArraySet;
58import android.util.Log;
59import android.util.SparseArray;
60import android.view.Gravity;
61import android.view.NotificationHeaderView;
62import android.view.View;
63import android.view.ViewGroup;
64import android.widget.ProgressBar;
65import android.widget.RemoteViews;
66
67import com.android.internal.R;
68import com.android.internal.util.ArrayUtils;
69import com.android.internal.util.NotificationColorUtil;
70
71import java.lang.annotation.Retention;
72import java.lang.annotation.RetentionPolicy;
73import java.lang.reflect.Constructor;
74import java.util.ArrayList;
75import java.util.Arrays;
76import java.util.Collection;
77import java.util.Collections;
78import java.util.List;
79import java.util.Set;
80
81/**
82 * A class that represents how a persistent notification is to be presented to
83 * the user using the {@link android.app.NotificationManager}.
84 *
85 * <p>The {@link Notification.Builder Notification.Builder} has been added to make it
86 * easier to construct Notifications.</p>
87 *
88 * <div class="special reference">
89 * <h3>Developer Guides</h3>
90 * <p>For a guide to creating notifications, read the
91 * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a>
92 * developer guide.</p>
93 * </div>
94 */
95public class Notification implements Parcelable
96{
97    private static final String TAG = "Notification";
98
99    /**
100     * An activity that provides a user interface for adjusting notification preferences for its
101     * containing application. Optional but recommended for apps that post
102     * {@link android.app.Notification Notifications}.
103     */
104    @SdkConstant(SdkConstantType.INTENT_CATEGORY)
105    public static final String INTENT_CATEGORY_NOTIFICATION_PREFERENCES
106            = "android.intent.category.NOTIFICATION_PREFERENCES";
107
108    /**
109     * Use all default values (where applicable).
110     */
111    public static final int DEFAULT_ALL = ~0;
112
113    /**
114     * Use the default notification sound. This will ignore any given
115     * {@link #sound}.
116     *
117     * <p>
118     * A notification that is noisy is more likely to be presented as a heads-up notification.
119     * </p>
120     *
121     * @see #defaults
122     */
123
124    public static final int DEFAULT_SOUND = 1;
125
126    /**
127     * Use the default notification vibrate. This will ignore any given
128     * {@link #vibrate}. Using phone vibration requires the
129     * {@link android.Manifest.permission#VIBRATE VIBRATE} permission.
130     *
131     * <p>
132     * A notification that vibrates is more likely to be presented as a heads-up notification.
133     * </p>
134     *
135     * @see #defaults
136     */
137
138    public static final int DEFAULT_VIBRATE = 2;
139
140    /**
141     * Use the default notification lights. This will ignore the
142     * {@link #FLAG_SHOW_LIGHTS} bit, and {@link #ledARGB}, {@link #ledOffMS}, or
143     * {@link #ledOnMS}.
144     *
145     * @see #defaults
146     */
147
148    public static final int DEFAULT_LIGHTS = 4;
149
150    /**
151     * Maximum length of CharSequences accepted by Builder and friends.
152     *
153     * <p>
154     * Avoids spamming the system with overly large strings such as full e-mails.
155     */
156    private static final int MAX_CHARSEQUENCE_LENGTH = 5 * 1024;
157
158    /**
159     * Maximum entries of reply text that are accepted by Builder and friends.
160     */
161    private static final int MAX_REPLY_HISTORY = 5;
162
163    /**
164     * A timestamp related to this notification, in milliseconds since the epoch.
165     *
166     * Default value: {@link System#currentTimeMillis() Now}.
167     *
168     * Choose a timestamp that will be most relevant to the user. For most finite events, this
169     * corresponds to the time the event happened (or will happen, in the case of events that have
170     * yet to occur but about which the user is being informed). Indefinite events should be
171     * timestamped according to when the activity began.
172     *
173     * Some examples:
174     *
175     * <ul>
176     *   <li>Notification of a new chat message should be stamped when the message was received.</li>
177     *   <li>Notification of an ongoing file download (with a progress bar, for example) should be stamped when the download started.</li>
178     *   <li>Notification of a completed file download should be stamped when the download finished.</li>
179     *   <li>Notification of an upcoming meeting should be stamped with the time the meeting will begin (that is, in the future).</li>
180     *   <li>Notification of an ongoing stopwatch (increasing timer) should be stamped with the watch's start time.
181     *   <li>Notification of an ongoing countdown timer should be stamped with the timer's end time.
182     * </ul>
183     *
184     * For apps targeting {@link android.os.Build.VERSION_CODES#N} and above, this time is not shown
185     * anymore by default and must be opted into by using
186     * {@link android.app.Notification.Builder#setShowWhen(boolean)}
187     */
188    public long when;
189
190    /**
191     * The creation time of the notification
192     */
193    private long creationTime;
194
195    /**
196     * The resource id of a drawable to use as the icon in the status bar.
197     *
198     * @deprecated Use {@link Builder#setSmallIcon(Icon)} instead.
199     */
200    @Deprecated
201    @DrawableRes
202    public int icon;
203
204    /**
205     * If the icon in the status bar is to have more than one level, you can set this.  Otherwise,
206     * leave it at its default value of 0.
207     *
208     * @see android.widget.ImageView#setImageLevel
209     * @see android.graphics.drawable.Drawable#setLevel
210     */
211    public int iconLevel;
212
213    /**
214     * The number of events that this notification represents. For example, in a new mail
215     * notification, this could be the number of unread messages.
216     *
217     * The system may or may not use this field to modify the appearance of the notification. For
218     * example, before {@link android.os.Build.VERSION_CODES#HONEYCOMB}, this number was
219     * superimposed over the icon in the status bar. Starting with
220     * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, the template used by
221     * {@link Notification.Builder} has displayed the number in the expanded notification view.
222     *
223     * If the number is 0 or negative, it is never shown.
224     *
225     * @deprecated this number is not shown anymore
226     */
227    public int number;
228
229    /**
230     * The intent to execute when the expanded status entry is clicked.  If
231     * this is an activity, it must include the
232     * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires
233     * that you take care of task management as described in the
234     * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back
235     * Stack</a> document.  In particular, make sure to read the notification section
236     * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html#HandlingNotifications">Handling
237     * Notifications</a> for the correct ways to launch an application from a
238     * notification.
239     */
240    public PendingIntent contentIntent;
241
242    /**
243     * The intent to execute when the notification is explicitly dismissed by the user, either with
244     * the "Clear All" button or by swiping it away individually.
245     *
246     * This probably shouldn't be launching an activity since several of those will be sent
247     * at the same time.
248     */
249    public PendingIntent deleteIntent;
250
251    /**
252     * An intent to launch instead of posting the notification to the status bar.
253     *
254     * <p>
255     * The system UI may choose to display a heads-up notification, instead of
256     * launching this intent, while the user is using the device.
257     * </p>
258     *
259     * @see Notification.Builder#setFullScreenIntent
260     */
261    public PendingIntent fullScreenIntent;
262
263    /**
264     * Text that summarizes this notification for accessibility services.
265     *
266     * As of the L release, this text is no longer shown on screen, but it is still useful to
267     * accessibility services (where it serves as an audible announcement of the notification's
268     * appearance).
269     *
270     * @see #tickerView
271     */
272    public CharSequence tickerText;
273
274    /**
275     * Formerly, a view showing the {@link #tickerText}.
276     *
277     * No longer displayed in the status bar as of API 21.
278     */
279    @Deprecated
280    public RemoteViews tickerView;
281
282    /**
283     * The view that will represent this notification in the notification list (which is pulled
284     * down from the status bar).
285     *
286     * As of N, this field may be null. The notification view is determined by the inputs
287     * to {@link Notification.Builder}; a custom RemoteViews can optionally be
288     * supplied with {@link Notification.Builder#setCustomContentView(RemoteViews)}.
289     */
290    @Deprecated
291    public RemoteViews contentView;
292
293    /**
294     * A large-format version of {@link #contentView}, giving the Notification an
295     * opportunity to show more detail. The system UI may choose to show this
296     * instead of the normal content view at its discretion.
297     *
298     * As of N, this field may be null. The expanded notification view is determined by the
299     * inputs to {@link Notification.Builder}; a custom RemoteViews can optionally be
300     * supplied with {@link Notification.Builder#setCustomBigContentView(RemoteViews)}.
301     */
302    @Deprecated
303    public RemoteViews bigContentView;
304
305
306    /**
307     * A medium-format version of {@link #contentView}, providing the Notification an
308     * opportunity to add action buttons to contentView. At its discretion, the system UI may
309     * choose to show this as a heads-up notification, which will pop up so the user can see
310     * it without leaving their current activity.
311     *
312     * As of N, this field may be null. The heads-up notification view is determined by the
313     * inputs to {@link Notification.Builder}; a custom RemoteViews can optionally be
314     * supplied with {@link Notification.Builder#setCustomHeadsUpContentView(RemoteViews)}.
315     */
316    @Deprecated
317    public RemoteViews headsUpContentView;
318
319    /**
320     * A large bitmap to be shown in the notification content area.
321     *
322     * @deprecated Use {@link Builder#setLargeIcon(Icon)} instead.
323     */
324    @Deprecated
325    public Bitmap largeIcon;
326
327    /**
328     * The sound to play.
329     *
330     * <p>
331     * A notification that is noisy is more likely to be presented as a heads-up notification.
332     * </p>
333     *
334     * <p>
335     * To play the default notification sound, see {@link #defaults}.
336     * </p>
337     */
338    public Uri sound;
339
340    /**
341     * Use this constant as the value for audioStreamType to request that
342     * the default stream type for notifications be used.  Currently the
343     * default stream type is {@link AudioManager#STREAM_NOTIFICATION}.
344     *
345     * @deprecated Use {@link #audioAttributes} instead.
346     */
347    @Deprecated
348    public static final int STREAM_DEFAULT = -1;
349
350    /**
351     * The audio stream type to use when playing the sound.
352     * Should be one of the STREAM_ constants from
353     * {@link android.media.AudioManager}.
354     *
355     * @deprecated Use {@link #audioAttributes} instead.
356     */
357    @Deprecated
358    public int audioStreamType = STREAM_DEFAULT;
359
360    /**
361     * The default value of {@link #audioAttributes}.
362     */
363    public static final AudioAttributes AUDIO_ATTRIBUTES_DEFAULT = new AudioAttributes.Builder()
364            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
365            .setUsage(AudioAttributes.USAGE_NOTIFICATION)
366            .build();
367
368    /**
369     * The {@link AudioAttributes audio attributes} to use when playing the sound.
370     */
371    public AudioAttributes audioAttributes = AUDIO_ATTRIBUTES_DEFAULT;
372
373    /**
374     * The pattern with which to vibrate.
375     *
376     * <p>
377     * To vibrate the default pattern, see {@link #defaults}.
378     * </p>
379     *
380     * <p>
381     * A notification that vibrates is more likely to be presented as a heads-up notification.
382     * </p>
383     *
384     * @see android.os.Vibrator#vibrate(long[],int)
385     */
386    public long[] vibrate;
387
388    /**
389     * The color of the led.  The hardware will do its best approximation.
390     *
391     * @see #FLAG_SHOW_LIGHTS
392     * @see #flags
393     */
394    @ColorInt
395    public int ledARGB;
396
397    /**
398     * The number of milliseconds for the LED to be on while it's flashing.
399     * The hardware will do its best approximation.
400     *
401     * @see #FLAG_SHOW_LIGHTS
402     * @see #flags
403     */
404    public int ledOnMS;
405
406    /**
407     * The number of milliseconds for the LED to be off while it's flashing.
408     * The hardware will do its best approximation.
409     *
410     * @see #FLAG_SHOW_LIGHTS
411     * @see #flags
412     */
413    public int ledOffMS;
414
415    /**
416     * Specifies which values should be taken from the defaults.
417     * <p>
418     * To set, OR the desired from {@link #DEFAULT_SOUND},
419     * {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}. For all default
420     * values, use {@link #DEFAULT_ALL}.
421     * </p>
422     */
423    public int defaults;
424
425    /**
426     * Bit to be bitwise-ored into the {@link #flags} field that should be
427     * set if you want the LED on for this notification.
428     * <ul>
429     * <li>To turn the LED off, pass 0 in the alpha channel for colorARGB
430     *      or 0 for both ledOnMS and ledOffMS.</li>
431     * <li>To turn the LED on, pass 1 for ledOnMS and 0 for ledOffMS.</li>
432     * <li>To flash the LED, pass the number of milliseconds that it should
433     *      be on and off to ledOnMS and ledOffMS.</li>
434     * </ul>
435     * <p>
436     * Since hardware varies, you are not guaranteed that any of the values
437     * you pass are honored exactly.  Use the system defaults (TODO) if possible
438     * because they will be set to values that work on any given hardware.
439     * <p>
440     * The alpha channel must be set for forward compatibility.
441     *
442     */
443    public static final int FLAG_SHOW_LIGHTS        = 0x00000001;
444
445    /**
446     * Bit to be bitwise-ored into the {@link #flags} field that should be
447     * set if this notification is in reference to something that is ongoing,
448     * like a phone call.  It should not be set if this notification is in
449     * reference to something that happened at a particular point in time,
450     * like a missed phone call.
451     */
452    public static final int FLAG_ONGOING_EVENT      = 0x00000002;
453
454    /**
455     * Bit to be bitwise-ored into the {@link #flags} field that if set,
456     * the audio will be repeated until the notification is
457     * cancelled or the notification window is opened.
458     */
459    public static final int FLAG_INSISTENT          = 0x00000004;
460
461    /**
462     * Bit to be bitwise-ored into the {@link #flags} field that should be
463     * set if you would only like the sound, vibrate and ticker to be played
464     * if the notification was not already showing.
465     */
466    public static final int FLAG_ONLY_ALERT_ONCE    = 0x00000008;
467
468    /**
469     * Bit to be bitwise-ored into the {@link #flags} field that should be
470     * set if the notification should be canceled when it is clicked by the
471     * user.
472     */
473    public static final int FLAG_AUTO_CANCEL        = 0x00000010;
474
475    /**
476     * Bit to be bitwise-ored into the {@link #flags} field that should be
477     * set if the notification should not be canceled when the user clicks
478     * the Clear all button.
479     */
480    public static final int FLAG_NO_CLEAR           = 0x00000020;
481
482    /**
483     * Bit to be bitwise-ored into the {@link #flags} field that should be
484     * set if this notification represents a currently running service.  This
485     * will normally be set for you by {@link Service#startForeground}.
486     */
487    public static final int FLAG_FOREGROUND_SERVICE = 0x00000040;
488
489    /**
490     * Obsolete flag indicating high-priority notifications; use the priority field instead.
491     *
492     * @deprecated Use {@link #priority} with a positive value.
493     */
494    public static final int FLAG_HIGH_PRIORITY      = 0x00000080;
495
496    /**
497     * Bit to be bitswise-ored into the {@link #flags} field that should be
498     * set if this notification is relevant to the current device only
499     * and it is not recommended that it bridge to other devices.
500     */
501    public static final int FLAG_LOCAL_ONLY         = 0x00000100;
502
503    /**
504     * Bit to be bitswise-ored into the {@link #flags} field that should be
505     * set if this notification is the group summary for a group of notifications.
506     * Grouped notifications may display in a cluster or stack on devices which
507     * support such rendering. Requires a group key also be set using {@link Builder#setGroup}.
508     */
509    public static final int FLAG_GROUP_SUMMARY      = 0x00000200;
510
511    /**
512     * Bit to be bitswise-ored into the {@link #flags} field that should be
513     * set if this notification is the group summary for an auto-group of notifications.
514     *
515     * @hide
516     */
517    @SystemApi
518    public static final int FLAG_AUTOGROUP_SUMMARY  = 0x00000400;
519
520    public int flags;
521
522    /** @hide */
523    @IntDef({PRIORITY_DEFAULT,PRIORITY_LOW,PRIORITY_MIN,PRIORITY_HIGH,PRIORITY_MAX})
524    @Retention(RetentionPolicy.SOURCE)
525    public @interface Priority {}
526
527    /**
528     * Default notification {@link #priority}. If your application does not prioritize its own
529     * notifications, use this value for all notifications.
530     */
531    public static final int PRIORITY_DEFAULT = 0;
532
533    /**
534     * Lower {@link #priority}, for items that are less important. The UI may choose to show these
535     * items smaller, or at a different position in the list, compared with your app's
536     * {@link #PRIORITY_DEFAULT} items.
537     */
538    public static final int PRIORITY_LOW = -1;
539
540    /**
541     * Lowest {@link #priority}; these items might not be shown to the user except under special
542     * circumstances, such as detailed notification logs.
543     */
544    public static final int PRIORITY_MIN = -2;
545
546    /**
547     * Higher {@link #priority}, for more important notifications or alerts. The UI may choose to
548     * show these items larger, or at a different position in notification lists, compared with
549     * your app's {@link #PRIORITY_DEFAULT} items.
550     */
551    public static final int PRIORITY_HIGH = 1;
552
553    /**
554     * Highest {@link #priority}, for your application's most important items that require the
555     * user's prompt attention or input.
556     */
557    public static final int PRIORITY_MAX = 2;
558
559    /**
560     * Relative priority for this notification.
561     *
562     * Priority is an indication of how much of the user's valuable attention should be consumed by
563     * this notification. Low-priority notifications may be hidden from the user in certain
564     * situations, while the user might be interrupted for a higher-priority notification. The
565     * system will make a determination about how to interpret this priority when presenting
566     * the notification.
567     *
568     * <p>
569     * A notification that is at least {@link #PRIORITY_HIGH} is more likely to be presented
570     * as a heads-up notification.
571     * </p>
572     *
573     */
574    @Priority
575    public int priority;
576
577    /**
578     * Accent color (an ARGB integer like the constants in {@link android.graphics.Color})
579     * to be applied by the standard Style templates when presenting this notification.
580     *
581     * The current template design constructs a colorful header image by overlaying the
582     * {@link #icon} image (stenciled in white) atop a field of this color. Alpha components are
583     * ignored.
584     */
585    @ColorInt
586    public int color = COLOR_DEFAULT;
587
588    /**
589     * Special value of {@link #color} telling the system not to decorate this notification with
590     * any special color but instead use default colors when presenting this notification.
591     */
592    @ColorInt
593    public static final int COLOR_DEFAULT = 0; // AKA Color.TRANSPARENT
594
595    /**
596     * Special value of {@link #color} used as a place holder for an invalid color.
597     */
598    @ColorInt
599    private static final int COLOR_INVALID = 1;
600
601    /**
602     * Sphere of visibility of this notification, which affects how and when the SystemUI reveals
603     * the notification's presence and contents in untrusted situations (namely, on the secure
604     * lockscreen).
605     *
606     * The default level, {@link #VISIBILITY_PRIVATE}, behaves exactly as notifications have always
607     * done on Android: The notification's {@link #icon} and {@link #tickerText} (if available) are
608     * shown in all situations, but the contents are only available if the device is unlocked for
609     * the appropriate user.
610     *
611     * A more permissive policy can be expressed by {@link #VISIBILITY_PUBLIC}; such a notification
612     * can be read even in an "insecure" context (that is, above a secure lockscreen).
613     * To modify the public version of this notification—for example, to redact some portions—see
614     * {@link Builder#setPublicVersion(Notification)}.
615     *
616     * Finally, a notification can be made {@link #VISIBILITY_SECRET}, which will suppress its icon
617     * and ticker until the user has bypassed the lockscreen.
618     */
619    public int visibility;
620
621    /**
622     * Notification visibility: Show this notification in its entirety on all lockscreens.
623     *
624     * {@see #visibility}
625     */
626    public static final int VISIBILITY_PUBLIC = 1;
627
628    /**
629     * Notification visibility: Show this notification on all lockscreens, but conceal sensitive or
630     * private information on secure lockscreens.
631     *
632     * {@see #visibility}
633     */
634    public static final int VISIBILITY_PRIVATE = 0;
635
636    /**
637     * Notification visibility: Do not reveal any part of this notification on a secure lockscreen.
638     *
639     * {@see #visibility}
640     */
641    public static final int VISIBILITY_SECRET = -1;
642
643    /**
644     * Notification category: incoming call (voice or video) or similar synchronous communication request.
645     */
646    public static final String CATEGORY_CALL = "call";
647
648    /**
649     * Notification category: incoming direct message (SMS, instant message, etc.).
650     */
651    public static final String CATEGORY_MESSAGE = "msg";
652
653    /**
654     * Notification category: asynchronous bulk message (email).
655     */
656    public static final String CATEGORY_EMAIL = "email";
657
658    /**
659     * Notification category: calendar event.
660     */
661    public static final String CATEGORY_EVENT = "event";
662
663    /**
664     * Notification category: promotion or advertisement.
665     */
666    public static final String CATEGORY_PROMO = "promo";
667
668    /**
669     * Notification category: alarm or timer.
670     */
671    public static final String CATEGORY_ALARM = "alarm";
672
673    /**
674     * Notification category: progress of a long-running background operation.
675     */
676    public static final String CATEGORY_PROGRESS = "progress";
677
678    /**
679     * Notification category: social network or sharing update.
680     */
681    public static final String CATEGORY_SOCIAL = "social";
682
683    /**
684     * Notification category: error in background operation or authentication status.
685     */
686    public static final String CATEGORY_ERROR = "err";
687
688    /**
689     * Notification category: media transport control for playback.
690     */
691    public static final String CATEGORY_TRANSPORT = "transport";
692
693    /**
694     * Notification category: system or device status update.  Reserved for system use.
695     */
696    public static final String CATEGORY_SYSTEM = "sys";
697
698    /**
699     * Notification category: indication of running background service.
700     */
701    public static final String CATEGORY_SERVICE = "service";
702
703    /**
704     * Notification category: a specific, timely recommendation for a single thing.
705     * For example, a news app might want to recommend a news story it believes the user will
706     * want to read next.
707     */
708    public static final String CATEGORY_RECOMMENDATION = "recommendation";
709
710    /**
711     * Notification category: ongoing information about device or contextual status.
712     */
713    public static final String CATEGORY_STATUS = "status";
714
715    /**
716     * Notification category: user-scheduled reminder.
717     */
718    public static final String CATEGORY_REMINDER = "reminder";
719
720    /**
721     * One of the predefined notification categories (see the <code>CATEGORY_*</code> constants)
722     * that best describes this Notification.  May be used by the system for ranking and filtering.
723     */
724    public String category;
725
726    private String mGroupKey;
727
728    /**
729     * Get the key used to group this notification into a cluster or stack
730     * with other notifications on devices which support such rendering.
731     */
732    public String getGroup() {
733        return mGroupKey;
734    }
735
736    private String mSortKey;
737
738    /**
739     * Get a sort key that orders this notification among other notifications from the
740     * same package. This can be useful if an external sort was already applied and an app
741     * would like to preserve this. Notifications will be sorted lexicographically using this
742     * value, although providing different priorities in addition to providing sort key may
743     * cause this value to be ignored.
744     *
745     * <p>This sort key can also be used to order members of a notification group. See
746     * {@link Builder#setGroup}.
747     *
748     * @see String#compareTo(String)
749     */
750    public String getSortKey() {
751        return mSortKey;
752    }
753
754    /**
755     * Additional semantic data to be carried around with this Notification.
756     * <p>
757     * The extras keys defined here are intended to capture the original inputs to {@link Builder}
758     * APIs, and are intended to be used by
759     * {@link android.service.notification.NotificationListenerService} implementations to extract
760     * detailed information from notification objects.
761     */
762    public Bundle extras = new Bundle();
763
764    /**
765     * All pending intents in the notification as the system needs to be able to access them but
766     * touching the extras bundle in the system process is not safe because the bundle may contain
767     * custom parcelable objects.
768     *
769     * @hide
770     */
771    public ArraySet<PendingIntent> allPendingIntents;
772
773    /**
774     * {@link #extras} key: this is the title of the notification,
775     * as supplied to {@link Builder#setContentTitle(CharSequence)}.
776     */
777    public static final String EXTRA_TITLE = "android.title";
778
779    /**
780     * {@link #extras} key: this is the title of the notification when shown in expanded form,
781     * e.g. as supplied to {@link BigTextStyle#setBigContentTitle(CharSequence)}.
782     */
783    public static final String EXTRA_TITLE_BIG = EXTRA_TITLE + ".big";
784
785    /**
786     * {@link #extras} key: this is the main text payload, as supplied to
787     * {@link Builder#setContentText(CharSequence)}.
788     */
789    public static final String EXTRA_TEXT = "android.text";
790
791    /**
792     * {@link #extras} key: this is a third line of text, as supplied to
793     * {@link Builder#setSubText(CharSequence)}.
794     */
795    public static final String EXTRA_SUB_TEXT = "android.subText";
796
797    /**
798     * {@link #extras} key: this is the remote input history, as supplied to
799     * {@link Builder#setRemoteInputHistory(CharSequence[])}.
800     *
801     * Apps can fill this through {@link Builder#setRemoteInputHistory(CharSequence[])}
802     * with the most recent inputs that have been sent through a {@link RemoteInput} of this
803     * Notification and are expected to clear it once the it is no longer relevant (e.g. for chat
804     * notifications once the other party has responded).
805     *
806     * The extra with this key is of type CharSequence[] and contains the most recent entry at
807     * the 0 index, the second most recent at the 1 index, etc.
808     *
809     * @see Builder#setRemoteInputHistory(CharSequence[])
810     */
811    public static final String EXTRA_REMOTE_INPUT_HISTORY = "android.remoteInputHistory";
812
813    /**
814     * {@link #extras} key: this is a small piece of additional text as supplied to
815     * {@link Builder#setContentInfo(CharSequence)}.
816     */
817    public static final String EXTRA_INFO_TEXT = "android.infoText";
818
819    /**
820     * {@link #extras} key: this is a line of summary information intended to be shown
821     * alongside expanded notifications, as supplied to (e.g.)
822     * {@link BigTextStyle#setSummaryText(CharSequence)}.
823     */
824    public static final String EXTRA_SUMMARY_TEXT = "android.summaryText";
825
826    /**
827     * {@link #extras} key: this is the longer text shown in the big form of a
828     * {@link BigTextStyle} notification, as supplied to
829     * {@link BigTextStyle#bigText(CharSequence)}.
830     */
831    public static final String EXTRA_BIG_TEXT = "android.bigText";
832
833    /**
834     * {@link #extras} key: this is the resource ID of the notification's main small icon, as
835     * supplied to {@link Builder#setSmallIcon(int)}.
836     */
837    public static final String EXTRA_SMALL_ICON = "android.icon";
838
839    /**
840     * {@link #extras} key: this is a bitmap to be used instead of the small icon when showing the
841     * notification payload, as
842     * supplied to {@link Builder#setLargeIcon(android.graphics.Bitmap)}.
843     */
844    public static final String EXTRA_LARGE_ICON = "android.largeIcon";
845
846    /**
847     * {@link #extras} key: this is a bitmap to be used instead of the one from
848     * {@link Builder#setLargeIcon(android.graphics.Bitmap)} when the notification is
849     * shown in its expanded form, as supplied to
850     * {@link BigPictureStyle#bigLargeIcon(android.graphics.Bitmap)}.
851     */
852    public static final String EXTRA_LARGE_ICON_BIG = EXTRA_LARGE_ICON + ".big";
853
854    /**
855     * {@link #extras} key: this is the progress value supplied to
856     * {@link Builder#setProgress(int, int, boolean)}.
857     */
858    public static final String EXTRA_PROGRESS = "android.progress";
859
860    /**
861     * {@link #extras} key: this is the maximum value supplied to
862     * {@link Builder#setProgress(int, int, boolean)}.
863     */
864    public static final String EXTRA_PROGRESS_MAX = "android.progressMax";
865
866    /**
867     * {@link #extras} key: whether the progress bar is indeterminate, supplied to
868     * {@link Builder#setProgress(int, int, boolean)}.
869     */
870    public static final String EXTRA_PROGRESS_INDETERMINATE = "android.progressIndeterminate";
871
872    /**
873     * {@link #extras} key: whether {@link #when} should be shown as a count-up timer (specifically
874     * a {@link android.widget.Chronometer}) instead of a timestamp, as supplied to
875     * {@link Builder#setUsesChronometer(boolean)}.
876     */
877    public static final String EXTRA_SHOW_CHRONOMETER = "android.showChronometer";
878
879    /**
880     * {@link #extras} key: whether the chronometer set on the notification should count down
881     * instead of counting up. Is only relevant if key {@link #EXTRA_SHOW_CHRONOMETER} is present.
882     * This extra is a boolean. The default is false.
883     */
884    public static final String EXTRA_CHRONOMETER_COUNT_DOWN = "android.chronometerCountDown";
885
886    /**
887     * {@link #extras} key: whether {@link #when} should be shown,
888     * as supplied to {@link Builder#setShowWhen(boolean)}.
889     */
890    public static final String EXTRA_SHOW_WHEN = "android.showWhen";
891
892    /**
893     * {@link #extras} key: this is a bitmap to be shown in {@link BigPictureStyle} expanded
894     * notifications, supplied to {@link BigPictureStyle#bigPicture(android.graphics.Bitmap)}.
895     */
896    public static final String EXTRA_PICTURE = "android.picture";
897
898    /**
899     * {@link #extras} key: An array of CharSequences to show in {@link InboxStyle} expanded
900     * notifications, each of which was supplied to {@link InboxStyle#addLine(CharSequence)}.
901     */
902    public static final String EXTRA_TEXT_LINES = "android.textLines";
903
904    /**
905     * {@link #extras} key: A string representing the name of the specific
906     * {@link android.app.Notification.Style} used to create this notification.
907     */
908    public static final String EXTRA_TEMPLATE = "android.template";
909
910    /**
911     * {@link #extras} key: A String array containing the people that this notification relates to,
912     * each of which was supplied to {@link Builder#addPerson(String)}.
913     */
914    public static final String EXTRA_PEOPLE = "android.people";
915
916    /**
917     * Allow certain system-generated notifications to appear before the device is provisioned.
918     * Only available to notifications coming from the android package.
919     * @hide
920     */
921    public static final String EXTRA_ALLOW_DURING_SETUP = "android.allowDuringSetup";
922
923    /**
924     * {@link #extras} key: A
925     * {@link android.content.ContentUris content URI} pointing to an image that can be displayed
926     * in the background when the notification is selected. The URI must point to an image stream
927     * suitable for passing into
928     * {@link android.graphics.BitmapFactory#decodeStream(java.io.InputStream)
929     * BitmapFactory.decodeStream}; all other content types will be ignored. The content provider
930     * URI used for this purpose must require no permissions to read the image data.
931     */
932    public static final String EXTRA_BACKGROUND_IMAGE_URI = "android.backgroundImageUri";
933
934    /**
935     * {@link #extras} key: A
936     * {@link android.media.session.MediaSession.Token} associated with a
937     * {@link android.app.Notification.MediaStyle} notification.
938     */
939    public static final String EXTRA_MEDIA_SESSION = "android.mediaSession";
940
941    /**
942     * {@link #extras} key: the indices of actions to be shown in the compact view,
943     * as supplied to (e.g.) {@link MediaStyle#setShowActionsInCompactView(int...)}.
944     */
945    public static final String EXTRA_COMPACT_ACTIONS = "android.compactActions";
946
947    /**
948     * {@link #extras} key: the username to be displayed for all messages sent by the user including
949     * direct replies
950     * {@link android.app.Notification.MessagingStyle} notification. This extra is a
951     * {@link CharSequence}
952     */
953    public static final String EXTRA_SELF_DISPLAY_NAME = "android.selfDisplayName";
954
955    /**
956     * {@link #extras} key: a {@link CharSequence} to be displayed as the title to a conversation
957     * represented by a {@link android.app.Notification.MessagingStyle}
958     */
959    public static final String EXTRA_CONVERSATION_TITLE = "android.conversationTitle";
960
961    /**
962     * {@link #extras} key: an array of {@link android.app.Notification.MessagingStyle.Message}
963     * bundles provided by a
964     * {@link android.app.Notification.MessagingStyle} notification. This extra is a parcelable
965     * array of bundles.
966     */
967    public static final String EXTRA_MESSAGES = "android.messages";
968
969    /**
970     * {@link #extras} key: the user that built the notification.
971     *
972     * @hide
973     */
974    public static final String EXTRA_ORIGINATING_USERID = "android.originatingUserId";
975
976    /**
977     * @hide
978     */
979    public static final String EXTRA_BUILDER_APPLICATION_INFO = "android.appInfo";
980
981    /**
982     * @hide
983     */
984    public static final String EXTRA_CONTAINS_CUSTOM_VIEW = "android.contains.customView";
985
986    /** @hide */
987    @SystemApi
988    public static final String EXTRA_SUBSTITUTE_APP_NAME = "android.substName";
989
990    private Icon mSmallIcon;
991    private Icon mLargeIcon;
992
993    /**
994     * Structure to encapsulate a named action that can be shown as part of this notification.
995     * It must include an icon, a label, and a {@link PendingIntent} to be fired when the action is
996     * selected by the user.
997     * <p>
998     * Apps should use {@link Notification.Builder#addAction(int, CharSequence, PendingIntent)}
999     * or {@link Notification.Builder#addAction(Notification.Action)}
1000     * to attach actions.
1001     */
1002    public static class Action implements Parcelable {
1003        private final Bundle mExtras;
1004        private Icon mIcon;
1005        private final RemoteInput[] mRemoteInputs;
1006        private boolean mAllowGeneratedReplies = false;
1007
1008        /**
1009         * Small icon representing the action.
1010         *
1011         * @deprecated Use {@link Action#getIcon()} instead.
1012         */
1013        @Deprecated
1014        public int icon;
1015
1016        /**
1017         * Title of the action.
1018         */
1019        public CharSequence title;
1020
1021        /**
1022         * Intent to send when the user invokes this action. May be null, in which case the action
1023         * may be rendered in a disabled presentation by the system UI.
1024         */
1025        public PendingIntent actionIntent;
1026
1027        private Action(Parcel in) {
1028            if (in.readInt() != 0) {
1029                mIcon = Icon.CREATOR.createFromParcel(in);
1030                if (mIcon.getType() == Icon.TYPE_RESOURCE) {
1031                    icon = mIcon.getResId();
1032                }
1033            }
1034            title = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
1035            if (in.readInt() == 1) {
1036                actionIntent = PendingIntent.CREATOR.createFromParcel(in);
1037            }
1038            mExtras = Bundle.setDefusable(in.readBundle(), true);
1039            mRemoteInputs = in.createTypedArray(RemoteInput.CREATOR);
1040            mAllowGeneratedReplies = in.readInt() == 1;
1041        }
1042
1043        /**
1044         * @deprecated Use {@link android.app.Notification.Action.Builder}.
1045         */
1046        @Deprecated
1047        public Action(int icon, CharSequence title, PendingIntent intent) {
1048            this(Icon.createWithResource("", icon), title, intent, new Bundle(), null, false);
1049        }
1050
1051        private Action(Icon icon, CharSequence title, PendingIntent intent, Bundle extras,
1052                RemoteInput[] remoteInputs, boolean allowGeneratedReplies) {
1053            this.mIcon = icon;
1054            if (icon != null && icon.getType() == Icon.TYPE_RESOURCE) {
1055                this.icon = icon.getResId();
1056            }
1057            this.title = title;
1058            this.actionIntent = intent;
1059            this.mExtras = extras != null ? extras : new Bundle();
1060            this.mRemoteInputs = remoteInputs;
1061            this.mAllowGeneratedReplies = allowGeneratedReplies;
1062        }
1063
1064        /**
1065         * Return an icon representing the action.
1066         */
1067        public Icon getIcon() {
1068            if (mIcon == null && icon != 0) {
1069                // you snuck an icon in here without using the builder; let's try to keep it
1070                mIcon = Icon.createWithResource("", icon);
1071            }
1072            return mIcon;
1073        }
1074
1075        /**
1076         * Get additional metadata carried around with this Action.
1077         */
1078        public Bundle getExtras() {
1079            return mExtras;
1080        }
1081
1082        /**
1083         * Return whether the platform should automatically generate possible replies for this
1084         * {@link Action}
1085         */
1086        public boolean getAllowGeneratedReplies() {
1087            return mAllowGeneratedReplies;
1088        }
1089
1090        /**
1091         * Get the list of inputs to be collected from the user when this action is sent.
1092         * May return null if no remote inputs were added.
1093         */
1094        public RemoteInput[] getRemoteInputs() {
1095            return mRemoteInputs;
1096        }
1097
1098        /**
1099         * Builder class for {@link Action} objects.
1100         */
1101        public static final class Builder {
1102            private final Icon mIcon;
1103            private final CharSequence mTitle;
1104            private final PendingIntent mIntent;
1105            private boolean mAllowGeneratedReplies;
1106            private final Bundle mExtras;
1107            private ArrayList<RemoteInput> mRemoteInputs;
1108
1109            /**
1110             * Construct a new builder for {@link Action} object.
1111             * @param icon icon to show for this action
1112             * @param title the title of the action
1113             * @param intent the {@link PendingIntent} to fire when users trigger this action
1114             */
1115            @Deprecated
1116            public Builder(int icon, CharSequence title, PendingIntent intent) {
1117                this(Icon.createWithResource("", icon), title, intent, new Bundle(), null);
1118            }
1119
1120            /**
1121             * Construct a new builder for {@link Action} object.
1122             * @param icon icon to show for this action
1123             * @param title the title of the action
1124             * @param intent the {@link PendingIntent} to fire when users trigger this action
1125             */
1126            public Builder(Icon icon, CharSequence title, PendingIntent intent) {
1127                this(icon, title, intent, new Bundle(), null);
1128            }
1129
1130            /**
1131             * Construct a new builder for {@link Action} object using the fields from an
1132             * {@link Action}.
1133             * @param action the action to read fields from.
1134             */
1135            public Builder(Action action) {
1136                this(action.getIcon(), action.title, action.actionIntent, new Bundle(action.mExtras),
1137                        action.getRemoteInputs());
1138            }
1139
1140            private Builder(Icon icon, CharSequence title, PendingIntent intent, Bundle extras,
1141                    RemoteInput[] remoteInputs) {
1142                mIcon = icon;
1143                mTitle = title;
1144                mIntent = intent;
1145                mExtras = extras;
1146                if (remoteInputs != null) {
1147                    mRemoteInputs = new ArrayList<RemoteInput>(remoteInputs.length);
1148                    Collections.addAll(mRemoteInputs, remoteInputs);
1149                }
1150            }
1151
1152            /**
1153             * Merge additional metadata into this builder.
1154             *
1155             * <p>Values within the Bundle will replace existing extras values in this Builder.
1156             *
1157             * @see Notification.Action#extras
1158             */
1159            public Builder addExtras(Bundle extras) {
1160                if (extras != null) {
1161                    mExtras.putAll(extras);
1162                }
1163                return this;
1164            }
1165
1166            /**
1167             * Get the metadata Bundle used by this Builder.
1168             *
1169             * <p>The returned Bundle is shared with this Builder.
1170             */
1171            public Bundle getExtras() {
1172                return mExtras;
1173            }
1174
1175            /**
1176             * Add an input to be collected from the user when this action is sent.
1177             * Response values can be retrieved from the fired intent by using the
1178             * {@link RemoteInput#getResultsFromIntent} function.
1179             * @param remoteInput a {@link RemoteInput} to add to the action
1180             * @return this object for method chaining
1181             */
1182            public Builder addRemoteInput(RemoteInput remoteInput) {
1183                if (mRemoteInputs == null) {
1184                    mRemoteInputs = new ArrayList<RemoteInput>();
1185                }
1186                mRemoteInputs.add(remoteInput);
1187                return this;
1188            }
1189
1190            /**
1191             * Set whether the platform should automatically generate possible replies to add to
1192             * {@link RemoteInput#getChoices()}. If the {@link Action} doesn't have a
1193             * {@link RemoteInput}, this has no effect.
1194             * @param allowGeneratedReplies {@code true} to allow generated replies, {@code false}
1195             * otherwise
1196             * @return this object for method chaining
1197             * The default value is {@code false}
1198             */
1199            public Builder setAllowGeneratedReplies(boolean allowGeneratedReplies) {
1200                mAllowGeneratedReplies = allowGeneratedReplies;
1201                return this;
1202            }
1203
1204            /**
1205             * Apply an extender to this action builder. Extenders may be used to add
1206             * metadata or change options on this builder.
1207             */
1208            public Builder extend(Extender extender) {
1209                extender.extend(this);
1210                return this;
1211            }
1212
1213            /**
1214             * Combine all of the options that have been set and return a new {@link Action}
1215             * object.
1216             * @return the built action
1217             */
1218            public Action build() {
1219                RemoteInput[] remoteInputs = mRemoteInputs != null
1220                        ? mRemoteInputs.toArray(new RemoteInput[mRemoteInputs.size()]) : null;
1221                return new Action(mIcon, mTitle, mIntent, mExtras, remoteInputs,
1222                        mAllowGeneratedReplies);
1223            }
1224        }
1225
1226        @Override
1227        public Action clone() {
1228            return new Action(
1229                    getIcon(),
1230                    title,
1231                    actionIntent, // safe to alias
1232                    new Bundle(mExtras),
1233                    getRemoteInputs(),
1234                    getAllowGeneratedReplies());
1235        }
1236        @Override
1237        public int describeContents() {
1238            return 0;
1239        }
1240        @Override
1241        public void writeToParcel(Parcel out, int flags) {
1242            final Icon ic = getIcon();
1243            if (ic != null) {
1244                out.writeInt(1);
1245                ic.writeToParcel(out, 0);
1246            } else {
1247                out.writeInt(0);
1248            }
1249            TextUtils.writeToParcel(title, out, flags);
1250            if (actionIntent != null) {
1251                out.writeInt(1);
1252                actionIntent.writeToParcel(out, flags);
1253            } else {
1254                out.writeInt(0);
1255            }
1256            out.writeBundle(mExtras);
1257            out.writeTypedArray(mRemoteInputs, flags);
1258            out.writeInt(mAllowGeneratedReplies ? 1 : 0);
1259        }
1260        public static final Parcelable.Creator<Action> CREATOR =
1261                new Parcelable.Creator<Action>() {
1262            public Action createFromParcel(Parcel in) {
1263                return new Action(in);
1264            }
1265            public Action[] newArray(int size) {
1266                return new Action[size];
1267            }
1268        };
1269
1270        /**
1271         * Extender interface for use with {@link Builder#extend}. Extenders may be used to add
1272         * metadata or change options on an action builder.
1273         */
1274        public interface Extender {
1275            /**
1276             * Apply this extender to a notification action builder.
1277             * @param builder the builder to be modified.
1278             * @return the build object for chaining.
1279             */
1280            public Builder extend(Builder builder);
1281        }
1282
1283        /**
1284         * Wearable extender for notification actions. To add extensions to an action,
1285         * create a new {@link android.app.Notification.Action.WearableExtender} object using
1286         * the {@code WearableExtender()} constructor and apply it to a
1287         * {@link android.app.Notification.Action.Builder} using
1288         * {@link android.app.Notification.Action.Builder#extend}.
1289         *
1290         * <pre class="prettyprint">
1291         * Notification.Action action = new Notification.Action.Builder(
1292         *         R.drawable.archive_all, "Archive all", actionIntent)
1293         *         .extend(new Notification.Action.WearableExtender()
1294         *                 .setAvailableOffline(false))
1295         *         .build();</pre>
1296         */
1297        public static final class WearableExtender implements Extender {
1298            /** Notification action extra which contains wearable extensions */
1299            private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS";
1300
1301            // Keys within EXTRA_WEARABLE_EXTENSIONS for wearable options.
1302            private static final String KEY_FLAGS = "flags";
1303            private static final String KEY_IN_PROGRESS_LABEL = "inProgressLabel";
1304            private static final String KEY_CONFIRM_LABEL = "confirmLabel";
1305            private static final String KEY_CANCEL_LABEL = "cancelLabel";
1306
1307            // Flags bitwise-ored to mFlags
1308            private static final int FLAG_AVAILABLE_OFFLINE = 0x1;
1309            private static final int FLAG_HINT_LAUNCHES_ACTIVITY = 1 << 1;
1310            private static final int FLAG_HINT_DISPLAY_INLINE = 1 << 2;
1311
1312            // Default value for flags integer
1313            private static final int DEFAULT_FLAGS = FLAG_AVAILABLE_OFFLINE;
1314
1315            private int mFlags = DEFAULT_FLAGS;
1316
1317            private CharSequence mInProgressLabel;
1318            private CharSequence mConfirmLabel;
1319            private CharSequence mCancelLabel;
1320
1321            /**
1322             * Create a {@link android.app.Notification.Action.WearableExtender} with default
1323             * options.
1324             */
1325            public WearableExtender() {
1326            }
1327
1328            /**
1329             * Create a {@link android.app.Notification.Action.WearableExtender} by reading
1330             * wearable options present in an existing notification action.
1331             * @param action the notification action to inspect.
1332             */
1333            public WearableExtender(Action action) {
1334                Bundle wearableBundle = action.getExtras().getBundle(EXTRA_WEARABLE_EXTENSIONS);
1335                if (wearableBundle != null) {
1336                    mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS);
1337                    mInProgressLabel = wearableBundle.getCharSequence(KEY_IN_PROGRESS_LABEL);
1338                    mConfirmLabel = wearableBundle.getCharSequence(KEY_CONFIRM_LABEL);
1339                    mCancelLabel = wearableBundle.getCharSequence(KEY_CANCEL_LABEL);
1340                }
1341            }
1342
1343            /**
1344             * Apply wearable extensions to a notification action that is being built. This is
1345             * typically called by the {@link android.app.Notification.Action.Builder#extend}
1346             * method of {@link android.app.Notification.Action.Builder}.
1347             */
1348            @Override
1349            public Action.Builder extend(Action.Builder builder) {
1350                Bundle wearableBundle = new Bundle();
1351
1352                if (mFlags != DEFAULT_FLAGS) {
1353                    wearableBundle.putInt(KEY_FLAGS, mFlags);
1354                }
1355                if (mInProgressLabel != null) {
1356                    wearableBundle.putCharSequence(KEY_IN_PROGRESS_LABEL, mInProgressLabel);
1357                }
1358                if (mConfirmLabel != null) {
1359                    wearableBundle.putCharSequence(KEY_CONFIRM_LABEL, mConfirmLabel);
1360                }
1361                if (mCancelLabel != null) {
1362                    wearableBundle.putCharSequence(KEY_CANCEL_LABEL, mCancelLabel);
1363                }
1364
1365                builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle);
1366                return builder;
1367            }
1368
1369            @Override
1370            public WearableExtender clone() {
1371                WearableExtender that = new WearableExtender();
1372                that.mFlags = this.mFlags;
1373                that.mInProgressLabel = this.mInProgressLabel;
1374                that.mConfirmLabel = this.mConfirmLabel;
1375                that.mCancelLabel = this.mCancelLabel;
1376                return that;
1377            }
1378
1379            /**
1380             * Set whether this action is available when the wearable device is not connected to
1381             * a companion device. The user can still trigger this action when the wearable device is
1382             * offline, but a visual hint will indicate that the action may not be available.
1383             * Defaults to true.
1384             */
1385            public WearableExtender setAvailableOffline(boolean availableOffline) {
1386                setFlag(FLAG_AVAILABLE_OFFLINE, availableOffline);
1387                return this;
1388            }
1389
1390            /**
1391             * Get whether this action is available when the wearable device is not connected to
1392             * a companion device. The user can still trigger this action when the wearable device is
1393             * offline, but a visual hint will indicate that the action may not be available.
1394             * Defaults to true.
1395             */
1396            public boolean isAvailableOffline() {
1397                return (mFlags & FLAG_AVAILABLE_OFFLINE) != 0;
1398            }
1399
1400            private void setFlag(int mask, boolean value) {
1401                if (value) {
1402                    mFlags |= mask;
1403                } else {
1404                    mFlags &= ~mask;
1405                }
1406            }
1407
1408            /**
1409             * Set a label to display while the wearable is preparing to automatically execute the
1410             * action. This is usually a 'ing' verb ending in ellipsis like "Sending..."
1411             *
1412             * @param label the label to display while the action is being prepared to execute
1413             * @return this object for method chaining
1414             */
1415            public WearableExtender setInProgressLabel(CharSequence label) {
1416                mInProgressLabel = label;
1417                return this;
1418            }
1419
1420            /**
1421             * Get the label to display while the wearable is preparing to automatically execute
1422             * the action. This is usually a 'ing' verb ending in ellipsis like "Sending..."
1423             *
1424             * @return the label to display while the action is being prepared to execute
1425             */
1426            public CharSequence getInProgressLabel() {
1427                return mInProgressLabel;
1428            }
1429
1430            /**
1431             * Set a label to display to confirm that the action should be executed.
1432             * This is usually an imperative verb like "Send".
1433             *
1434             * @param label the label to confirm the action should be executed
1435             * @return this object for method chaining
1436             */
1437            public WearableExtender setConfirmLabel(CharSequence label) {
1438                mConfirmLabel = label;
1439                return this;
1440            }
1441
1442            /**
1443             * Get the label to display to confirm that the action should be executed.
1444             * This is usually an imperative verb like "Send".
1445             *
1446             * @return the label to confirm the action should be executed
1447             */
1448            public CharSequence getConfirmLabel() {
1449                return mConfirmLabel;
1450            }
1451
1452            /**
1453             * Set a label to display to cancel the action.
1454             * This is usually an imperative verb, like "Cancel".
1455             *
1456             * @param label the label to display to cancel the action
1457             * @return this object for method chaining
1458             */
1459            public WearableExtender setCancelLabel(CharSequence label) {
1460                mCancelLabel = label;
1461                return this;
1462            }
1463
1464            /**
1465             * Get the label to display to cancel the action.
1466             * This is usually an imperative verb like "Cancel".
1467             *
1468             * @return the label to display to cancel the action
1469             */
1470            public CharSequence getCancelLabel() {
1471                return mCancelLabel;
1472            }
1473
1474            /**
1475             * Set a hint that this Action will launch an {@link Activity} directly, telling the
1476             * platform that it can generate the appropriate transitions.
1477             * @param hintLaunchesActivity {@code true} if the content intent will launch
1478             * an activity and transitions should be generated, false otherwise.
1479             * @return this object for method chaining
1480             */
1481            public WearableExtender setHintLaunchesActivity(
1482                    boolean hintLaunchesActivity) {
1483                setFlag(FLAG_HINT_LAUNCHES_ACTIVITY, hintLaunchesActivity);
1484                return this;
1485            }
1486
1487            /**
1488             * Get a hint that this Action will launch an {@link Activity} directly, telling the
1489             * platform that it can generate the appropriate transitions
1490             * @return {@code true} if the content intent will launch an activity and transitions
1491             * should be generated, false otherwise. The default value is {@code false} if this was
1492             * never set.
1493             */
1494            public boolean getHintLaunchesActivity() {
1495                return (mFlags & FLAG_HINT_LAUNCHES_ACTIVITY) != 0;
1496            }
1497
1498            /**
1499             * Set a hint that this Action should be displayed inline.
1500             *
1501             * @param hintDisplayInline {@code true} if action should be displayed inline, false
1502             *        otherwise
1503             * @return this object for method chaining
1504             */
1505            public WearableExtender setHintDisplayActionInline(
1506                    boolean hintDisplayInline) {
1507                setFlag(FLAG_HINT_DISPLAY_INLINE, hintDisplayInline);
1508                return this;
1509            }
1510
1511            /**
1512             * Get a hint that this Action should be displayed inline.
1513             *
1514             * @return {@code true} if the Action should be displayed inline, {@code false}
1515             *         otherwise. The default value is {@code false} if this was never set.
1516             */
1517            public boolean getHintDisplayActionInline() {
1518                return (mFlags & FLAG_HINT_DISPLAY_INLINE) != 0;
1519            }
1520        }
1521    }
1522
1523    /**
1524     * Array of all {@link Action} structures attached to this notification by
1525     * {@link Builder#addAction(int, CharSequence, PendingIntent)}. Mostly useful for instances of
1526     * {@link android.service.notification.NotificationListenerService} that provide an alternative
1527     * interface for invoking actions.
1528     */
1529    public Action[] actions;
1530
1531    /**
1532     * Replacement version of this notification whose content will be shown
1533     * in an insecure context such as atop a secure keyguard. See {@link #visibility}
1534     * and {@link #VISIBILITY_PUBLIC}.
1535     */
1536    public Notification publicVersion;
1537
1538    /**
1539     * Constructs a Notification object with default values.
1540     * You might want to consider using {@link Builder} instead.
1541     */
1542    public Notification()
1543    {
1544        this.when = System.currentTimeMillis();
1545        this.creationTime = System.currentTimeMillis();
1546        this.priority = PRIORITY_DEFAULT;
1547    }
1548
1549    /**
1550     * @hide
1551     */
1552    public Notification(Context context, int icon, CharSequence tickerText, long when,
1553            CharSequence contentTitle, CharSequence contentText, Intent contentIntent)
1554    {
1555        new Builder(context)
1556                .setWhen(when)
1557                .setSmallIcon(icon)
1558                .setTicker(tickerText)
1559                .setContentTitle(contentTitle)
1560                .setContentText(contentText)
1561                .setContentIntent(PendingIntent.getActivity(context, 0, contentIntent, 0))
1562                .buildInto(this);
1563    }
1564
1565    /**
1566     * Constructs a Notification object with the information needed to
1567     * have a status bar icon without the standard expanded view.
1568     *
1569     * @param icon          The resource id of the icon to put in the status bar.
1570     * @param tickerText    The text that flows by in the status bar when the notification first
1571     *                      activates.
1572     * @param when          The time to show in the time field.  In the System.currentTimeMillis
1573     *                      timebase.
1574     *
1575     * @deprecated Use {@link Builder} instead.
1576     */
1577    @Deprecated
1578    public Notification(int icon, CharSequence tickerText, long when)
1579    {
1580        this.icon = icon;
1581        this.tickerText = tickerText;
1582        this.when = when;
1583        this.creationTime = System.currentTimeMillis();
1584    }
1585
1586    /**
1587     * Unflatten the notification from a parcel.
1588     */
1589    @SuppressWarnings("unchecked")
1590    public Notification(Parcel parcel) {
1591        // IMPORTANT: Add unmarshaling code in readFromParcel as the pending
1592        // intents in extras are always written as the last entry.
1593        readFromParcelImpl(parcel);
1594        // Must be read last!
1595        allPendingIntents = (ArraySet<PendingIntent>) parcel.readArraySet(null);
1596    }
1597
1598    private void readFromParcelImpl(Parcel parcel)
1599    {
1600        int version = parcel.readInt();
1601
1602        when = parcel.readLong();
1603        creationTime = parcel.readLong();
1604        if (parcel.readInt() != 0) {
1605            mSmallIcon = Icon.CREATOR.createFromParcel(parcel);
1606            if (mSmallIcon.getType() == Icon.TYPE_RESOURCE) {
1607                icon = mSmallIcon.getResId();
1608            }
1609        }
1610        number = parcel.readInt();
1611        if (parcel.readInt() != 0) {
1612            contentIntent = PendingIntent.CREATOR.createFromParcel(parcel);
1613        }
1614        if (parcel.readInt() != 0) {
1615            deleteIntent = PendingIntent.CREATOR.createFromParcel(parcel);
1616        }
1617        if (parcel.readInt() != 0) {
1618            tickerText = TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(parcel);
1619        }
1620        if (parcel.readInt() != 0) {
1621            tickerView = RemoteViews.CREATOR.createFromParcel(parcel);
1622        }
1623        if (parcel.readInt() != 0) {
1624            contentView = RemoteViews.CREATOR.createFromParcel(parcel);
1625        }
1626        if (parcel.readInt() != 0) {
1627            mLargeIcon = Icon.CREATOR.createFromParcel(parcel);
1628        }
1629        defaults = parcel.readInt();
1630        flags = parcel.readInt();
1631        if (parcel.readInt() != 0) {
1632            sound = Uri.CREATOR.createFromParcel(parcel);
1633        }
1634
1635        audioStreamType = parcel.readInt();
1636        if (parcel.readInt() != 0) {
1637            audioAttributes = AudioAttributes.CREATOR.createFromParcel(parcel);
1638        }
1639        vibrate = parcel.createLongArray();
1640        ledARGB = parcel.readInt();
1641        ledOnMS = parcel.readInt();
1642        ledOffMS = parcel.readInt();
1643        iconLevel = parcel.readInt();
1644
1645        if (parcel.readInt() != 0) {
1646            fullScreenIntent = PendingIntent.CREATOR.createFromParcel(parcel);
1647        }
1648
1649        priority = parcel.readInt();
1650
1651        category = parcel.readString();
1652
1653        mGroupKey = parcel.readString();
1654
1655        mSortKey = parcel.readString();
1656
1657        extras = Bundle.setDefusable(parcel.readBundle(), true); // may be null
1658
1659        actions = parcel.createTypedArray(Action.CREATOR); // may be null
1660
1661        if (parcel.readInt() != 0) {
1662            bigContentView = RemoteViews.CREATOR.createFromParcel(parcel);
1663        }
1664
1665        if (parcel.readInt() != 0) {
1666            headsUpContentView = RemoteViews.CREATOR.createFromParcel(parcel);
1667        }
1668
1669        visibility = parcel.readInt();
1670
1671        if (parcel.readInt() != 0) {
1672            publicVersion = Notification.CREATOR.createFromParcel(parcel);
1673        }
1674
1675        color = parcel.readInt();
1676    }
1677
1678    @Override
1679    public Notification clone() {
1680        Notification that = new Notification();
1681        cloneInto(that, true);
1682        return that;
1683    }
1684
1685    /**
1686     * Copy all (or if heavy is false, all except Bitmaps and RemoteViews) members
1687     * of this into that.
1688     * @hide
1689     */
1690    public void cloneInto(Notification that, boolean heavy) {
1691        that.when = this.when;
1692        that.creationTime = this.creationTime;
1693        that.mSmallIcon = this.mSmallIcon;
1694        that.number = this.number;
1695
1696        // PendingIntents are global, so there's no reason (or way) to clone them.
1697        that.contentIntent = this.contentIntent;
1698        that.deleteIntent = this.deleteIntent;
1699        that.fullScreenIntent = this.fullScreenIntent;
1700
1701        if (this.tickerText != null) {
1702            that.tickerText = this.tickerText.toString();
1703        }
1704        if (heavy && this.tickerView != null) {
1705            that.tickerView = this.tickerView.clone();
1706        }
1707        if (heavy && this.contentView != null) {
1708            that.contentView = this.contentView.clone();
1709        }
1710        if (heavy && this.mLargeIcon != null) {
1711            that.mLargeIcon = this.mLargeIcon;
1712        }
1713        that.iconLevel = this.iconLevel;
1714        that.sound = this.sound; // android.net.Uri is immutable
1715        that.audioStreamType = this.audioStreamType;
1716        if (this.audioAttributes != null) {
1717            that.audioAttributes = new AudioAttributes.Builder(this.audioAttributes).build();
1718        }
1719
1720        final long[] vibrate = this.vibrate;
1721        if (vibrate != null) {
1722            final int N = vibrate.length;
1723            final long[] vib = that.vibrate = new long[N];
1724            System.arraycopy(vibrate, 0, vib, 0, N);
1725        }
1726
1727        that.ledARGB = this.ledARGB;
1728        that.ledOnMS = this.ledOnMS;
1729        that.ledOffMS = this.ledOffMS;
1730        that.defaults = this.defaults;
1731
1732        that.flags = this.flags;
1733
1734        that.priority = this.priority;
1735
1736        that.category = this.category;
1737
1738        that.mGroupKey = this.mGroupKey;
1739
1740        that.mSortKey = this.mSortKey;
1741
1742        if (this.extras != null) {
1743            try {
1744                that.extras = new Bundle(this.extras);
1745                // will unparcel
1746                that.extras.size();
1747            } catch (BadParcelableException e) {
1748                Log.e(TAG, "could not unparcel extras from notification: " + this, e);
1749                that.extras = null;
1750            }
1751        }
1752
1753        if (!ArrayUtils.isEmpty(allPendingIntents)) {
1754            that.allPendingIntents = new ArraySet<>(allPendingIntents);
1755        }
1756
1757        if (this.actions != null) {
1758            that.actions = new Action[this.actions.length];
1759            for(int i=0; i<this.actions.length; i++) {
1760                that.actions[i] = this.actions[i].clone();
1761            }
1762        }
1763
1764        if (heavy && this.bigContentView != null) {
1765            that.bigContentView = this.bigContentView.clone();
1766        }
1767
1768        if (heavy && this.headsUpContentView != null) {
1769            that.headsUpContentView = this.headsUpContentView.clone();
1770        }
1771
1772        that.visibility = this.visibility;
1773
1774        if (this.publicVersion != null) {
1775            that.publicVersion = new Notification();
1776            this.publicVersion.cloneInto(that.publicVersion, heavy);
1777        }
1778
1779        that.color = this.color;
1780
1781        if (!heavy) {
1782            that.lightenPayload(); // will clean out extras
1783        }
1784    }
1785
1786    /**
1787     * Removes heavyweight parts of the Notification object for archival or for sending to
1788     * listeners when the full contents are not necessary.
1789     * @hide
1790     */
1791    public final void lightenPayload() {
1792        tickerView = null;
1793        contentView = null;
1794        bigContentView = null;
1795        headsUpContentView = null;
1796        mLargeIcon = null;
1797        if (extras != null && !extras.isEmpty()) {
1798            final Set<String> keyset = extras.keySet();
1799            final int N = keyset.size();
1800            final String[] keys = keyset.toArray(new String[N]);
1801            for (int i=0; i<N; i++) {
1802                final String key = keys[i];
1803                final Object obj = extras.get(key);
1804                if (obj != null &&
1805                    (  obj instanceof Parcelable
1806                    || obj instanceof Parcelable[]
1807                    || obj instanceof SparseArray
1808                    || obj instanceof ArrayList)) {
1809                    extras.remove(key);
1810                }
1811            }
1812        }
1813    }
1814
1815    /**
1816     * Make sure this CharSequence is safe to put into a bundle, which basically
1817     * means it had better not be some custom Parcelable implementation.
1818     * @hide
1819     */
1820    public static CharSequence safeCharSequence(CharSequence cs) {
1821        if (cs == null) return cs;
1822        if (cs.length() > MAX_CHARSEQUENCE_LENGTH) {
1823            cs = cs.subSequence(0, MAX_CHARSEQUENCE_LENGTH);
1824        }
1825        if (cs instanceof Parcelable) {
1826            Log.e(TAG, "warning: " + cs.getClass().getCanonicalName()
1827                    + " instance is a custom Parcelable and not allowed in Notification");
1828            return cs.toString();
1829        }
1830        return removeTextSizeSpans(cs);
1831    }
1832
1833    private static CharSequence removeTextSizeSpans(CharSequence charSequence) {
1834        if (charSequence instanceof Spanned) {
1835            Spanned ss = (Spanned) charSequence;
1836            Object[] spans = ss.getSpans(0, ss.length(), Object.class);
1837            SpannableStringBuilder builder = new SpannableStringBuilder(ss.toString());
1838            for (Object span : spans) {
1839                Object resultSpan = span;
1840                if (resultSpan instanceof CharacterStyle) {
1841                    resultSpan = ((CharacterStyle) span).getUnderlying();
1842                }
1843                if (resultSpan instanceof TextAppearanceSpan) {
1844                    TextAppearanceSpan originalSpan = (TextAppearanceSpan) resultSpan;
1845                    resultSpan = new TextAppearanceSpan(
1846                            originalSpan.getFamily(),
1847                            originalSpan.getTextStyle(),
1848                            -1,
1849                            originalSpan.getTextColor(),
1850                            originalSpan.getLinkTextColor());
1851                } else if (resultSpan instanceof RelativeSizeSpan
1852                        || resultSpan instanceof AbsoluteSizeSpan) {
1853                    continue;
1854                } else {
1855                    resultSpan = span;
1856                }
1857                builder.setSpan(resultSpan, ss.getSpanStart(span), ss.getSpanEnd(span),
1858                        ss.getSpanFlags(span));
1859            }
1860            return builder;
1861        }
1862        return charSequence;
1863    }
1864
1865    public int describeContents() {
1866        return 0;
1867    }
1868
1869    /**
1870     * Flatten this notification into a parcel.
1871     */
1872    public void writeToParcel(Parcel parcel, int flags) {
1873        // We need to mark all pending intents getting into the notification
1874        // system as being put there to later allow the notification ranker
1875        // to launch them and by doing so add the app to the battery saver white
1876        // list for a short period of time. The problem is that the system
1877        // cannot look into the extras as there may be parcelables there that
1878        // the platform does not know how to handle. To go around that we have
1879        // an explicit list of the pending intents in the extras bundle.
1880        final boolean collectPendingIntents = (allPendingIntents == null);
1881        if (collectPendingIntents) {
1882            PendingIntent.setOnMarshaledListener(
1883                    (PendingIntent intent, Parcel out, int outFlags) -> {
1884                if (parcel == out) {
1885                    if (allPendingIntents == null) {
1886                        allPendingIntents = new ArraySet<>();
1887                    }
1888                    allPendingIntents.add(intent);
1889                }
1890            });
1891        }
1892        try {
1893            // IMPORTANT: Add marshaling code in writeToParcelImpl as we
1894            // want to intercept all pending events written to the pacel.
1895            writeToParcelImpl(parcel, flags);
1896            // Must be written last!
1897            parcel.writeArraySet(allPendingIntents);
1898        } finally {
1899            if (collectPendingIntents) {
1900                PendingIntent.setOnMarshaledListener(null);
1901            }
1902        }
1903    }
1904
1905    private void writeToParcelImpl(Parcel parcel, int flags) {
1906        parcel.writeInt(1);
1907
1908        parcel.writeLong(when);
1909        parcel.writeLong(creationTime);
1910        if (mSmallIcon == null && icon != 0) {
1911            // you snuck an icon in here without using the builder; let's try to keep it
1912            mSmallIcon = Icon.createWithResource("", icon);
1913        }
1914        if (mSmallIcon != null) {
1915            parcel.writeInt(1);
1916            mSmallIcon.writeToParcel(parcel, 0);
1917        } else {
1918            parcel.writeInt(0);
1919        }
1920        parcel.writeInt(number);
1921        if (contentIntent != null) {
1922            parcel.writeInt(1);
1923            contentIntent.writeToParcel(parcel, 0);
1924        } else {
1925            parcel.writeInt(0);
1926        }
1927        if (deleteIntent != null) {
1928            parcel.writeInt(1);
1929            deleteIntent.writeToParcel(parcel, 0);
1930        } else {
1931            parcel.writeInt(0);
1932        }
1933        if (tickerText != null) {
1934            parcel.writeInt(1);
1935            TextUtils.writeToParcel(tickerText, parcel, flags);
1936        } else {
1937            parcel.writeInt(0);
1938        }
1939        if (tickerView != null) {
1940            parcel.writeInt(1);
1941            tickerView.writeToParcel(parcel, 0);
1942        } else {
1943            parcel.writeInt(0);
1944        }
1945        if (contentView != null) {
1946            parcel.writeInt(1);
1947            contentView.writeToParcel(parcel, 0);
1948        } else {
1949            parcel.writeInt(0);
1950        }
1951        if (mLargeIcon == null && largeIcon != null) {
1952            // you snuck an icon in here without using the builder; let's try to keep it
1953            mLargeIcon = Icon.createWithBitmap(largeIcon);
1954        }
1955        if (mLargeIcon != null) {
1956            parcel.writeInt(1);
1957            mLargeIcon.writeToParcel(parcel, 0);
1958        } else {
1959            parcel.writeInt(0);
1960        }
1961
1962        parcel.writeInt(defaults);
1963        parcel.writeInt(this.flags);
1964
1965        if (sound != null) {
1966            parcel.writeInt(1);
1967            sound.writeToParcel(parcel, 0);
1968        } else {
1969            parcel.writeInt(0);
1970        }
1971        parcel.writeInt(audioStreamType);
1972
1973        if (audioAttributes != null) {
1974            parcel.writeInt(1);
1975            audioAttributes.writeToParcel(parcel, 0);
1976        } else {
1977            parcel.writeInt(0);
1978        }
1979
1980        parcel.writeLongArray(vibrate);
1981        parcel.writeInt(ledARGB);
1982        parcel.writeInt(ledOnMS);
1983        parcel.writeInt(ledOffMS);
1984        parcel.writeInt(iconLevel);
1985
1986        if (fullScreenIntent != null) {
1987            parcel.writeInt(1);
1988            fullScreenIntent.writeToParcel(parcel, 0);
1989        } else {
1990            parcel.writeInt(0);
1991        }
1992
1993        parcel.writeInt(priority);
1994
1995        parcel.writeString(category);
1996
1997        parcel.writeString(mGroupKey);
1998
1999        parcel.writeString(mSortKey);
2000
2001        parcel.writeBundle(extras); // null ok
2002
2003        parcel.writeTypedArray(actions, 0); // null ok
2004
2005        if (bigContentView != null) {
2006            parcel.writeInt(1);
2007            bigContentView.writeToParcel(parcel, 0);
2008        } else {
2009            parcel.writeInt(0);
2010        }
2011
2012        if (headsUpContentView != null) {
2013            parcel.writeInt(1);
2014            headsUpContentView.writeToParcel(parcel, 0);
2015        } else {
2016            parcel.writeInt(0);
2017        }
2018
2019        parcel.writeInt(visibility);
2020
2021        if (publicVersion != null) {
2022            parcel.writeInt(1);
2023            publicVersion.writeToParcel(parcel, 0);
2024        } else {
2025            parcel.writeInt(0);
2026        }
2027
2028        parcel.writeInt(color);
2029    }
2030
2031    /**
2032     * Parcelable.Creator that instantiates Notification objects
2033     */
2034    public static final Parcelable.Creator<Notification> CREATOR
2035            = new Parcelable.Creator<Notification>()
2036    {
2037        public Notification createFromParcel(Parcel parcel)
2038        {
2039            return new Notification(parcel);
2040        }
2041
2042        public Notification[] newArray(int size)
2043        {
2044            return new Notification[size];
2045        }
2046    };
2047
2048    /**
2049     * Sets the {@link #contentView} field to be a view with the standard "Latest Event"
2050     * layout.
2051     *
2052     * <p>Uses the {@link #icon} and {@link #when} fields to set the icon and time fields
2053     * in the view.</p>
2054     * @param context       The context for your application / activity.
2055     * @param contentTitle The title that goes in the expanded entry.
2056     * @param contentText  The text that goes in the expanded entry.
2057     * @param contentIntent The intent to launch when the user clicks the expanded notification.
2058     * If this is an activity, it must include the
2059     * {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires
2060     * that you take care of task management as described in the
2061     * <a href="{@docRoot}guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back
2062     * Stack</a> document.
2063     *
2064     * @deprecated Use {@link Builder} instead.
2065     * @removed
2066     */
2067    @Deprecated
2068    public void setLatestEventInfo(Context context,
2069            CharSequence contentTitle, CharSequence contentText, PendingIntent contentIntent) {
2070        if (context.getApplicationInfo().targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1){
2071            Log.e(TAG, "setLatestEventInfo() is deprecated and you should feel deprecated.",
2072                    new Throwable());
2073        }
2074
2075        if (context.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N) {
2076            extras.putBoolean(EXTRA_SHOW_WHEN, true);
2077        }
2078
2079        // ensure that any information already set directly is preserved
2080        final Notification.Builder builder = new Notification.Builder(context, this);
2081
2082        // now apply the latestEventInfo fields
2083        if (contentTitle != null) {
2084            builder.setContentTitle(contentTitle);
2085        }
2086        if (contentText != null) {
2087            builder.setContentText(contentText);
2088        }
2089        builder.setContentIntent(contentIntent);
2090
2091        builder.build(); // callers expect this notification to be ready to use
2092    }
2093
2094    /**
2095     * @hide
2096     */
2097    public static void addFieldsFromContext(Context context, Notification notification) {
2098        addFieldsFromContext(context.getApplicationInfo(), context.getUserId(), notification);
2099    }
2100
2101    /**
2102     * @hide
2103     */
2104    public static void addFieldsFromContext(ApplicationInfo ai, int userId,
2105            Notification notification) {
2106        notification.extras.putParcelable(EXTRA_BUILDER_APPLICATION_INFO, ai);
2107        notification.extras.putInt(EXTRA_ORIGINATING_USERID, userId);
2108    }
2109
2110    @Override
2111    public String toString() {
2112        StringBuilder sb = new StringBuilder();
2113        sb.append("Notification(pri=");
2114        sb.append(priority);
2115        sb.append(" contentView=");
2116        if (contentView != null) {
2117            sb.append(contentView.getPackage());
2118            sb.append("/0x");
2119            sb.append(Integer.toHexString(contentView.getLayoutId()));
2120        } else {
2121            sb.append("null");
2122        }
2123        sb.append(" vibrate=");
2124        if ((this.defaults & DEFAULT_VIBRATE) != 0) {
2125            sb.append("default");
2126        } else if (this.vibrate != null) {
2127            int N = this.vibrate.length-1;
2128            sb.append("[");
2129            for (int i=0; i<N; i++) {
2130                sb.append(this.vibrate[i]);
2131                sb.append(',');
2132            }
2133            if (N != -1) {
2134                sb.append(this.vibrate[N]);
2135            }
2136            sb.append("]");
2137        } else {
2138            sb.append("null");
2139        }
2140        sb.append(" sound=");
2141        if ((this.defaults & DEFAULT_SOUND) != 0) {
2142            sb.append("default");
2143        } else if (this.sound != null) {
2144            sb.append(this.sound.toString());
2145        } else {
2146            sb.append("null");
2147        }
2148        if (this.tickerText != null) {
2149            sb.append(" tick");
2150        }
2151        sb.append(" defaults=0x");
2152        sb.append(Integer.toHexString(this.defaults));
2153        sb.append(" flags=0x");
2154        sb.append(Integer.toHexString(this.flags));
2155        sb.append(String.format(" color=0x%08x", this.color));
2156        if (this.category != null) {
2157            sb.append(" category=");
2158            sb.append(this.category);
2159        }
2160        if (this.mGroupKey != null) {
2161            sb.append(" groupKey=");
2162            sb.append(this.mGroupKey);
2163        }
2164        if (this.mSortKey != null) {
2165            sb.append(" sortKey=");
2166            sb.append(this.mSortKey);
2167        }
2168        if (actions != null) {
2169            sb.append(" actions=");
2170            sb.append(actions.length);
2171        }
2172        sb.append(" vis=");
2173        sb.append(visibilityToString(this.visibility));
2174        if (this.publicVersion != null) {
2175            sb.append(" publicVersion=");
2176            sb.append(publicVersion.toString());
2177        }
2178        sb.append(")");
2179        return sb.toString();
2180    }
2181
2182    /**
2183     * {@hide}
2184     */
2185    public static String visibilityToString(int vis) {
2186        switch (vis) {
2187            case VISIBILITY_PRIVATE:
2188                return "PRIVATE";
2189            case VISIBILITY_PUBLIC:
2190                return "PUBLIC";
2191            case VISIBILITY_SECRET:
2192                return "SECRET";
2193            default:
2194                return "UNKNOWN(" + String.valueOf(vis) + ")";
2195        }
2196    }
2197
2198    /**
2199     * {@hide}
2200     */
2201    public static String priorityToString(@Priority int pri) {
2202        switch (pri) {
2203            case PRIORITY_MIN:
2204                return "MIN";
2205            case PRIORITY_LOW:
2206                return "LOW";
2207            case PRIORITY_DEFAULT:
2208                return "DEFAULT";
2209            case PRIORITY_HIGH:
2210                return "HIGH";
2211            case PRIORITY_MAX:
2212                return "MAX";
2213            default:
2214                return "UNKNOWN(" + String.valueOf(pri) + ")";
2215        }
2216    }
2217
2218    /**
2219     * The small icon representing this notification in the status bar and content view.
2220     *
2221     * @return the small icon representing this notification.
2222     *
2223     * @see Builder#getSmallIcon()
2224     * @see Builder#setSmallIcon(Icon)
2225     */
2226    public Icon getSmallIcon() {
2227        return mSmallIcon;
2228    }
2229
2230    /**
2231     * Used when notifying to clean up legacy small icons.
2232     * @hide
2233     */
2234    public void setSmallIcon(Icon icon) {
2235        mSmallIcon = icon;
2236    }
2237
2238    /**
2239     * The large icon shown in this notification's content view.
2240     * @see Builder#getLargeIcon()
2241     * @see Builder#setLargeIcon(Icon)
2242     */
2243    public Icon getLargeIcon() {
2244        return mLargeIcon;
2245    }
2246
2247    /**
2248     * @hide
2249     */
2250    public boolean isGroupSummary() {
2251        return mGroupKey != null && (flags & FLAG_GROUP_SUMMARY) != 0;
2252    }
2253
2254    /**
2255     * @hide
2256     */
2257    public boolean isGroupChild() {
2258        return mGroupKey != null && (flags & FLAG_GROUP_SUMMARY) == 0;
2259    }
2260
2261    /**
2262     * Builder class for {@link Notification} objects.
2263     *
2264     * Provides a convenient way to set the various fields of a {@link Notification} and generate
2265     * content views using the platform's notification layout template. If your app supports
2266     * versions of Android as old as API level 4, you can instead use
2267     * {@link android.support.v4.app.NotificationCompat.Builder NotificationCompat.Builder},
2268     * available in the <a href="{@docRoot}tools/extras/support-library.html">Android Support
2269     * library</a>.
2270     *
2271     * <p>Example:
2272     *
2273     * <pre class="prettyprint">
2274     * Notification noti = new Notification.Builder(mContext)
2275     *         .setContentTitle(&quot;New mail from &quot; + sender.toString())
2276     *         .setContentText(subject)
2277     *         .setSmallIcon(R.drawable.new_mail)
2278     *         .setLargeIcon(aBitmap)
2279     *         .build();
2280     * </pre>
2281     */
2282    public static class Builder {
2283        /**
2284         * @hide
2285         */
2286        public static final String EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT =
2287                "android.rebuild.contentViewActionCount";
2288        /**
2289         * @hide
2290         */
2291        public static final String EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT
2292                = "android.rebuild.bigViewActionCount";
2293        /**
2294         * @hide
2295         */
2296        public static final String EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT
2297                = "android.rebuild.hudViewActionCount";
2298
2299        private static final int MAX_ACTION_BUTTONS = 3;
2300
2301        private Context mContext;
2302        private Notification mN;
2303        private Bundle mUserExtras = new Bundle();
2304        private Style mStyle;
2305        private ArrayList<Action> mActions = new ArrayList<Action>(MAX_ACTION_BUTTONS);
2306        private ArrayList<String> mPersonList = new ArrayList<String>();
2307        private NotificationColorUtil mColorUtil;
2308        private boolean mColorUtilInited = false;
2309
2310        /**
2311         * Caches a contrast-enhanced version of {@link #mCachedContrastColorIsFor}.
2312         */
2313        private int mCachedContrastColor = COLOR_INVALID;
2314        private int mCachedContrastColorIsFor = COLOR_INVALID;
2315
2316        /**
2317         * Constructs a new Builder with the defaults:
2318         *
2319
2320         * <table>
2321         * <tr><th align=right>priority</th>
2322         *     <td>{@link #PRIORITY_DEFAULT}</td></tr>
2323         * <tr><th align=right>when</th>
2324         *     <td>now ({@link System#currentTimeMillis()})</td></tr>
2325         * <tr><th align=right>audio stream</th>
2326         *     <td>{@link #STREAM_DEFAULT}</td></tr>
2327         * </table>
2328         *
2329
2330         * @param context
2331         *            A {@link Context} that will be used by the Builder to construct the
2332         *            RemoteViews. The Context will not be held past the lifetime of this Builder
2333         *            object.
2334         */
2335        public Builder(Context context) {
2336            this(context, null);
2337        }
2338
2339        /**
2340         * @hide
2341         */
2342        public Builder(Context context, Notification toAdopt) {
2343            mContext = context;
2344
2345            if (toAdopt == null) {
2346                mN = new Notification();
2347                if (context.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N) {
2348                    mN.extras.putBoolean(EXTRA_SHOW_WHEN, true);
2349                }
2350                mN.priority = PRIORITY_DEFAULT;
2351                mN.visibility = VISIBILITY_PRIVATE;
2352            } else {
2353                mN = toAdopt;
2354                if (mN.actions != null) {
2355                    Collections.addAll(mActions, mN.actions);
2356                }
2357
2358                if (mN.extras.containsKey(EXTRA_PEOPLE)) {
2359                    Collections.addAll(mPersonList, mN.extras.getStringArray(EXTRA_PEOPLE));
2360                }
2361
2362                if (mN.getSmallIcon() == null && mN.icon != 0) {
2363                    setSmallIcon(mN.icon);
2364                }
2365
2366                if (mN.getLargeIcon() == null && mN.largeIcon != null) {
2367                    setLargeIcon(mN.largeIcon);
2368                }
2369
2370                String templateClass = mN.extras.getString(EXTRA_TEMPLATE);
2371                if (!TextUtils.isEmpty(templateClass)) {
2372                    final Class<? extends Style> styleClass
2373                            = getNotificationStyleClass(templateClass);
2374                    if (styleClass == null) {
2375                        Log.d(TAG, "Unknown style class: " + templateClass);
2376                    } else {
2377                        try {
2378                            final Constructor<? extends Style> ctor =
2379                                    styleClass.getDeclaredConstructor();
2380                            ctor.setAccessible(true);
2381                            final Style style = ctor.newInstance();
2382                            style.restoreFromExtras(mN.extras);
2383
2384                            if (style != null) {
2385                                setStyle(style);
2386                            }
2387                        } catch (Throwable t) {
2388                            Log.e(TAG, "Could not create Style", t);
2389                        }
2390                    }
2391                }
2392
2393            }
2394        }
2395
2396        private NotificationColorUtil getColorUtil() {
2397            if (!mColorUtilInited) {
2398                mColorUtilInited = true;
2399                if (mContext.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.LOLLIPOP) {
2400                    mColorUtil = NotificationColorUtil.getInstance(mContext);
2401                }
2402            }
2403            return mColorUtil;
2404        }
2405
2406        /**
2407         * Add a timestamp pertaining to the notification (usually the time the event occurred).
2408         *
2409         * For apps targeting {@link android.os.Build.VERSION_CODES#N} and above, this time is not
2410         * shown anymore by default and must be opted into by using
2411         * {@link android.app.Notification.Builder#setShowWhen(boolean)}
2412         *
2413         * @see Notification#when
2414         */
2415        public Builder setWhen(long when) {
2416            mN.when = when;
2417            return this;
2418        }
2419
2420        /**
2421         * Control whether the timestamp set with {@link #setWhen(long) setWhen} is shown
2422         * in the content view.
2423         * For apps targeting {@link android.os.Build.VERSION_CODES#N} and above, this defaults to
2424         * {@code false}. For earlier apps, the default is {@code true}.
2425         */
2426        public Builder setShowWhen(boolean show) {
2427            mN.extras.putBoolean(EXTRA_SHOW_WHEN, show);
2428            return this;
2429        }
2430
2431        /**
2432         * Show the {@link Notification#when} field as a stopwatch.
2433         *
2434         * Instead of presenting <code>when</code> as a timestamp, the notification will show an
2435         * automatically updating display of the minutes and seconds since <code>when</code>.
2436         *
2437         * Useful when showing an elapsed time (like an ongoing phone call).
2438         *
2439         * The counter can also be set to count down to <code>when</code> when using
2440         * {@link #setChronometerCountDown(boolean)}.
2441         *
2442         * @see android.widget.Chronometer
2443         * @see Notification#when
2444         * @see #setChronometerCountDown(boolean)
2445         */
2446        public Builder setUsesChronometer(boolean b) {
2447            mN.extras.putBoolean(EXTRA_SHOW_CHRONOMETER, b);
2448            return this;
2449        }
2450
2451        /**
2452         * Sets the Chronometer to count down instead of counting up.
2453         *
2454         * <p>This is only relevant if {@link #setUsesChronometer(boolean)} has been set to true.
2455         * If it isn't set the chronometer will count up.
2456         *
2457         * @see #setUsesChronometer(boolean)
2458         */
2459        public Builder setChronometerCountDown(boolean countDown) {
2460            mN.extras.putBoolean(EXTRA_CHRONOMETER_COUNT_DOWN, countDown);
2461            return this;
2462        }
2463
2464        /**
2465         * Set the small icon resource, which will be used to represent the notification in the
2466         * status bar.
2467         *
2468
2469         * The platform template for the expanded view will draw this icon in the left, unless a
2470         * {@link #setLargeIcon(Bitmap) large icon} has also been specified, in which case the small
2471         * icon will be moved to the right-hand side.
2472         *
2473
2474         * @param icon
2475         *            A resource ID in the application's package of the drawable to use.
2476         * @see Notification#icon
2477         */
2478        public Builder setSmallIcon(@DrawableRes int icon) {
2479            return setSmallIcon(icon != 0
2480                    ? Icon.createWithResource(mContext, icon)
2481                    : null);
2482        }
2483
2484        /**
2485         * A variant of {@link #setSmallIcon(int) setSmallIcon(int)} that takes an additional
2486         * level parameter for when the icon is a {@link android.graphics.drawable.LevelListDrawable
2487         * LevelListDrawable}.
2488         *
2489         * @param icon A resource ID in the application's package of the drawable to use.
2490         * @param level The level to use for the icon.
2491         *
2492         * @see Notification#icon
2493         * @see Notification#iconLevel
2494         */
2495        public Builder setSmallIcon(@DrawableRes int icon, int level) {
2496            mN.iconLevel = level;
2497            return setSmallIcon(icon);
2498        }
2499
2500        /**
2501         * Set the small icon, which will be used to represent the notification in the
2502         * status bar and content view (unless overriden there by a
2503         * {@link #setLargeIcon(Bitmap) large icon}).
2504         *
2505         * @param icon An Icon object to use.
2506         * @see Notification#icon
2507         */
2508        public Builder setSmallIcon(Icon icon) {
2509            mN.setSmallIcon(icon);
2510            if (icon != null && icon.getType() == Icon.TYPE_RESOURCE) {
2511                mN.icon = icon.getResId();
2512            }
2513            return this;
2514        }
2515
2516        /**
2517         * Set the first line of text in the platform notification template.
2518         */
2519        public Builder setContentTitle(CharSequence title) {
2520            mN.extras.putCharSequence(EXTRA_TITLE, safeCharSequence(title));
2521            return this;
2522        }
2523
2524        /**
2525         * Set the second line of text in the platform notification template.
2526         */
2527        public Builder setContentText(CharSequence text) {
2528            mN.extras.putCharSequence(EXTRA_TEXT, safeCharSequence(text));
2529            return this;
2530        }
2531
2532        /**
2533         * This provides some additional information that is displayed in the notification. No
2534         * guarantees are given where exactly it is displayed.
2535         *
2536         * <p>This information should only be provided if it provides an essential
2537         * benefit to the understanding of the notification. The more text you provide the
2538         * less readable it becomes. For example, an email client should only provide the account
2539         * name here if more than one email account has been added.</p>
2540         *
2541         * <p>As of {@link android.os.Build.VERSION_CODES#N} this information is displayed in the
2542         * notification header area.
2543         *
2544         * On Android versions before {@link android.os.Build.VERSION_CODES#N}
2545         * this will be shown in the third line of text in the platform notification template.
2546         * You should not be using {@link #setProgress(int, int, boolean)} at the
2547         * same time on those versions; they occupy the same place.
2548         * </p>
2549         */
2550        public Builder setSubText(CharSequence text) {
2551            mN.extras.putCharSequence(EXTRA_SUB_TEXT, safeCharSequence(text));
2552            return this;
2553        }
2554
2555        /**
2556         * Set the remote input history.
2557         *
2558         * This should be set to the most recent inputs that have been sent
2559         * through a {@link RemoteInput} of this Notification and cleared once the it is no
2560         * longer relevant (e.g. for chat notifications once the other party has responded).
2561         *
2562         * The most recent input must be stored at the 0 index, the second most recent at the
2563         * 1 index, etc. Note that the system will limit both how far back the inputs will be shown
2564         * and how much of each individual input is shown.
2565         *
2566         * <p>Note: The reply text will only be shown on notifications that have least one action
2567         * with a {@code RemoteInput}.</p>
2568         */
2569        public Builder setRemoteInputHistory(CharSequence[] text) {
2570            if (text == null) {
2571                mN.extras.putCharSequenceArray(EXTRA_REMOTE_INPUT_HISTORY, null);
2572            } else {
2573                final int N = Math.min(MAX_REPLY_HISTORY, text.length);
2574                CharSequence[] safe = new CharSequence[N];
2575                for (int i = 0; i < N; i++) {
2576                    safe[i] = safeCharSequence(text[i]);
2577                }
2578                mN.extras.putCharSequenceArray(EXTRA_REMOTE_INPUT_HISTORY, safe);
2579            }
2580            return this;
2581        }
2582
2583        /**
2584         * Set the large number at the right-hand side of the notification.  This is
2585         * equivalent to setContentInfo, although it might show the number in a different
2586         * font size for readability.
2587         *
2588         * @deprecated this number is not shown anywhere anymore
2589         */
2590        public Builder setNumber(int number) {
2591            mN.number = number;
2592            return this;
2593        }
2594
2595        /**
2596         * A small piece of additional information pertaining to this notification.
2597         *
2598         * The platform template will draw this on the last line of the notification, at the far
2599         * right (to the right of a smallIcon if it has been placed there).
2600         *
2601         * @deprecated use {@link #setSubText(CharSequence)} instead to set a text in the header.
2602         * For legacy apps targeting a version below {@link android.os.Build.VERSION_CODES#N} this
2603         * field will still show up, but the subtext will take precedence.
2604         */
2605        public Builder setContentInfo(CharSequence info) {
2606            mN.extras.putCharSequence(EXTRA_INFO_TEXT, safeCharSequence(info));
2607            return this;
2608        }
2609
2610        /**
2611         * Set the progress this notification represents.
2612         *
2613         * The platform template will represent this using a {@link ProgressBar}.
2614         */
2615        public Builder setProgress(int max, int progress, boolean indeterminate) {
2616            mN.extras.putInt(EXTRA_PROGRESS, progress);
2617            mN.extras.putInt(EXTRA_PROGRESS_MAX, max);
2618            mN.extras.putBoolean(EXTRA_PROGRESS_INDETERMINATE, indeterminate);
2619            return this;
2620        }
2621
2622        /**
2623         * Supply a custom RemoteViews to use instead of the platform template.
2624         *
2625         * Use {@link #setCustomContentView(RemoteViews)} instead.
2626         */
2627        @Deprecated
2628        public Builder setContent(RemoteViews views) {
2629            return setCustomContentView(views);
2630        }
2631
2632        /**
2633         * Supply custom RemoteViews to use instead of the platform template.
2634         *
2635         * This will override the layout that would otherwise be constructed by this Builder
2636         * object.
2637         */
2638        public Builder setCustomContentView(RemoteViews contentView) {
2639            mN.contentView = contentView;
2640            return this;
2641        }
2642
2643        /**
2644         * Supply custom RemoteViews to use instead of the platform template in the expanded form.
2645         *
2646         * This will override the expanded layout that would otherwise be constructed by this
2647         * Builder object.
2648         */
2649        public Builder setCustomBigContentView(RemoteViews contentView) {
2650            mN.bigContentView = contentView;
2651            return this;
2652        }
2653
2654        /**
2655         * Supply custom RemoteViews to use instead of the platform template in the heads up dialog.
2656         *
2657         * This will override the heads-up layout that would otherwise be constructed by this
2658         * Builder object.
2659         */
2660        public Builder setCustomHeadsUpContentView(RemoteViews contentView) {
2661            mN.headsUpContentView = contentView;
2662            return this;
2663        }
2664
2665        /**
2666         * Supply a {@link PendingIntent} to be sent when the notification is clicked.
2667         *
2668         * As of {@link android.os.Build.VERSION_CODES#HONEYCOMB}, if this field is unset and you
2669         * have specified a custom RemoteViews with {@link #setContent(RemoteViews)}, you can use
2670         * {@link RemoteViews#setOnClickPendingIntent RemoteViews.setOnClickPendingIntent(int,PendingIntent)}
2671         * to assign PendingIntents to individual views in that custom layout (i.e., to create
2672         * clickable buttons inside the notification view).
2673         *
2674         * @see Notification#contentIntent Notification.contentIntent
2675         */
2676        public Builder setContentIntent(PendingIntent intent) {
2677            mN.contentIntent = intent;
2678            return this;
2679        }
2680
2681        /**
2682         * Supply a {@link PendingIntent} to send when the notification is cleared explicitly by the user.
2683         *
2684         * @see Notification#deleteIntent
2685         */
2686        public Builder setDeleteIntent(PendingIntent intent) {
2687            mN.deleteIntent = intent;
2688            return this;
2689        }
2690
2691        /**
2692         * An intent to launch instead of posting the notification to the status bar.
2693         * Only for use with extremely high-priority notifications demanding the user's
2694         * <strong>immediate</strong> attention, such as an incoming phone call or
2695         * alarm clock that the user has explicitly set to a particular time.
2696         * If this facility is used for something else, please give the user an option
2697         * to turn it off and use a normal notification, as this can be extremely
2698         * disruptive.
2699         *
2700         * <p>
2701         * The system UI may choose to display a heads-up notification, instead of
2702         * launching this intent, while the user is using the device.
2703         * </p>
2704         *
2705         * @param intent The pending intent to launch.
2706         * @param highPriority Passing true will cause this notification to be sent
2707         *          even if other notifications are suppressed.
2708         *
2709         * @see Notification#fullScreenIntent
2710         */
2711        public Builder setFullScreenIntent(PendingIntent intent, boolean highPriority) {
2712            mN.fullScreenIntent = intent;
2713            setFlag(FLAG_HIGH_PRIORITY, highPriority);
2714            return this;
2715        }
2716
2717        /**
2718         * Set the "ticker" text which is sent to accessibility services.
2719         *
2720         * @see Notification#tickerText
2721         */
2722        public Builder setTicker(CharSequence tickerText) {
2723            mN.tickerText = safeCharSequence(tickerText);
2724            return this;
2725        }
2726
2727        /**
2728         * Obsolete version of {@link #setTicker(CharSequence)}.
2729         *
2730         */
2731        @Deprecated
2732        public Builder setTicker(CharSequence tickerText, RemoteViews views) {
2733            setTicker(tickerText);
2734            // views is ignored
2735            return this;
2736        }
2737
2738        /**
2739         * Add a large icon to the notification content view.
2740         *
2741         * In the platform template, this image will be shown on the left of the notification view
2742         * in place of the {@link #setSmallIcon(Icon) small icon} (which will be placed in a small
2743         * badge atop the large icon).
2744         */
2745        public Builder setLargeIcon(Bitmap b) {
2746            return setLargeIcon(b != null ? Icon.createWithBitmap(b) : null);
2747        }
2748
2749        /**
2750         * Add a large icon to the notification content view.
2751         *
2752         * In the platform template, this image will be shown on the left of the notification view
2753         * in place of the {@link #setSmallIcon(Icon) small icon} (which will be placed in a small
2754         * badge atop the large icon).
2755         */
2756        public Builder setLargeIcon(Icon icon) {
2757            mN.mLargeIcon = icon;
2758            mN.extras.putParcelable(EXTRA_LARGE_ICON, icon);
2759            return this;
2760        }
2761
2762        /**
2763         * Set the sound to play.
2764         *
2765         * It will be played using the {@link #AUDIO_ATTRIBUTES_DEFAULT default audio attributes}
2766         * for notifications.
2767         *
2768         * <p>
2769         * A notification that is noisy is more likely to be presented as a heads-up notification.
2770         * </p>
2771         *
2772         * @see Notification#sound
2773         */
2774        public Builder setSound(Uri sound) {
2775            mN.sound = sound;
2776            mN.audioAttributes = AUDIO_ATTRIBUTES_DEFAULT;
2777            return this;
2778        }
2779
2780        /**
2781         * Set the sound to play, along with a specific stream on which to play it.
2782         *
2783         * See {@link android.media.AudioManager} for the <code>STREAM_</code> constants.
2784         *
2785         * <p>
2786         * A notification that is noisy is more likely to be presented as a heads-up notification.
2787         * </p>
2788         * @deprecated use {@link #setSound(Uri, AudioAttributes)} instead.
2789         * @see Notification#sound
2790         */
2791        @Deprecated
2792        public Builder setSound(Uri sound, int streamType) {
2793            mN.sound = sound;
2794            mN.audioStreamType = streamType;
2795            return this;
2796        }
2797
2798        /**
2799         * Set the sound to play, along with specific {@link AudioAttributes audio attributes} to
2800         * use during playback.
2801         *
2802         * <p>
2803         * A notification that is noisy is more likely to be presented as a heads-up notification.
2804         * </p>
2805         *
2806         * @see Notification#sound
2807         */
2808        public Builder setSound(Uri sound, AudioAttributes audioAttributes) {
2809            mN.sound = sound;
2810            mN.audioAttributes = audioAttributes;
2811            return this;
2812        }
2813
2814        /**
2815         * Set the vibration pattern to use.
2816         *
2817         * See {@link android.os.Vibrator#vibrate(long[], int)} for a discussion of the
2818         * <code>pattern</code> parameter.
2819         *
2820         * <p>
2821         * A notification that vibrates is more likely to be presented as a heads-up notification.
2822         * </p>
2823         *
2824         * @see Notification#vibrate
2825         */
2826        public Builder setVibrate(long[] pattern) {
2827            mN.vibrate = pattern;
2828            return this;
2829        }
2830
2831        /**
2832         * Set the desired color for the indicator LED on the device, as well as the
2833         * blink duty cycle (specified in milliseconds).
2834         *
2835
2836         * Not all devices will honor all (or even any) of these values.
2837         *
2838
2839         * @see Notification#ledARGB
2840         * @see Notification#ledOnMS
2841         * @see Notification#ledOffMS
2842         */
2843        public Builder setLights(@ColorInt int argb, int onMs, int offMs) {
2844            mN.ledARGB = argb;
2845            mN.ledOnMS = onMs;
2846            mN.ledOffMS = offMs;
2847            if (onMs != 0 || offMs != 0) {
2848                mN.flags |= FLAG_SHOW_LIGHTS;
2849            }
2850            return this;
2851        }
2852
2853        /**
2854         * Set whether this is an "ongoing" notification.
2855         *
2856
2857         * Ongoing notifications cannot be dismissed by the user, so your application or service
2858         * must take care of canceling them.
2859         *
2860
2861         * They are typically used to indicate a background task that the user is actively engaged
2862         * with (e.g., playing music) or is pending in some way and therefore occupying the device
2863         * (e.g., a file download, sync operation, active network connection).
2864         *
2865
2866         * @see Notification#FLAG_ONGOING_EVENT
2867         * @see Service#setForeground(boolean)
2868         */
2869        public Builder setOngoing(boolean ongoing) {
2870            setFlag(FLAG_ONGOING_EVENT, ongoing);
2871            return this;
2872        }
2873
2874        /**
2875         * Set this flag if you would only like the sound, vibrate
2876         * and ticker to be played if the notification is not already showing.
2877         *
2878         * @see Notification#FLAG_ONLY_ALERT_ONCE
2879         */
2880        public Builder setOnlyAlertOnce(boolean onlyAlertOnce) {
2881            setFlag(FLAG_ONLY_ALERT_ONCE, onlyAlertOnce);
2882            return this;
2883        }
2884
2885        /**
2886         * Make this notification automatically dismissed when the user touches it. The
2887         * PendingIntent set with {@link #setDeleteIntent} will be sent when this happens.
2888         *
2889         * @see Notification#FLAG_AUTO_CANCEL
2890         */
2891        public Builder setAutoCancel(boolean autoCancel) {
2892            setFlag(FLAG_AUTO_CANCEL, autoCancel);
2893            return this;
2894        }
2895
2896        /**
2897         * Set whether or not this notification should not bridge to other devices.
2898         *
2899         * <p>Some notifications can be bridged to other devices for remote display.
2900         * This hint can be set to recommend this notification not be bridged.
2901         */
2902        public Builder setLocalOnly(boolean localOnly) {
2903            setFlag(FLAG_LOCAL_ONLY, localOnly);
2904            return this;
2905        }
2906
2907        /**
2908         * Set which notification properties will be inherited from system defaults.
2909         * <p>
2910         * The value should be one or more of the following fields combined with
2911         * bitwise-or:
2912         * {@link #DEFAULT_SOUND}, {@link #DEFAULT_VIBRATE}, {@link #DEFAULT_LIGHTS}.
2913         * <p>
2914         * For all default values, use {@link #DEFAULT_ALL}.
2915         */
2916        public Builder setDefaults(int defaults) {
2917            mN.defaults = defaults;
2918            return this;
2919        }
2920
2921        /**
2922         * Set the priority of this notification.
2923         *
2924         * @see Notification#priority
2925         */
2926        public Builder setPriority(@Priority int pri) {
2927            mN.priority = pri;
2928            return this;
2929        }
2930
2931        /**
2932         * Set the notification category.
2933         *
2934         * @see Notification#category
2935         */
2936        public Builder setCategory(String category) {
2937            mN.category = category;
2938            return this;
2939        }
2940
2941        /**
2942         * Add a person that is relevant to this notification.
2943         *
2944         * <P>
2945         * Depending on user preferences, this annotation may allow the notification to pass
2946         * through interruption filters, and to appear more prominently in the user interface.
2947         * </P>
2948         *
2949         * <P>
2950         * The person should be specified by the {@code String} representation of a
2951         * {@link android.provider.ContactsContract.Contacts#CONTENT_LOOKUP_URI}.
2952         * </P>
2953         *
2954         * <P>The system will also attempt to resolve {@code mailto:} and {@code tel:} schema
2955         * URIs.  The path part of these URIs must exist in the contacts database, in the
2956         * appropriate column, or the reference will be discarded as invalid. Telephone schema
2957         * URIs will be resolved by {@link android.provider.ContactsContract.PhoneLookup}.
2958         * </P>
2959         *
2960         * @param uri A URI for the person.
2961         * @see Notification#EXTRA_PEOPLE
2962         */
2963        public Builder addPerson(String uri) {
2964            mPersonList.add(uri);
2965            return this;
2966        }
2967
2968        /**
2969         * Set this notification to be part of a group of notifications sharing the same key.
2970         * Grouped notifications may display in a cluster or stack on devices which
2971         * support such rendering.
2972         *
2973         * <p>To make this notification the summary for its group, also call
2974         * {@link #setGroupSummary}. A sort order can be specified for group members by using
2975         * {@link #setSortKey}.
2976         * @param groupKey The group key of the group.
2977         * @return this object for method chaining
2978         */
2979        public Builder setGroup(String groupKey) {
2980            mN.mGroupKey = groupKey;
2981            return this;
2982        }
2983
2984        /**
2985         * Set this notification to be the group summary for a group of notifications.
2986         * Grouped notifications may display in a cluster or stack on devices which
2987         * support such rendering. Requires a group key also be set using {@link #setGroup}.
2988         * @param isGroupSummary Whether this notification should be a group summary.
2989         * @return this object for method chaining
2990         */
2991        public Builder setGroupSummary(boolean isGroupSummary) {
2992            setFlag(FLAG_GROUP_SUMMARY, isGroupSummary);
2993            return this;
2994        }
2995
2996        /**
2997         * Set a sort key that orders this notification among other notifications from the
2998         * same package. This can be useful if an external sort was already applied and an app
2999         * would like to preserve this. Notifications will be sorted lexicographically using this
3000         * value, although providing different priorities in addition to providing sort key may
3001         * cause this value to be ignored.
3002         *
3003         * <p>This sort key can also be used to order members of a notification group. See
3004         * {@link #setGroup}.
3005         *
3006         * @see String#compareTo(String)
3007         */
3008        public Builder setSortKey(String sortKey) {
3009            mN.mSortKey = sortKey;
3010            return this;
3011        }
3012
3013        /**
3014         * Merge additional metadata into this notification.
3015         *
3016         * <p>Values within the Bundle will replace existing extras values in this Builder.
3017         *
3018         * @see Notification#extras
3019         */
3020        public Builder addExtras(Bundle extras) {
3021            if (extras != null) {
3022                mUserExtras.putAll(extras);
3023            }
3024            return this;
3025        }
3026
3027        /**
3028         * Set metadata for this notification.
3029         *
3030         * <p>A reference to the Bundle is held for the lifetime of this Builder, and the Bundle's
3031         * current contents are copied into the Notification each time {@link #build()} is
3032         * called.
3033         *
3034         * <p>Replaces any existing extras values with those from the provided Bundle.
3035         * Use {@link #addExtras} to merge in metadata instead.
3036         *
3037         * @see Notification#extras
3038         */
3039        public Builder setExtras(Bundle extras) {
3040            if (extras != null) {
3041                mUserExtras = extras;
3042            }
3043            return this;
3044        }
3045
3046        /**
3047         * Get the current metadata Bundle used by this notification Builder.
3048         *
3049         * <p>The returned Bundle is shared with this Builder.
3050         *
3051         * <p>The current contents of this Bundle are copied into the Notification each time
3052         * {@link #build()} is called.
3053         *
3054         * @see Notification#extras
3055         */
3056        public Bundle getExtras() {
3057            return mUserExtras;
3058        }
3059
3060        private Bundle getAllExtras() {
3061            final Bundle saveExtras = (Bundle) mUserExtras.clone();
3062            saveExtras.putAll(mN.extras);
3063            return saveExtras;
3064        }
3065
3066        /**
3067         * Add an action to this notification. Actions are typically displayed by
3068         * the system as a button adjacent to the notification content.
3069         * <p>
3070         * Every action must have an icon (32dp square and matching the
3071         * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo
3072         * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}.
3073         * <p>
3074         * A notification in its expanded form can display up to 3 actions, from left to right in
3075         * the order they were added. Actions will not be displayed when the notification is
3076         * collapsed, however, so be sure that any essential functions may be accessed by the user
3077         * in some other way (for example, in the Activity pointed to by {@link #contentIntent}).
3078         *
3079         * @param icon Resource ID of a drawable that represents the action.
3080         * @param title Text describing the action.
3081         * @param intent PendingIntent to be fired when the action is invoked.
3082         *
3083         * @deprecated Use {@link #addAction(Action)} instead.
3084         */
3085        @Deprecated
3086        public Builder addAction(int icon, CharSequence title, PendingIntent intent) {
3087            mActions.add(new Action(icon, safeCharSequence(title), intent));
3088            return this;
3089        }
3090
3091        /**
3092         * Add an action to this notification. Actions are typically displayed by
3093         * the system as a button adjacent to the notification content.
3094         * <p>
3095         * Every action must have an icon (32dp square and matching the
3096         * <a href="{@docRoot}design/style/iconography.html#action-bar">Holo
3097         * Dark action bar</a> visual style), a textual label, and a {@link PendingIntent}.
3098         * <p>
3099         * A notification in its expanded form can display up to 3 actions, from left to right in
3100         * the order they were added. Actions will not be displayed when the notification is
3101         * collapsed, however, so be sure that any essential functions may be accessed by the user
3102         * in some other way (for example, in the Activity pointed to by {@link #contentIntent}).
3103         *
3104         * @param action The action to add.
3105         */
3106        public Builder addAction(Action action) {
3107            mActions.add(action);
3108            return this;
3109        }
3110
3111        /**
3112         * Alter the complete list of actions attached to this notification.
3113         * @see #addAction(Action).
3114         *
3115         * @param actions
3116         * @return
3117         */
3118        public Builder setActions(Action... actions) {
3119            mActions.clear();
3120            for (int i = 0; i < actions.length; i++) {
3121                mActions.add(actions[i]);
3122            }
3123            return this;
3124        }
3125
3126        /**
3127         * Add a rich notification style to be applied at build time.
3128         *
3129         * @param style Object responsible for modifying the notification style.
3130         */
3131        public Builder setStyle(Style style) {
3132            if (mStyle != style) {
3133                mStyle = style;
3134                if (mStyle != null) {
3135                    mStyle.setBuilder(this);
3136                    mN.extras.putString(EXTRA_TEMPLATE, style.getClass().getName());
3137                }  else {
3138                    mN.extras.remove(EXTRA_TEMPLATE);
3139                }
3140            }
3141            return this;
3142        }
3143
3144        /**
3145         * Specify the value of {@link #visibility}.
3146         *
3147         * @param visibility One of {@link #VISIBILITY_PRIVATE} (the default),
3148         * {@link #VISIBILITY_SECRET}, or {@link #VISIBILITY_PUBLIC}.
3149         *
3150         * @return The same Builder.
3151         */
3152        public Builder setVisibility(int visibility) {
3153            mN.visibility = visibility;
3154            return this;
3155        }
3156
3157        /**
3158         * Supply a replacement Notification whose contents should be shown in insecure contexts
3159         * (i.e. atop the secure lockscreen). See {@link #visibility} and {@link #VISIBILITY_PUBLIC}.
3160         * @param n A replacement notification, presumably with some or all info redacted.
3161         * @return The same Builder.
3162         */
3163        public Builder setPublicVersion(Notification n) {
3164            if (n != null) {
3165                mN.publicVersion = new Notification();
3166                n.cloneInto(mN.publicVersion, /*heavy=*/ true);
3167            } else {
3168                mN.publicVersion = null;
3169            }
3170            return this;
3171        }
3172
3173        /**
3174         * Apply an extender to this notification builder. Extenders may be used to add
3175         * metadata or change options on this builder.
3176         */
3177        public Builder extend(Extender extender) {
3178            extender.extend(this);
3179            return this;
3180        }
3181
3182        /**
3183         * @hide
3184         */
3185        public Builder setFlag(int mask, boolean value) {
3186            if (value) {
3187                mN.flags |= mask;
3188            } else {
3189                mN.flags &= ~mask;
3190            }
3191            return this;
3192        }
3193
3194        /**
3195         * Sets {@link Notification#color}.
3196         *
3197         * @param argb The accent color to use
3198         *
3199         * @return The same Builder.
3200         */
3201        public Builder setColor(@ColorInt int argb) {
3202            mN.color = argb;
3203            sanitizeColor();
3204            return this;
3205        }
3206
3207        private Drawable getProfileBadgeDrawable() {
3208            if (mContext.getUserId() == UserHandle.USER_SYSTEM) {
3209                // This user can never be a badged profile,
3210                // and also includes USER_ALL system notifications.
3211                return null;
3212            }
3213            // Note: This assumes that the current user can read the profile badge of the
3214            // originating user.
3215            return mContext.getPackageManager().getUserBadgeForDensityNoBackground(
3216                    new UserHandle(mContext.getUserId()), 0);
3217        }
3218
3219        private Bitmap getProfileBadge() {
3220            Drawable badge = getProfileBadgeDrawable();
3221            if (badge == null) {
3222                return null;
3223            }
3224            final int size = mContext.getResources().getDimensionPixelSize(
3225                    R.dimen.notification_badge_size);
3226            Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
3227            Canvas canvas = new Canvas(bitmap);
3228            badge.setBounds(0, 0, size, size);
3229            badge.draw(canvas);
3230            return bitmap;
3231        }
3232
3233        private void bindProfileBadge(RemoteViews contentView) {
3234            Bitmap profileBadge = getProfileBadge();
3235
3236            if (profileBadge != null) {
3237                contentView.setImageViewBitmap(R.id.profile_badge, profileBadge);
3238                contentView.setViewVisibility(R.id.profile_badge, View.VISIBLE);
3239            }
3240        }
3241
3242        private void resetStandardTemplate(RemoteViews contentView) {
3243            resetNotificationHeader(contentView);
3244            resetContentMargins(contentView);
3245            contentView.setViewVisibility(R.id.right_icon, View.GONE);
3246            contentView.setViewVisibility(R.id.title, View.GONE);
3247            contentView.setTextViewText(R.id.title, null);
3248            contentView.setViewVisibility(R.id.text, View.GONE);
3249            contentView.setTextViewText(R.id.text, null);
3250            contentView.setViewVisibility(R.id.text_line_1, View.GONE);
3251            contentView.setTextViewText(R.id.text_line_1, null);
3252            contentView.setViewVisibility(R.id.progress, View.GONE);
3253        }
3254
3255        /**
3256         * Resets the notification header to its original state
3257         */
3258        private void resetNotificationHeader(RemoteViews contentView) {
3259            contentView.setImageViewResource(R.id.icon, 0);
3260            contentView.setBoolean(R.id.notification_header, "setExpanded", false);
3261            contentView.setTextViewText(R.id.app_name_text, null);
3262            contentView.setViewVisibility(R.id.chronometer, View.GONE);
3263            contentView.setViewVisibility(R.id.header_text, View.GONE);
3264            contentView.setTextViewText(R.id.header_text, null);
3265            contentView.setViewVisibility(R.id.header_text_divider, View.GONE);
3266            contentView.setViewVisibility(R.id.time_divider, View.GONE);
3267            contentView.setViewVisibility(R.id.time, View.GONE);
3268            contentView.setImageViewIcon(R.id.profile_badge, null);
3269            contentView.setViewVisibility(R.id.profile_badge, View.GONE);
3270        }
3271
3272        private void resetContentMargins(RemoteViews contentView) {
3273            contentView.setViewLayoutMarginEndDimen(R.id.line1, 0);
3274            contentView.setViewLayoutMarginEndDimen(R.id.text, 0);
3275        }
3276
3277        private RemoteViews applyStandardTemplate(int resId) {
3278            return applyStandardTemplate(resId, true /* hasProgress */);
3279        }
3280
3281        /**
3282         * @param hasProgress whether the progress bar should be shown and set
3283         */
3284        private RemoteViews applyStandardTemplate(int resId, boolean hasProgress) {
3285            final Bundle ex = mN.extras;
3286
3287            CharSequence title = processLegacyText(ex.getCharSequence(EXTRA_TITLE));
3288            CharSequence text = processLegacyText(ex.getCharSequence(EXTRA_TEXT));
3289            return applyStandardTemplate(resId, hasProgress, title, text);
3290        }
3291
3292        /**
3293         * @param hasProgress whether the progress bar should be shown and set
3294         */
3295        private RemoteViews applyStandardTemplate(int resId, boolean hasProgress,
3296                CharSequence title, CharSequence text) {
3297            RemoteViews contentView = new BuilderRemoteViews(mContext.getApplicationInfo(), resId);
3298
3299            resetStandardTemplate(contentView);
3300
3301            final Bundle ex = mN.extras;
3302
3303            bindNotificationHeader(contentView);
3304            bindLargeIcon(contentView);
3305            boolean showProgress = handleProgressBar(hasProgress, contentView, ex);
3306            if (title != null) {
3307                contentView.setViewVisibility(R.id.title, View.VISIBLE);
3308                contentView.setTextViewText(R.id.title, title);
3309                contentView.setViewLayoutWidth(R.id.title, showProgress
3310                        ? ViewGroup.LayoutParams.WRAP_CONTENT
3311                        : ViewGroup.LayoutParams.MATCH_PARENT);
3312            }
3313            if (text != null) {
3314                int textId = showProgress ? com.android.internal.R.id.text_line_1
3315                        : com.android.internal.R.id.text;
3316                contentView.setTextViewText(textId, text);
3317                contentView.setViewVisibility(textId, View.VISIBLE);
3318            }
3319
3320            setContentMinHeight(contentView, showProgress || mN.hasLargeIcon());
3321
3322            return contentView;
3323        }
3324
3325        /**
3326         * @param remoteView the remote view to update the minheight in
3327         * @param hasMinHeight does it have a mimHeight
3328         * @hide
3329         */
3330        void setContentMinHeight(RemoteViews remoteView, boolean hasMinHeight) {
3331            int minHeight = 0;
3332            if (hasMinHeight) {
3333                // we need to set the minHeight of the notification
3334                minHeight = mContext.getResources().getDimensionPixelSize(
3335                        com.android.internal.R.dimen.notification_min_content_height);
3336            }
3337            remoteView.setInt(R.id.notification_main_column, "setMinimumHeight", minHeight);
3338        }
3339
3340        private boolean handleProgressBar(boolean hasProgress, RemoteViews contentView, Bundle ex) {
3341            final int max = ex.getInt(EXTRA_PROGRESS_MAX, 0);
3342            final int progress = ex.getInt(EXTRA_PROGRESS, 0);
3343            final boolean ind = ex.getBoolean(EXTRA_PROGRESS_INDETERMINATE);
3344            if (hasProgress && (max != 0 || ind)) {
3345                contentView.setViewVisibility(com.android.internal.R.id.progress, View.VISIBLE);
3346                contentView.setProgressBar(
3347                        R.id.progress, max, progress, ind);
3348                contentView.setProgressBackgroundTintList(
3349                        R.id.progress, ColorStateList.valueOf(mContext.getColor(
3350                                R.color.notification_progress_background_color)));
3351                if (mN.color != COLOR_DEFAULT) {
3352                    ColorStateList colorStateList = ColorStateList.valueOf(resolveContrastColor());
3353                    contentView.setProgressTintList(R.id.progress, colorStateList);
3354                    contentView.setProgressIndeterminateTintList(R.id.progress, colorStateList);
3355                }
3356                return true;
3357            } else {
3358                contentView.setViewVisibility(R.id.progress, View.GONE);
3359                return false;
3360            }
3361        }
3362
3363        private void bindLargeIcon(RemoteViews contentView) {
3364            if (mN.mLargeIcon == null && mN.largeIcon != null) {
3365                mN.mLargeIcon = Icon.createWithBitmap(mN.largeIcon);
3366            }
3367            if (mN.mLargeIcon != null) {
3368                contentView.setViewVisibility(R.id.right_icon, View.VISIBLE);
3369                contentView.setImageViewIcon(R.id.right_icon, mN.mLargeIcon);
3370                processLargeLegacyIcon(mN.mLargeIcon, contentView);
3371                int endMargin = R.dimen.notification_content_picture_margin;
3372                contentView.setViewLayoutMarginEndDimen(R.id.line1, endMargin);
3373                contentView.setViewLayoutMarginEndDimen(R.id.text, endMargin);
3374                contentView.setViewLayoutMarginEndDimen(R.id.progress, endMargin);
3375            }
3376        }
3377
3378        private void bindNotificationHeader(RemoteViews contentView) {
3379            bindSmallIcon(contentView);
3380            bindHeaderAppName(contentView);
3381            bindHeaderText(contentView);
3382            bindHeaderChronometerAndTime(contentView);
3383            bindExpandButton(contentView);
3384            bindProfileBadge(contentView);
3385        }
3386
3387        private void bindExpandButton(RemoteViews contentView) {
3388            contentView.setDrawableParameters(R.id.expand_button, false, -1, resolveContrastColor(),
3389                    PorterDuff.Mode.SRC_ATOP, -1);
3390            contentView.setInt(R.id.notification_header, "setOriginalNotificationColor",
3391                    resolveContrastColor());
3392        }
3393
3394        private void bindHeaderChronometerAndTime(RemoteViews contentView) {
3395            if (showsTimeOrChronometer()) {
3396                contentView.setViewVisibility(R.id.time_divider, View.VISIBLE);
3397                if (mN.extras.getBoolean(EXTRA_SHOW_CHRONOMETER)) {
3398                    contentView.setViewVisibility(R.id.chronometer, View.VISIBLE);
3399                    contentView.setLong(R.id.chronometer, "setBase",
3400                            mN.when + (SystemClock.elapsedRealtime() - System.currentTimeMillis()));
3401                    contentView.setBoolean(R.id.chronometer, "setStarted", true);
3402                    boolean countsDown = mN.extras.getBoolean(EXTRA_CHRONOMETER_COUNT_DOWN);
3403                    contentView.setChronometerCountDown(R.id.chronometer, countsDown);
3404                } else {
3405                    contentView.setViewVisibility(R.id.time, View.VISIBLE);
3406                    contentView.setLong(R.id.time, "setTime", mN.when);
3407                }
3408            } else {
3409                // We still want a time to be set but gone, such that we can show and hide it
3410                // on demand in case it's a child notification without anything in the header
3411                contentView.setLong(R.id.time, "setTime", mN.when != 0 ? mN.when : mN.creationTime);
3412            }
3413        }
3414
3415        private void bindHeaderText(RemoteViews contentView) {
3416            CharSequence headerText = mN.extras.getCharSequence(EXTRA_SUB_TEXT);
3417            if (headerText == null && mStyle != null && mStyle.mSummaryTextSet
3418                    && mStyle.hasSummaryInHeader()) {
3419                headerText = mStyle.mSummaryText;
3420            }
3421            if (headerText == null
3422                    && mContext.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N
3423                    && mN.extras.getCharSequence(EXTRA_INFO_TEXT) != null) {
3424                headerText = mN.extras.getCharSequence(EXTRA_INFO_TEXT);
3425            }
3426            if (headerText != null) {
3427                // TODO: Remove the span entirely to only have the string with propper formating.
3428                contentView.setTextViewText(R.id.header_text, processLegacyText(headerText));
3429                contentView.setViewVisibility(R.id.header_text, View.VISIBLE);
3430                contentView.setViewVisibility(R.id.header_text_divider, View.VISIBLE);
3431            }
3432        }
3433
3434        /**
3435         * @hide
3436         */
3437        public String loadHeaderAppName() {
3438            CharSequence name = null;
3439            final PackageManager pm = mContext.getPackageManager();
3440            if (mN.extras.containsKey(EXTRA_SUBSTITUTE_APP_NAME)) {
3441                // only system packages which lump together a bunch of unrelated stuff
3442                // may substitute a different name to make the purpose of the
3443                // notification more clear. the correct package label should always
3444                // be accessible via SystemUI.
3445                final String pkg = mContext.getPackageName();
3446                final String subName = mN.extras.getString(EXTRA_SUBSTITUTE_APP_NAME);
3447                if (PackageManager.PERMISSION_GRANTED == pm.checkPermission(
3448                        android.Manifest.permission.SUBSTITUTE_NOTIFICATION_APP_NAME, pkg)) {
3449                    name = subName;
3450                } else {
3451                    Log.w(TAG, "warning: pkg "
3452                            + pkg + " attempting to substitute app name '" + subName
3453                            + "' without holding perm "
3454                            + android.Manifest.permission.SUBSTITUTE_NOTIFICATION_APP_NAME);
3455                }
3456            }
3457            if (TextUtils.isEmpty(name)) {
3458                name = pm.getApplicationLabel(mContext.getApplicationInfo());
3459            }
3460            if (TextUtils.isEmpty(name)) {
3461                // still nothing?
3462                return null;
3463            }
3464
3465            return String.valueOf(name);
3466        }
3467        private void bindHeaderAppName(RemoteViews contentView) {
3468            contentView.setTextViewText(R.id.app_name_text, loadHeaderAppName());
3469            contentView.setTextColor(R.id.app_name_text, resolveContrastColor());
3470        }
3471
3472        private void bindSmallIcon(RemoteViews contentView) {
3473            if (mN.mSmallIcon == null && mN.icon != 0) {
3474                mN.mSmallIcon = Icon.createWithResource(mContext, mN.icon);
3475            }
3476            contentView.setImageViewIcon(R.id.icon, mN.mSmallIcon);
3477            processSmallIconColor(mN.mSmallIcon, contentView);
3478        }
3479
3480        /**
3481         * @return true if the built notification will show the time or the chronometer; false
3482         *         otherwise
3483         */
3484        private boolean showsTimeOrChronometer() {
3485            return mN.showsTime() || mN.showsChronometer();
3486        }
3487
3488        private void resetStandardTemplateWithActions(RemoteViews big) {
3489            // actions_container is only reset when there are no actions to avoid focus issues with
3490            // remote inputs.
3491            big.setViewVisibility(R.id.actions, View.GONE);
3492            big.removeAllViews(R.id.actions);
3493
3494            big.setViewVisibility(R.id.notification_material_reply_container, View.GONE);
3495            big.setTextViewText(R.id.notification_material_reply_text_1, null);
3496
3497            big.setViewVisibility(R.id.notification_material_reply_text_2, View.GONE);
3498            big.setTextViewText(R.id.notification_material_reply_text_2, null);
3499            big.setViewVisibility(R.id.notification_material_reply_text_3, View.GONE);
3500            big.setTextViewText(R.id.notification_material_reply_text_3, null);
3501
3502            big.setViewLayoutMarginBottomDimen(R.id.notification_action_list_margin_target, 0);
3503        }
3504
3505        private RemoteViews applyStandardTemplateWithActions(int layoutId) {
3506            final Bundle ex = mN.extras;
3507
3508            CharSequence title = processLegacyText(ex.getCharSequence(EXTRA_TITLE));
3509            CharSequence text = processLegacyText(ex.getCharSequence(EXTRA_TEXT));
3510            return applyStandardTemplateWithActions(layoutId, true /* hasProgress */, title, text);
3511        }
3512
3513        private RemoteViews applyStandardTemplateWithActions(int layoutId, boolean hasProgress,
3514                CharSequence title, CharSequence text) {
3515            RemoteViews big = applyStandardTemplate(layoutId, hasProgress, title, text);
3516
3517            resetStandardTemplateWithActions(big);
3518
3519            boolean validRemoteInput = false;
3520
3521            int N = mActions.size();
3522            if (N > 0) {
3523                big.setViewVisibility(R.id.actions_container, View.VISIBLE);
3524                big.setViewVisibility(R.id.actions, View.VISIBLE);
3525                big.setViewLayoutMarginBottomDimen(R.id.notification_action_list_margin_target,
3526                        R.dimen.notification_action_list_height);
3527                if (N>MAX_ACTION_BUTTONS) N=MAX_ACTION_BUTTONS;
3528                for (int i=0; i<N; i++) {
3529                    Action action = mActions.get(i);
3530                    validRemoteInput |= hasValidRemoteInput(action);
3531
3532                    final RemoteViews button = generateActionButton(action);
3533                    big.addView(R.id.actions, button);
3534                }
3535            } else {
3536                big.setViewVisibility(R.id.actions_container, View.GONE);
3537            }
3538
3539            CharSequence[] replyText = mN.extras.getCharSequenceArray(EXTRA_REMOTE_INPUT_HISTORY);
3540            if (validRemoteInput && replyText != null
3541                    && replyText.length > 0 && !TextUtils.isEmpty(replyText[0])) {
3542                big.setViewVisibility(R.id.notification_material_reply_container, View.VISIBLE);
3543                big.setTextViewText(R.id.notification_material_reply_text_1, replyText[0]);
3544
3545                if (replyText.length > 1 && !TextUtils.isEmpty(replyText[1])) {
3546                    big.setViewVisibility(R.id.notification_material_reply_text_2, View.VISIBLE);
3547                    big.setTextViewText(R.id.notification_material_reply_text_2, replyText[1]);
3548
3549                    if (replyText.length > 2 && !TextUtils.isEmpty(replyText[2])) {
3550                        big.setViewVisibility(
3551                                R.id.notification_material_reply_text_3, View.VISIBLE);
3552                        big.setTextViewText(R.id.notification_material_reply_text_3, replyText[2]);
3553                    }
3554                }
3555            }
3556
3557            return big;
3558        }
3559
3560        private boolean hasValidRemoteInput(Action action) {
3561            if (TextUtils.isEmpty(action.title) || action.actionIntent == null) {
3562                // Weird actions
3563                return false;
3564            }
3565
3566            RemoteInput[] remoteInputs = action.getRemoteInputs();
3567            if (remoteInputs == null) {
3568                return false;
3569            }
3570
3571            for (RemoteInput r : remoteInputs) {
3572                CharSequence[] choices = r.getChoices();
3573                if (r.getAllowFreeFormInput() || (choices != null && choices.length != 0)) {
3574                    return true;
3575                }
3576            }
3577            return false;
3578        }
3579
3580        /**
3581         * Construct a RemoteViews for the final 1U notification layout. In order:
3582         *   1. Custom contentView from the caller
3583         *   2. Style's proposed content view
3584         *   3. Standard template view
3585         */
3586        public RemoteViews createContentView() {
3587            if (mN.contentView != null && (mStyle == null || !mStyle.displayCustomViewInline())) {
3588                return mN.contentView;
3589            } else if (mStyle != null) {
3590                final RemoteViews styleView = mStyle.makeContentView();
3591                if (styleView != null) {
3592                    return styleView;
3593                }
3594            }
3595            return applyStandardTemplate(getBaseLayoutResource());
3596        }
3597
3598        /**
3599         * Construct a RemoteViews for the final big notification layout.
3600         */
3601        public RemoteViews createBigContentView() {
3602            RemoteViews result = null;
3603            if (mN.bigContentView != null
3604                    && (mStyle == null || !mStyle.displayCustomViewInline())) {
3605                return mN.bigContentView;
3606            } else if (mStyle != null) {
3607                result = mStyle.makeBigContentView();
3608                hideLine1Text(result);
3609            } else if (mActions.size() != 0) {
3610                result = applyStandardTemplateWithActions(getBigBaseLayoutResource());
3611            }
3612            adaptNotificationHeaderForBigContentView(result);
3613            return result;
3614        }
3615
3616        /**
3617         * Construct a RemoteViews for the final notification header only
3618         *
3619         * @hide
3620         */
3621        public RemoteViews makeNotificationHeader() {
3622            RemoteViews header = new BuilderRemoteViews(mContext.getApplicationInfo(),
3623                    R.layout.notification_template_header);
3624            resetNotificationHeader(header);
3625            bindNotificationHeader(header);
3626            return header;
3627        }
3628
3629        private void hideLine1Text(RemoteViews result) {
3630            if (result != null) {
3631                result.setViewVisibility(R.id.text_line_1, View.GONE);
3632            }
3633        }
3634
3635        private void adaptNotificationHeaderForBigContentView(RemoteViews result) {
3636            if (result != null) {
3637                result.setBoolean(R.id.notification_header, "setExpanded", true);
3638            }
3639        }
3640
3641        /**
3642         * Construct a RemoteViews for the final heads-up notification layout.
3643         */
3644        public RemoteViews createHeadsUpContentView() {
3645            if (mN.headsUpContentView != null
3646                    && (mStyle == null ||  !mStyle.displayCustomViewInline())) {
3647                return mN.headsUpContentView;
3648            } else if (mStyle != null) {
3649                    final RemoteViews styleView = mStyle.makeHeadsUpContentView();
3650                    if (styleView != null) {
3651                        return styleView;
3652                    }
3653            } else if (mActions.size() == 0) {
3654                return null;
3655            }
3656
3657            return applyStandardTemplateWithActions(getBigBaseLayoutResource());
3658        }
3659
3660        /**
3661         * Construct a RemoteViews for the display in public contexts like on the lockscreen.
3662         *
3663         * @hide
3664         */
3665        public RemoteViews makePublicContentView() {
3666            if (mN.publicVersion != null) {
3667                final Builder builder = recoverBuilder(mContext, mN.publicVersion);
3668                return builder.createContentView();
3669            }
3670            Bundle savedBundle = mN.extras;
3671            Style style = mStyle;
3672            mStyle = null;
3673            Icon largeIcon = mN.mLargeIcon;
3674            mN.mLargeIcon = null;
3675            Bitmap largeIconLegacy = mN.largeIcon;
3676            mN.largeIcon = null;
3677            Bundle publicExtras = new Bundle();
3678            publicExtras.putBoolean(EXTRA_SHOW_WHEN,
3679                    savedBundle.getBoolean(EXTRA_SHOW_WHEN));
3680            publicExtras.putBoolean(EXTRA_SHOW_CHRONOMETER,
3681                    savedBundle.getBoolean(EXTRA_SHOW_CHRONOMETER));
3682            publicExtras.putBoolean(EXTRA_CHRONOMETER_COUNT_DOWN,
3683                    savedBundle.getBoolean(EXTRA_CHRONOMETER_COUNT_DOWN));
3684            publicExtras.putCharSequence(EXTRA_TITLE,
3685                    mContext.getString(R.string.notification_hidden_text));
3686            mN.extras = publicExtras;
3687            final RemoteViews publicView = applyStandardTemplate(getBaseLayoutResource());
3688            mN.extras = savedBundle;
3689            mN.mLargeIcon = largeIcon;
3690            mN.largeIcon = largeIconLegacy;
3691            mStyle = style;
3692            return publicView;
3693        }
3694
3695
3696
3697        private RemoteViews generateActionButton(Action action) {
3698            final boolean tombstone = (action.actionIntent == null);
3699            RemoteViews button = new BuilderRemoteViews(mContext.getApplicationInfo(),
3700                    tombstone ? getActionTombstoneLayoutResource()
3701                              : getActionLayoutResource());
3702            final Icon ai = action.getIcon();
3703            button.setTextViewText(R.id.action0, processLegacyText(action.title));
3704            if (!tombstone) {
3705                button.setOnClickPendingIntent(R.id.action0, action.actionIntent);
3706            }
3707            button.setContentDescription(R.id.action0, action.title);
3708            if (action.mRemoteInputs != null) {
3709                button.setRemoteInputs(R.id.action0, action.mRemoteInputs);
3710            }
3711            if (mN.color != COLOR_DEFAULT) {
3712                button.setTextColor(R.id.action0, resolveContrastColor());
3713            }
3714            return button;
3715        }
3716
3717        /**
3718         * @return Whether we are currently building a notification from a legacy (an app that
3719         *         doesn't create material notifications by itself) app.
3720         */
3721        private boolean isLegacy() {
3722            return getColorUtil() != null;
3723        }
3724
3725        private CharSequence processLegacyText(CharSequence charSequence) {
3726            if (isLegacy()) {
3727                return getColorUtil().invertCharSequenceColors(charSequence);
3728            } else {
3729                return charSequence;
3730            }
3731        }
3732
3733        /**
3734         * Apply any necessariy colors to the small icon
3735         */
3736        private void processSmallIconColor(Icon smallIcon, RemoteViews contentView) {
3737            boolean colorable = !isLegacy() || getColorUtil().isGrayscaleIcon(mContext, smallIcon);
3738            if (colorable) {
3739                contentView.setDrawableParameters(R.id.icon, false, -1, resolveContrastColor(),
3740                        PorterDuff.Mode.SRC_ATOP, -1);
3741
3742            }
3743            contentView.setInt(R.id.notification_header, "setOriginalIconColor",
3744                    colorable ? resolveContrastColor() : NotificationHeaderView.NO_COLOR);
3745        }
3746
3747        /**
3748         * Make the largeIcon dark if it's a fake smallIcon (that is,
3749         * if it's grayscale).
3750         */
3751        // TODO: also check bounds, transparency, that sort of thing.
3752        private void processLargeLegacyIcon(Icon largeIcon, RemoteViews contentView) {
3753            if (largeIcon != null && isLegacy()
3754                    && getColorUtil().isGrayscaleIcon(mContext, largeIcon)) {
3755                // resolve color will fall back to the default when legacy
3756                contentView.setDrawableParameters(R.id.icon, false, -1, resolveContrastColor(),
3757                        PorterDuff.Mode.SRC_ATOP, -1);
3758            }
3759        }
3760
3761        private void sanitizeColor() {
3762            if (mN.color != COLOR_DEFAULT) {
3763                mN.color |= 0xFF000000; // no alpha for custom colors
3764            }
3765        }
3766
3767        int resolveContrastColor() {
3768            if (mCachedContrastColorIsFor == mN.color && mCachedContrastColor != COLOR_INVALID) {
3769                return mCachedContrastColor;
3770            }
3771            final int contrasted = NotificationColorUtil.resolveContrastColor(mContext, mN.color);
3772
3773            mCachedContrastColorIsFor = mN.color;
3774            return mCachedContrastColor = contrasted;
3775        }
3776
3777        /**
3778         * Apply the unstyled operations and return a new {@link Notification} object.
3779         * @hide
3780         */
3781        public Notification buildUnstyled() {
3782            if (mActions.size() > 0) {
3783                mN.actions = new Action[mActions.size()];
3784                mActions.toArray(mN.actions);
3785            }
3786            if (!mPersonList.isEmpty()) {
3787                mN.extras.putStringArray(EXTRA_PEOPLE,
3788                        mPersonList.toArray(new String[mPersonList.size()]));
3789            }
3790            if (mN.bigContentView != null || mN.contentView != null
3791                    || mN.headsUpContentView != null) {
3792                mN.extras.putBoolean(EXTRA_CONTAINS_CUSTOM_VIEW, true);
3793            }
3794            return mN;
3795        }
3796
3797        /**
3798         * Creates a Builder from an existing notification so further changes can be made.
3799         * @param context The context for your application / activity.
3800         * @param n The notification to create a Builder from.
3801         */
3802        public static Notification.Builder recoverBuilder(Context context, Notification n) {
3803            // Re-create notification context so we can access app resources.
3804            ApplicationInfo applicationInfo = n.extras.getParcelable(
3805                    EXTRA_BUILDER_APPLICATION_INFO);
3806            Context builderContext;
3807            if (applicationInfo != null) {
3808                try {
3809                    builderContext = context.createApplicationContext(applicationInfo,
3810                            Context.CONTEXT_RESTRICTED);
3811                } catch (NameNotFoundException e) {
3812                    Log.e(TAG, "ApplicationInfo " + applicationInfo + " not found");
3813                    builderContext = context;  // try with our context
3814                }
3815            } else {
3816                builderContext = context; // try with given context
3817            }
3818
3819            return new Builder(builderContext, n);
3820        }
3821
3822        private static Class<? extends Style> getNotificationStyleClass(String templateClass) {
3823            Class<? extends Style>[] classes = new Class[] {
3824                    BigTextStyle.class, BigPictureStyle.class, InboxStyle.class, MediaStyle.class,
3825                    DecoratedCustomViewStyle.class, DecoratedMediaCustomViewStyle.class,
3826                    MessagingStyle.class };
3827            for (Class<? extends Style> innerClass : classes) {
3828                if (templateClass.equals(innerClass.getName())) {
3829                    return innerClass;
3830                }
3831            }
3832            return null;
3833        }
3834
3835        /**
3836         * @deprecated Use {@link #build()} instead.
3837         */
3838        @Deprecated
3839        public Notification getNotification() {
3840            return build();
3841        }
3842
3843        /**
3844         * Combine all of the options that have been set and return a new {@link Notification}
3845         * object.
3846         */
3847        public Notification build() {
3848            // first, add any extras from the calling code
3849            if (mUserExtras != null) {
3850                mN.extras = getAllExtras();
3851            }
3852
3853            mN.creationTime = System.currentTimeMillis();
3854
3855            // lazy stuff from mContext; see comment in Builder(Context, Notification)
3856            Notification.addFieldsFromContext(mContext, mN);
3857
3858            buildUnstyled();
3859
3860            if (mStyle != null) {
3861                mStyle.buildStyled(mN);
3862            }
3863
3864            if (mContext.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N
3865                    && (mStyle == null || !mStyle.displayCustomViewInline())) {
3866                if (mN.contentView == null) {
3867                    mN.contentView = createContentView();
3868                    mN.extras.putInt(EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT,
3869                            mN.contentView.getSequenceNumber());
3870                }
3871                if (mN.bigContentView == null) {
3872                    mN.bigContentView = createBigContentView();
3873                    if (mN.bigContentView != null) {
3874                        mN.extras.putInt(EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT,
3875                                mN.bigContentView.getSequenceNumber());
3876                    }
3877                }
3878                if (mN.headsUpContentView == null) {
3879                    mN.headsUpContentView = createHeadsUpContentView();
3880                    if (mN.headsUpContentView != null) {
3881                        mN.extras.putInt(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT,
3882                                mN.headsUpContentView.getSequenceNumber());
3883                    }
3884                }
3885            }
3886
3887            if ((mN.defaults & DEFAULT_LIGHTS) != 0) {
3888                mN.flags |= FLAG_SHOW_LIGHTS;
3889            }
3890
3891            return mN;
3892        }
3893
3894        /**
3895         * Apply this Builder to an existing {@link Notification} object.
3896         *
3897         * @hide
3898         */
3899        public Notification buildInto(Notification n) {
3900            build().cloneInto(n, true);
3901            return n;
3902        }
3903
3904        /**
3905         * Removes RemoteViews that were created for compatibility from {@param n}, if they did not
3906         * change.
3907         *
3908         * @return {@param n}, if no stripping is needed, otherwise a stripped clone of {@param n}.
3909         *
3910         * @hide
3911         */
3912        public static Notification maybeCloneStrippedForDelivery(Notification n) {
3913            String templateClass = n.extras.getString(EXTRA_TEMPLATE);
3914
3915            // Only strip views for known Styles because we won't know how to
3916            // re-create them otherwise.
3917            if (!TextUtils.isEmpty(templateClass)
3918                    && getNotificationStyleClass(templateClass) == null) {
3919                return n;
3920            }
3921
3922            // Only strip unmodified BuilderRemoteViews.
3923            boolean stripContentView = n.contentView instanceof BuilderRemoteViews &&
3924                    n.extras.getInt(EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT, -1) ==
3925                            n.contentView.getSequenceNumber();
3926            boolean stripBigContentView = n.bigContentView instanceof BuilderRemoteViews &&
3927                    n.extras.getInt(EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT, -1) ==
3928                            n.bigContentView.getSequenceNumber();
3929            boolean stripHeadsUpContentView = n.headsUpContentView instanceof BuilderRemoteViews &&
3930                    n.extras.getInt(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT, -1) ==
3931                            n.headsUpContentView.getSequenceNumber();
3932
3933            // Nothing to do here, no need to clone.
3934            if (!stripContentView && !stripBigContentView && !stripHeadsUpContentView) {
3935                return n;
3936            }
3937
3938            Notification clone = n.clone();
3939            if (stripContentView) {
3940                clone.contentView = null;
3941                clone.extras.remove(EXTRA_REBUILD_CONTENT_VIEW_ACTION_COUNT);
3942            }
3943            if (stripBigContentView) {
3944                clone.bigContentView = null;
3945                clone.extras.remove(EXTRA_REBUILD_BIG_CONTENT_VIEW_ACTION_COUNT);
3946            }
3947            if (stripHeadsUpContentView) {
3948                clone.headsUpContentView = null;
3949                clone.extras.remove(EXTRA_REBUILD_HEADS_UP_CONTENT_VIEW_ACTION_COUNT);
3950            }
3951            return clone;
3952        }
3953
3954        private int getBaseLayoutResource() {
3955            return R.layout.notification_template_material_base;
3956        }
3957
3958        private int getBigBaseLayoutResource() {
3959            return R.layout.notification_template_material_big_base;
3960        }
3961
3962        private int getBigPictureLayoutResource() {
3963            return R.layout.notification_template_material_big_picture;
3964        }
3965
3966        private int getBigTextLayoutResource() {
3967            return R.layout.notification_template_material_big_text;
3968        }
3969
3970        private int getInboxLayoutResource() {
3971            return R.layout.notification_template_material_inbox;
3972        }
3973
3974        private int getMessagingLayoutResource() {
3975            return R.layout.notification_template_material_messaging;
3976        }
3977
3978        private int getActionLayoutResource() {
3979            return R.layout.notification_material_action;
3980        }
3981
3982        private int getActionTombstoneLayoutResource() {
3983            return R.layout.notification_material_action_tombstone;
3984        }
3985    }
3986
3987    private boolean hasLargeIcon() {
3988        return mLargeIcon != null || largeIcon != null;
3989    }
3990
3991    /**
3992     * @return true if the notification will show the time; false otherwise
3993     * @hide
3994     */
3995    public boolean showsTime() {
3996        return when != 0 && extras.getBoolean(EXTRA_SHOW_WHEN);
3997    }
3998
3999    /**
4000     * @return true if the notification will show a chronometer; false otherwise
4001     * @hide
4002     */
4003    public boolean showsChronometer() {
4004        return when != 0 && extras.getBoolean(EXTRA_SHOW_CHRONOMETER);
4005    }
4006
4007    /**
4008     * An object that can apply a rich notification style to a {@link Notification.Builder}
4009     * object.
4010     */
4011    public static abstract class Style {
4012        private CharSequence mBigContentTitle;
4013
4014        /**
4015         * @hide
4016         */
4017        protected CharSequence mSummaryText = null;
4018
4019        /**
4020         * @hide
4021         */
4022        protected boolean mSummaryTextSet = false;
4023
4024        protected Builder mBuilder;
4025
4026        /**
4027         * Overrides ContentTitle in the big form of the template.
4028         * This defaults to the value passed to setContentTitle().
4029         */
4030        protected void internalSetBigContentTitle(CharSequence title) {
4031            mBigContentTitle = title;
4032        }
4033
4034        /**
4035         * Set the first line of text after the detail section in the big form of the template.
4036         */
4037        protected void internalSetSummaryText(CharSequence cs) {
4038            mSummaryText = cs;
4039            mSummaryTextSet = true;
4040        }
4041
4042        public void setBuilder(Builder builder) {
4043            if (mBuilder != builder) {
4044                mBuilder = builder;
4045                if (mBuilder != null) {
4046                    mBuilder.setStyle(this);
4047                }
4048            }
4049        }
4050
4051        protected void checkBuilder() {
4052            if (mBuilder == null) {
4053                throw new IllegalArgumentException("Style requires a valid Builder object");
4054            }
4055        }
4056
4057        protected RemoteViews getStandardView(int layoutId) {
4058            checkBuilder();
4059
4060            // Nasty.
4061            CharSequence oldBuilderContentTitle =
4062                    mBuilder.getAllExtras().getCharSequence(EXTRA_TITLE);
4063            if (mBigContentTitle != null) {
4064                mBuilder.setContentTitle(mBigContentTitle);
4065            }
4066
4067            RemoteViews contentView = mBuilder.applyStandardTemplateWithActions(layoutId);
4068
4069            mBuilder.getAllExtras().putCharSequence(EXTRA_TITLE, oldBuilderContentTitle);
4070
4071            if (mBigContentTitle != null && mBigContentTitle.equals("")) {
4072                contentView.setViewVisibility(R.id.line1, View.GONE);
4073            } else {
4074                contentView.setViewVisibility(R.id.line1, View.VISIBLE);
4075            }
4076
4077            return contentView;
4078        }
4079
4080        /**
4081         * Construct a Style-specific RemoteViews for the final 1U notification layout.
4082         * The default implementation has nothing additional to add.
4083         * @hide
4084         */
4085        public RemoteViews makeContentView() {
4086            return null;
4087        }
4088
4089        /**
4090         * Construct a Style-specific RemoteViews for the final big notification layout.
4091         * @hide
4092         */
4093        public RemoteViews makeBigContentView() {
4094            return null;
4095        }
4096
4097        /**
4098         * Construct a Style-specific RemoteViews for the final HUN layout.
4099         * @hide
4100         */
4101        public RemoteViews makeHeadsUpContentView() {
4102            return null;
4103        }
4104
4105        /**
4106         * Apply any style-specific extras to this notification before shipping it out.
4107         * @hide
4108         */
4109        public void addExtras(Bundle extras) {
4110            if (mSummaryTextSet) {
4111                extras.putCharSequence(EXTRA_SUMMARY_TEXT, mSummaryText);
4112            }
4113            if (mBigContentTitle != null) {
4114                extras.putCharSequence(EXTRA_TITLE_BIG, mBigContentTitle);
4115            }
4116            extras.putString(EXTRA_TEMPLATE, this.getClass().getName());
4117        }
4118
4119        /**
4120         * Reconstruct the internal state of this Style object from extras.
4121         * @hide
4122         */
4123        protected void restoreFromExtras(Bundle extras) {
4124            if (extras.containsKey(EXTRA_SUMMARY_TEXT)) {
4125                mSummaryText = extras.getCharSequence(EXTRA_SUMMARY_TEXT);
4126                mSummaryTextSet = true;
4127            }
4128            if (extras.containsKey(EXTRA_TITLE_BIG)) {
4129                mBigContentTitle = extras.getCharSequence(EXTRA_TITLE_BIG);
4130            }
4131        }
4132
4133
4134        /**
4135         * @hide
4136         */
4137        public Notification buildStyled(Notification wip) {
4138            addExtras(wip.extras);
4139            return wip;
4140        }
4141
4142        /**
4143         * @hide
4144         */
4145        public void purgeResources() {}
4146
4147        /**
4148         * Calls {@link android.app.Notification.Builder#build()} on the Builder this Style is
4149         * attached to.
4150         *
4151         * @return the fully constructed Notification.
4152         */
4153        public Notification build() {
4154            checkBuilder();
4155            return mBuilder.build();
4156        }
4157
4158        /**
4159         * @hide
4160         * @return true if the style positions the progress bar on the second line; false if the
4161         *         style hides the progress bar
4162         */
4163        protected boolean hasProgress() {
4164            return true;
4165        }
4166
4167        /**
4168         * @hide
4169         * @return Whether we should put the summary be put into the notification header
4170         */
4171        public boolean hasSummaryInHeader() {
4172            return true;
4173        }
4174
4175        /**
4176         * @hide
4177         * @return Whether custom content views are displayed inline in the style
4178         */
4179        public boolean displayCustomViewInline() {
4180            return false;
4181        }
4182    }
4183
4184    /**
4185     * Helper class for generating large-format notifications that include a large image attachment.
4186     *
4187     * Here's how you'd set the <code>BigPictureStyle</code> on a notification:
4188     * <pre class="prettyprint">
4189     * Notification notif = new Notification.Builder(mContext)
4190     *     .setContentTitle(&quot;New photo from &quot; + sender.toString())
4191     *     .setContentText(subject)
4192     *     .setSmallIcon(R.drawable.new_post)
4193     *     .setLargeIcon(aBitmap)
4194     *     .setStyle(new Notification.BigPictureStyle()
4195     *         .bigPicture(aBigBitmap))
4196     *     .build();
4197     * </pre>
4198     *
4199     * @see Notification#bigContentView
4200     */
4201    public static class BigPictureStyle extends Style {
4202        private Bitmap mPicture;
4203        private Icon mBigLargeIcon;
4204        private boolean mBigLargeIconSet = false;
4205
4206        public BigPictureStyle() {
4207        }
4208
4209        /**
4210         * @deprecated use {@code BigPictureStyle()}.
4211         */
4212        @Deprecated
4213        public BigPictureStyle(Builder builder) {
4214            setBuilder(builder);
4215        }
4216
4217        /**
4218         * Overrides ContentTitle in the big form of the template.
4219         * This defaults to the value passed to setContentTitle().
4220         */
4221        public BigPictureStyle setBigContentTitle(CharSequence title) {
4222            internalSetBigContentTitle(safeCharSequence(title));
4223            return this;
4224        }
4225
4226        /**
4227         * Set the first line of text after the detail section in the big form of the template.
4228         */
4229        public BigPictureStyle setSummaryText(CharSequence cs) {
4230            internalSetSummaryText(safeCharSequence(cs));
4231            return this;
4232        }
4233
4234        /**
4235         * Provide the bitmap to be used as the payload for the BigPicture notification.
4236         */
4237        public BigPictureStyle bigPicture(Bitmap b) {
4238            mPicture = b;
4239            return this;
4240        }
4241
4242        /**
4243         * Override the large icon when the big notification is shown.
4244         */
4245        public BigPictureStyle bigLargeIcon(Bitmap b) {
4246            return bigLargeIcon(b != null ? Icon.createWithBitmap(b) : null);
4247        }
4248
4249        /**
4250         * Override the large icon when the big notification is shown.
4251         */
4252        public BigPictureStyle bigLargeIcon(Icon icon) {
4253            mBigLargeIconSet = true;
4254            mBigLargeIcon = icon;
4255            return this;
4256        }
4257
4258        /** @hide */
4259        public static final int MIN_ASHMEM_BITMAP_SIZE = 128 * (1 << 10);
4260
4261        /**
4262         * @hide
4263         */
4264        @Override
4265        public void purgeResources() {
4266            super.purgeResources();
4267            if (mPicture != null &&
4268                mPicture.isMutable() &&
4269                mPicture.getAllocationByteCount() >= MIN_ASHMEM_BITMAP_SIZE) {
4270                mPicture = mPicture.createAshmemBitmap();
4271            }
4272            if (mBigLargeIcon != null) {
4273                mBigLargeIcon.convertToAshmem();
4274            }
4275        }
4276
4277        /**
4278         * @hide
4279         */
4280        public RemoteViews makeBigContentView() {
4281            // Replace mN.mLargeIcon with mBigLargeIcon if mBigLargeIconSet
4282            // This covers the following cases:
4283            //   1. mBigLargeIconSet -> mBigLargeIcon (null or non-null) applies, overrides
4284            //          mN.mLargeIcon
4285            //   2. !mBigLargeIconSet -> mN.mLargeIcon applies
4286            Icon oldLargeIcon = null;
4287            if (mBigLargeIconSet) {
4288                oldLargeIcon = mBuilder.mN.mLargeIcon;
4289                mBuilder.mN.mLargeIcon = mBigLargeIcon;
4290            }
4291
4292            RemoteViews contentView = getStandardView(mBuilder.getBigPictureLayoutResource());
4293            if (mSummaryTextSet) {
4294                contentView.setTextViewText(R.id.text, mBuilder.processLegacyText(mSummaryText));
4295                contentView.setViewVisibility(R.id.text, View.VISIBLE);
4296            }
4297            mBuilder.setContentMinHeight(contentView, mBuilder.mN.hasLargeIcon());
4298
4299            if (mBigLargeIconSet) {
4300                mBuilder.mN.mLargeIcon = oldLargeIcon;
4301            }
4302
4303            contentView.setImageViewBitmap(R.id.big_picture, mPicture);
4304            return contentView;
4305        }
4306
4307        /**
4308         * @hide
4309         */
4310        public void addExtras(Bundle extras) {
4311            super.addExtras(extras);
4312
4313            if (mBigLargeIconSet) {
4314                extras.putParcelable(EXTRA_LARGE_ICON_BIG, mBigLargeIcon);
4315            }
4316            extras.putParcelable(EXTRA_PICTURE, mPicture);
4317        }
4318
4319        /**
4320         * @hide
4321         */
4322        @Override
4323        protected void restoreFromExtras(Bundle extras) {
4324            super.restoreFromExtras(extras);
4325
4326            if (extras.containsKey(EXTRA_LARGE_ICON_BIG)) {
4327                mBigLargeIconSet = true;
4328                mBigLargeIcon = extras.getParcelable(EXTRA_LARGE_ICON_BIG);
4329            }
4330            mPicture = extras.getParcelable(EXTRA_PICTURE);
4331        }
4332
4333        /**
4334         * @hide
4335         */
4336        @Override
4337        public boolean hasSummaryInHeader() {
4338            return false;
4339        }
4340    }
4341
4342    /**
4343     * Helper class for generating large-format notifications that include a lot of text.
4344     *
4345     * Here's how you'd set the <code>BigTextStyle</code> on a notification:
4346     * <pre class="prettyprint">
4347     * Notification notif = new Notification.Builder(mContext)
4348     *     .setContentTitle(&quot;New mail from &quot; + sender.toString())
4349     *     .setContentText(subject)
4350     *     .setSmallIcon(R.drawable.new_mail)
4351     *     .setLargeIcon(aBitmap)
4352     *     .setStyle(new Notification.BigTextStyle()
4353     *         .bigText(aVeryLongString))
4354     *     .build();
4355     * </pre>
4356     *
4357     * @see Notification#bigContentView
4358     */
4359    public static class BigTextStyle extends Style {
4360
4361        private static final int MAX_LINES = 13;
4362        private static final int LINES_CONSUMED_BY_ACTIONS = 4;
4363
4364        private CharSequence mBigText;
4365
4366        public BigTextStyle() {
4367        }
4368
4369        /**
4370         * @deprecated use {@code BigTextStyle()}.
4371         */
4372        @Deprecated
4373        public BigTextStyle(Builder builder) {
4374            setBuilder(builder);
4375        }
4376
4377        /**
4378         * Overrides ContentTitle in the big form of the template.
4379         * This defaults to the value passed to setContentTitle().
4380         */
4381        public BigTextStyle setBigContentTitle(CharSequence title) {
4382            internalSetBigContentTitle(safeCharSequence(title));
4383            return this;
4384        }
4385
4386        /**
4387         * Set the first line of text after the detail section in the big form of the template.
4388         */
4389        public BigTextStyle setSummaryText(CharSequence cs) {
4390            internalSetSummaryText(safeCharSequence(cs));
4391            return this;
4392        }
4393
4394        /**
4395         * Provide the longer text to be displayed in the big form of the
4396         * template in place of the content text.
4397         */
4398        public BigTextStyle bigText(CharSequence cs) {
4399            mBigText = safeCharSequence(cs);
4400            return this;
4401        }
4402
4403        /**
4404         * @hide
4405         */
4406        public void addExtras(Bundle extras) {
4407            super.addExtras(extras);
4408
4409            extras.putCharSequence(EXTRA_BIG_TEXT, mBigText);
4410        }
4411
4412        /**
4413         * @hide
4414         */
4415        @Override
4416        protected void restoreFromExtras(Bundle extras) {
4417            super.restoreFromExtras(extras);
4418
4419            mBigText = extras.getCharSequence(EXTRA_BIG_TEXT);
4420        }
4421
4422        /**
4423         * @hide
4424         */
4425        public RemoteViews makeBigContentView() {
4426
4427            // Nasty
4428            CharSequence text = mBuilder.getAllExtras().getCharSequence(EXTRA_TEXT);
4429            mBuilder.getAllExtras().putCharSequence(EXTRA_TEXT, null);
4430
4431            RemoteViews contentView = getStandardView(mBuilder.getBigTextLayoutResource());
4432
4433            mBuilder.getAllExtras().putCharSequence(EXTRA_TEXT, text);
4434
4435            CharSequence bigTextText = mBuilder.processLegacyText(mBigText);
4436            if (TextUtils.isEmpty(bigTextText)) {
4437                // In case the bigtext is null / empty fall back to the normal text to avoid a weird
4438                // experience
4439                bigTextText = mBuilder.processLegacyText(text);
4440            }
4441            applyBigTextContentView(mBuilder, contentView, bigTextText);
4442
4443            return contentView;
4444        }
4445
4446        static void applyBigTextContentView(Builder builder,
4447                RemoteViews contentView, CharSequence bigTextText) {
4448            contentView.setTextViewText(R.id.big_text, bigTextText);
4449            contentView.setViewVisibility(R.id.big_text,
4450                    TextUtils.isEmpty(bigTextText) ? View.GONE : View.VISIBLE);
4451            contentView.setInt(R.id.big_text, "setMaxLines", calculateMaxLines(builder));
4452            contentView.setBoolean(R.id.big_text, "setHasImage", builder.mN.hasLargeIcon());
4453        }
4454
4455        private static int calculateMaxLines(Builder builder) {
4456            int lineCount = MAX_LINES;
4457            boolean hasActions = builder.mActions.size() > 0;
4458            if (hasActions) {
4459                lineCount -= LINES_CONSUMED_BY_ACTIONS;
4460            }
4461            return lineCount;
4462        }
4463    }
4464
4465    /**
4466     * Helper class for generating large-format notifications that include multiple back-and-forth
4467     * messages of varying types between any number of people.
4468     *
4469     * <br>
4470     * If the platform does not provide large-format notifications, this method has no effect. The
4471     * user will always see the normal notification view.
4472     * <br>
4473     * This class is a "rebuilder": It attaches to a Builder object and modifies its behavior, like
4474     * so:
4475     * <pre class="prettyprint">
4476     *
4477     * Notification noti = new Notification.Builder()
4478     *     .setContentTitle(&quot;2 new messages wtih &quot; + sender.toString())
4479     *     .setContentText(subject)
4480     *     .setSmallIcon(R.drawable.new_message)
4481     *     .setLargeIcon(aBitmap)
4482     *     .setStyle(new Notification.MessagingStyle(resources.getString(R.string.reply_name))
4483     *         .addMessage(messages[0].getText(), messages[0].getTime(), messages[0].getSender())
4484     *         .addMessage(messages[1].getText(), messages[1].getTime(), messages[1].getSender()))
4485     *     .build();
4486     * </pre>
4487     */
4488    public static class MessagingStyle extends Style {
4489
4490        /**
4491         * The maximum number of messages that will be retained in the Notification itself (the
4492         * number displayed is up to the platform).
4493         */
4494        public static final int MAXIMUM_RETAINED_MESSAGES = 25;
4495
4496        CharSequence mUserDisplayName;
4497        CharSequence mConversationTitle;
4498        List<Message> mMessages = new ArrayList<>();
4499
4500        MessagingStyle() {
4501        }
4502
4503        /**
4504         * @param userDisplayName the name to be displayed for any replies sent by the user before the
4505         * posting app reposts the notification with those messages after they've been actually
4506         * sent and in previous messages sent by the user added in
4507         * {@link #addMessage(Notification.MessagingStyle.Message)}
4508         */
4509        public MessagingStyle(CharSequence userDisplayName) {
4510            mUserDisplayName = userDisplayName;
4511        }
4512
4513        /**
4514         * Returns the name to be displayed for any replies sent by the user
4515         */
4516        public CharSequence getUserDisplayName() {
4517            return mUserDisplayName;
4518        }
4519
4520        /**
4521         * Sets the title to be displayed on this conversation. This should only be used for
4522         * group messaging and left unset for one-on-one conversations.
4523         * @param conversationTitle
4524         * @return this object for method chaining.
4525         */
4526        public MessagingStyle setConversationTitle(CharSequence conversationTitle) {
4527            mConversationTitle = conversationTitle;
4528            return this;
4529        }
4530
4531        /**
4532         * Return the title to be displayed on this conversation. Can be <code>null</code> and
4533         * should be for one-on-one conversations
4534         */
4535        public CharSequence getConversationTitle() {
4536            return mConversationTitle;
4537        }
4538
4539        /**
4540         * Adds a message for display by this notification. Convenience call for a simple
4541         * {@link Message} in {@link #addMessage(Notification.MessagingStyle.Message)}.
4542         * @param text A {@link CharSequence} to be displayed as the message content
4543         * @param timestamp Time at which the message arrived
4544         * @param sender A {@link CharSequence} to be used for displaying the name of the
4545         * sender. Should be <code>null</code> for messages by the current user, in which case
4546         * the platform will insert {@link #getUserDisplayName()}.
4547         * Should be unique amongst all individuals in the conversation, and should be
4548         * consistent during re-posts of the notification.
4549         *
4550         * @see Message#Message(CharSequence, long, CharSequence)
4551         *
4552         * @return this object for method chaining
4553         */
4554        public MessagingStyle addMessage(CharSequence text, long timestamp, CharSequence sender) {
4555            mMessages.add(new Message(text, timestamp, sender));
4556            if (mMessages.size() > MAXIMUM_RETAINED_MESSAGES) {
4557                mMessages.remove(0);
4558            }
4559            return this;
4560        }
4561
4562        /**
4563         * Adds a {@link Message} for display in this notification.
4564         * @param message The {@link Message} to be displayed
4565         * @return this object for method chaining
4566         */
4567        public MessagingStyle addMessage(Message message) {
4568            mMessages.add(message);
4569            if (mMessages.size() > MAXIMUM_RETAINED_MESSAGES) {
4570                mMessages.remove(0);
4571            }
4572            return this;
4573        }
4574
4575        /**
4576         * Gets the list of {@code Message} objects that represent the notification
4577         */
4578        public List<Message> getMessages() {
4579            return mMessages;
4580        }
4581
4582        /**
4583         * @hide
4584         */
4585        @Override
4586        public void addExtras(Bundle extras) {
4587            super.addExtras(extras);
4588            if (mUserDisplayName != null) {
4589                extras.putCharSequence(EXTRA_SELF_DISPLAY_NAME, mUserDisplayName);
4590            }
4591            if (mConversationTitle != null) {
4592                extras.putCharSequence(EXTRA_CONVERSATION_TITLE, mConversationTitle);
4593            }
4594            if (!mMessages.isEmpty()) { extras.putParcelableArray(EXTRA_MESSAGES,
4595                    Message.getBundleArrayForMessages(mMessages));
4596            }
4597
4598            fixTitleAndTextExtras(extras);
4599        }
4600
4601        private void fixTitleAndTextExtras(Bundle extras) {
4602            Message m = findLatestIncomingMessage();
4603            CharSequence text = (m == null) ? null : m.mText;
4604            CharSequence sender = m == null ? null
4605                    : TextUtils.isEmpty(m.mSender) ? mUserDisplayName : m.mSender;
4606            CharSequence title;
4607            if (!TextUtils.isEmpty(mConversationTitle)) {
4608                if (!TextUtils.isEmpty(sender)) {
4609                    BidiFormatter bidi = BidiFormatter.getInstance();
4610                    title = mBuilder.mContext.getString(
4611                            com.android.internal.R.string.notification_messaging_title_template,
4612                            bidi.unicodeWrap(mConversationTitle), bidi.unicodeWrap(m.mSender));
4613                } else {
4614                    title = mConversationTitle;
4615                }
4616            } else {
4617                title = sender;
4618            }
4619
4620            if (title != null) {
4621                extras.putCharSequence(EXTRA_TITLE, title);
4622            }
4623            if (text != null) {
4624                extras.putCharSequence(EXTRA_TEXT, text);
4625            }
4626        }
4627
4628        /**
4629         * @hide
4630         */
4631        @Override
4632        protected void restoreFromExtras(Bundle extras) {
4633            super.restoreFromExtras(extras);
4634
4635            mMessages.clear();
4636            mUserDisplayName = extras.getCharSequence(EXTRA_SELF_DISPLAY_NAME);
4637            mConversationTitle = extras.getCharSequence(EXTRA_CONVERSATION_TITLE);
4638            Parcelable[] parcelables = extras.getParcelableArray(EXTRA_MESSAGES);
4639            if (parcelables != null && parcelables instanceof Parcelable[]) {
4640                mMessages = Message.getMessagesFromBundleArray(parcelables);
4641            }
4642        }
4643
4644        /**
4645         * @hide
4646         */
4647        @Override
4648        public RemoteViews makeContentView() {
4649            Message m = findLatestIncomingMessage();
4650            CharSequence title = mConversationTitle != null
4651                    ? mConversationTitle
4652                    : (m == null) ? null : m.mSender;
4653            CharSequence text = (m == null)
4654                    ? null
4655                    : mConversationTitle != null ? makeMessageLine(m) : m.mText;
4656
4657            return mBuilder.applyStandardTemplate(mBuilder.getBaseLayoutResource(),
4658                    false /* hasProgress */,
4659                    title,
4660                    text);
4661        }
4662
4663        private Message findLatestIncomingMessage() {
4664            for (int i = mMessages.size() - 1; i >= 0; i--) {
4665                Message m = mMessages.get(i);
4666                // Incoming messages have a non-empty sender.
4667                if (!TextUtils.isEmpty(m.mSender)) {
4668                    return m;
4669                }
4670            }
4671            if (!mMessages.isEmpty()) {
4672                // No incoming messages, fall back to outgoing message
4673                return mMessages.get(mMessages.size() - 1);
4674            }
4675            return null;
4676        }
4677
4678        /**
4679         * @hide
4680         */
4681        @Override
4682        public RemoteViews makeBigContentView() {
4683            CharSequence title = !TextUtils.isEmpty(super.mBigContentTitle)
4684                    ? super.mBigContentTitle
4685                    : mConversationTitle;
4686            boolean hasTitle = !TextUtils.isEmpty(title);
4687
4688            if (mMessages.size() == 1) {
4689                // Special case for a single message: Use the big text style
4690                // so the collapsed and expanded versions match nicely.
4691                CharSequence bigTitle;
4692                CharSequence text;
4693                if (hasTitle) {
4694                    bigTitle = title;
4695                    text = makeMessageLine(mMessages.get(0));
4696                } else {
4697                    bigTitle = mMessages.get(0).mSender;
4698                    text = mMessages.get(0).mText;
4699                }
4700                RemoteViews contentView = mBuilder.applyStandardTemplateWithActions(
4701                        mBuilder.getBigTextLayoutResource(),
4702                        false /* progress */, bigTitle, null /* text */);
4703                BigTextStyle.applyBigTextContentView(mBuilder, contentView, text);
4704                return contentView;
4705            }
4706
4707            RemoteViews contentView = mBuilder.applyStandardTemplateWithActions(
4708                    mBuilder.getMessagingLayoutResource(),
4709                    false /* hasProgress */,
4710                    title,
4711                    null /* text */);
4712
4713            int[] rowIds = {R.id.inbox_text0, R.id.inbox_text1, R.id.inbox_text2, R.id.inbox_text3,
4714                    R.id.inbox_text4, R.id.inbox_text5, R.id.inbox_text6};
4715
4716            // Make sure all rows are gone in case we reuse a view.
4717            for (int rowId : rowIds) {
4718                contentView.setViewVisibility(rowId, View.GONE);
4719            }
4720
4721            int i=0;
4722            contentView.setViewLayoutMarginBottomDimen(R.id.line1,
4723                    hasTitle ? R.dimen.notification_messaging_spacing : 0);
4724            contentView.setInt(R.id.notification_messaging, "setNumIndentLines",
4725                    !mBuilder.mN.hasLargeIcon() ? 0 : (hasTitle ? 1 : 2));
4726
4727            int contractedChildId = View.NO_ID;
4728            Message contractedMessage = findLatestIncomingMessage();
4729            int firstMessage = Math.max(0, mMessages.size() - rowIds.length);
4730            while (firstMessage + i < mMessages.size() && i < rowIds.length) {
4731                Message m = mMessages.get(firstMessage + i);
4732                int rowId = rowIds[i];
4733
4734                contentView.setViewVisibility(rowId, View.VISIBLE);
4735                contentView.setTextViewText(rowId, makeMessageLine(m));
4736
4737                if (contractedMessage == m) {
4738                    contractedChildId = rowId;
4739                }
4740
4741                i++;
4742            }
4743            // Record this here to allow transformation between the contracted and expanded views.
4744            contentView.setInt(R.id.notification_messaging, "setContractedChildId",
4745                    contractedChildId);
4746            return contentView;
4747        }
4748
4749        private CharSequence makeMessageLine(Message m) {
4750            BidiFormatter bidi = BidiFormatter.getInstance();
4751            SpannableStringBuilder sb = new SpannableStringBuilder();
4752            if (TextUtils.isEmpty(m.mSender)) {
4753                CharSequence replyName = mUserDisplayName == null ? "" : mUserDisplayName;
4754                sb.append(bidi.unicodeWrap(replyName),
4755                        makeFontColorSpan(mBuilder.resolveContrastColor()),
4756                        0 /* flags */);
4757            } else {
4758                sb.append(bidi.unicodeWrap(m.mSender),
4759                        makeFontColorSpan(Color.BLACK),
4760                        0 /* flags */);
4761            }
4762            CharSequence text = m.mText == null ? "" : m.mText;
4763            sb.append("  ").append(bidi.unicodeWrap(text));
4764            return sb;
4765        }
4766
4767        /**
4768         * @hide
4769         */
4770        @Override
4771        public RemoteViews makeHeadsUpContentView() {
4772            Message m = findLatestIncomingMessage();
4773            CharSequence title = mConversationTitle != null
4774                    ? mConversationTitle
4775                    : (m == null) ? null : m.mSender;
4776            CharSequence text = (m == null)
4777                    ? null
4778                    : mConversationTitle != null ? makeMessageLine(m) : m.mText;
4779
4780            return mBuilder.applyStandardTemplateWithActions(mBuilder.getBigBaseLayoutResource(),
4781                    false /* hasProgress */,
4782                    title,
4783                    text);
4784        }
4785
4786        private static TextAppearanceSpan makeFontColorSpan(int color) {
4787            return new TextAppearanceSpan(null, 0, 0,
4788                    ColorStateList.valueOf(color), null);
4789        }
4790
4791        public static final class Message {
4792
4793            static final String KEY_TEXT = "text";
4794            static final String KEY_TIMESTAMP = "time";
4795            static final String KEY_SENDER = "sender";
4796            static final String KEY_DATA_MIME_TYPE = "type";
4797            static final String KEY_DATA_URI= "uri";
4798
4799            private final CharSequence mText;
4800            private final long mTimestamp;
4801            private final CharSequence mSender;
4802
4803            private String mDataMimeType;
4804            private Uri mDataUri;
4805
4806            /**
4807             * Constructor
4808             * @param text A {@link CharSequence} to be displayed as the message content
4809             * @param timestamp Time at which the message arrived
4810             * @param sender A {@link CharSequence} to be used for displaying the name of the
4811             * sender. Should be <code>null</code> for messages by the current user, in which case
4812             * the platform will insert {@link MessagingStyle#getUserDisplayName()}.
4813             * Should be unique amongst all individuals in the conversation, and should be
4814             * consistent during re-posts of the notification.
4815             */
4816            public Message(CharSequence text, long timestamp, CharSequence sender){
4817                mText = text;
4818                mTimestamp = timestamp;
4819                mSender = sender;
4820            }
4821
4822            /**
4823             * Sets a binary blob of data and an associated MIME type for a message. In the case
4824             * where the platform doesn't support the MIME type, the original text provided in the
4825             * constructor will be used.
4826             * @param dataMimeType The MIME type of the content. See
4827             * <a href="{@docRoot}notifications/messaging.html"> for the list of supported MIME
4828             * types on Android and Android Wear.
4829             * @param dataUri The uri containing the content whose type is given by the MIME type.
4830             * <p class="note">
4831             * <ol>
4832             *   <li>Notification Listeners including the System UI need permission to access the
4833             *       data the Uri points to. The recommended ways to do this are:</li>
4834             *   <li>Store the data in your own ContentProvider, making sure that other apps have
4835             *       the correct permission to access your provider. The preferred mechanism for
4836             *       providing access is to use per-URI permissions which are temporary and only
4837             *       grant access to the receiving application. An easy way to create a
4838             *       ContentProvider like this is to use the FileProvider helper class.</li>
4839             *   <li>Use the system MediaStore. The MediaStore is primarily aimed at video, audio
4840             *       and image MIME types, however beginning with Android 3.0 (API level 11) it can
4841             *       also store non-media types (see MediaStore.Files for more info). Files can be
4842             *       inserted into the MediaStore using scanFile() after which a content:// style
4843             *       Uri suitable for sharing is passed to the provided onScanCompleted() callback.
4844             *       Note that once added to the system MediaStore the content is accessible to any
4845             *       app on the device.</li>
4846             * </ol>
4847             * @return this object for method chaining
4848             */
4849            public Message setData(String dataMimeType, Uri dataUri) {
4850                mDataMimeType = dataMimeType;
4851                mDataUri = dataUri;
4852                return this;
4853            }
4854
4855            /**
4856             * Get the text to be used for this message, or the fallback text if a type and content
4857             * Uri have been set
4858             */
4859            public CharSequence getText() {
4860                return mText;
4861            }
4862
4863            /**
4864             * Get the time at which this message arrived
4865             */
4866            public long getTimestamp() {
4867                return mTimestamp;
4868            }
4869
4870            /**
4871             * Get the text used to display the contact's name in the messaging experience
4872             */
4873            public CharSequence getSender() {
4874                return mSender;
4875            }
4876
4877            /**
4878             * Get the MIME type of the data pointed to by the Uri
4879             */
4880            public String getDataMimeType() {
4881                return mDataMimeType;
4882            }
4883
4884            /**
4885             * Get the the Uri pointing to the content of the message. Can be null, in which case
4886             * {@see #getText()} is used.
4887             */
4888            public Uri getDataUri() {
4889                return mDataUri;
4890            }
4891
4892            private Bundle toBundle() {
4893                Bundle bundle = new Bundle();
4894                if (mText != null) {
4895                    bundle.putCharSequence(KEY_TEXT, mText);
4896                }
4897                bundle.putLong(KEY_TIMESTAMP, mTimestamp);
4898                if (mSender != null) {
4899                    bundle.putCharSequence(KEY_SENDER, mSender);
4900                }
4901                if (mDataMimeType != null) {
4902                    bundle.putString(KEY_DATA_MIME_TYPE, mDataMimeType);
4903                }
4904                if (mDataUri != null) {
4905                    bundle.putParcelable(KEY_DATA_URI, mDataUri);
4906                }
4907                return bundle;
4908            }
4909
4910            static Bundle[] getBundleArrayForMessages(List<Message> messages) {
4911                Bundle[] bundles = new Bundle[messages.size()];
4912                final int N = messages.size();
4913                for (int i = 0; i < N; i++) {
4914                    bundles[i] = messages.get(i).toBundle();
4915                }
4916                return bundles;
4917            }
4918
4919            static List<Message> getMessagesFromBundleArray(Parcelable[] bundles) {
4920                List<Message> messages = new ArrayList<>(bundles.length);
4921                for (int i = 0; i < bundles.length; i++) {
4922                    if (bundles[i] instanceof Bundle) {
4923                        Message message = getMessageFromBundle((Bundle)bundles[i]);
4924                        if (message != null) {
4925                            messages.add(message);
4926                        }
4927                    }
4928                }
4929                return messages;
4930            }
4931
4932            static Message getMessageFromBundle(Bundle bundle) {
4933                try {
4934                    if (!bundle.containsKey(KEY_TEXT) || !bundle.containsKey(KEY_TIMESTAMP)) {
4935                        return null;
4936                    } else {
4937                        Message message = new Message(bundle.getCharSequence(KEY_TEXT),
4938                                bundle.getLong(KEY_TIMESTAMP), bundle.getCharSequence(KEY_SENDER));
4939                        if (bundle.containsKey(KEY_DATA_MIME_TYPE) &&
4940                                bundle.containsKey(KEY_DATA_URI)) {
4941
4942                            message.setData(bundle.getString(KEY_DATA_MIME_TYPE),
4943                                    (Uri) bundle.getParcelable(KEY_DATA_URI));
4944                        }
4945                        return message;
4946                    }
4947                } catch (ClassCastException e) {
4948                    return null;
4949                }
4950            }
4951        }
4952    }
4953
4954    /**
4955     * Helper class for generating large-format notifications that include a list of (up to 5) strings.
4956     *
4957     * Here's how you'd set the <code>InboxStyle</code> on a notification:
4958     * <pre class="prettyprint">
4959     * Notification notif = new Notification.Builder(mContext)
4960     *     .setContentTitle(&quot;5 New mails from &quot; + sender.toString())
4961     *     .setContentText(subject)
4962     *     .setSmallIcon(R.drawable.new_mail)
4963     *     .setLargeIcon(aBitmap)
4964     *     .setStyle(new Notification.InboxStyle()
4965     *         .addLine(str1)
4966     *         .addLine(str2)
4967     *         .setContentTitle(&quot;&quot;)
4968     *         .setSummaryText(&quot;+3 more&quot;))
4969     *     .build();
4970     * </pre>
4971     *
4972     * @see Notification#bigContentView
4973     */
4974    public static class InboxStyle extends Style {
4975        private ArrayList<CharSequence> mTexts = new ArrayList<CharSequence>(5);
4976
4977        public InboxStyle() {
4978        }
4979
4980        /**
4981         * @deprecated use {@code InboxStyle()}.
4982         */
4983        @Deprecated
4984        public InboxStyle(Builder builder) {
4985            setBuilder(builder);
4986        }
4987
4988        /**
4989         * Overrides ContentTitle in the big form of the template.
4990         * This defaults to the value passed to setContentTitle().
4991         */
4992        public InboxStyle setBigContentTitle(CharSequence title) {
4993            internalSetBigContentTitle(safeCharSequence(title));
4994            return this;
4995        }
4996
4997        /**
4998         * Set the first line of text after the detail section in the big form of the template.
4999         */
5000        public InboxStyle setSummaryText(CharSequence cs) {
5001            internalSetSummaryText(safeCharSequence(cs));
5002            return this;
5003        }
5004
5005        /**
5006         * Append a line to the digest section of the Inbox notification.
5007         */
5008        public InboxStyle addLine(CharSequence cs) {
5009            mTexts.add(safeCharSequence(cs));
5010            return this;
5011        }
5012
5013        /**
5014         * @hide
5015         */
5016        public void addExtras(Bundle extras) {
5017            super.addExtras(extras);
5018
5019            CharSequence[] a = new CharSequence[mTexts.size()];
5020            extras.putCharSequenceArray(EXTRA_TEXT_LINES, mTexts.toArray(a));
5021        }
5022
5023        /**
5024         * @hide
5025         */
5026        @Override
5027        protected void restoreFromExtras(Bundle extras) {
5028            super.restoreFromExtras(extras);
5029
5030            mTexts.clear();
5031            if (extras.containsKey(EXTRA_TEXT_LINES)) {
5032                Collections.addAll(mTexts, extras.getCharSequenceArray(EXTRA_TEXT_LINES));
5033            }
5034        }
5035
5036        /**
5037         * @hide
5038         */
5039        public RemoteViews makeBigContentView() {
5040            // Remove the content text so it disappears unless you have a summary
5041            // Nasty
5042            CharSequence oldBuilderContentText = mBuilder.mN.extras.getCharSequence(EXTRA_TEXT);
5043            mBuilder.getAllExtras().putCharSequence(EXTRA_TEXT, null);
5044
5045            RemoteViews contentView = getStandardView(mBuilder.getInboxLayoutResource());
5046
5047            mBuilder.getAllExtras().putCharSequence(EXTRA_TEXT, oldBuilderContentText);
5048
5049            int[] rowIds = {R.id.inbox_text0, R.id.inbox_text1, R.id.inbox_text2, R.id.inbox_text3,
5050                    R.id.inbox_text4, R.id.inbox_text5, R.id.inbox_text6};
5051
5052            // Make sure all rows are gone in case we reuse a view.
5053            for (int rowId : rowIds) {
5054                contentView.setViewVisibility(rowId, View.GONE);
5055            }
5056
5057            int i=0;
5058            int topPadding = mBuilder.mContext.getResources().getDimensionPixelSize(
5059                    R.dimen.notification_inbox_item_top_padding);
5060            boolean first = true;
5061            int onlyViewId = 0;
5062            int maxRows = rowIds.length;
5063            if (mBuilder.mActions.size() > 0) {
5064                maxRows--;
5065            }
5066            while (i < mTexts.size() && i < maxRows) {
5067                CharSequence str = mTexts.get(i);
5068                if (!TextUtils.isEmpty(str)) {
5069                    contentView.setViewVisibility(rowIds[i], View.VISIBLE);
5070                    contentView.setTextViewText(rowIds[i], mBuilder.processLegacyText(str));
5071                    contentView.setViewPadding(rowIds[i], 0, topPadding, 0, 0);
5072                    handleInboxImageMargin(contentView, rowIds[i], first);
5073                    if (first) {
5074                        onlyViewId = rowIds[i];
5075                    } else {
5076                        onlyViewId = 0;
5077                    }
5078                    first = false;
5079                }
5080                i++;
5081            }
5082            if (onlyViewId != 0) {
5083                // We only have 1 entry, lets make it look like the normal Text of a Bigtext
5084                topPadding = mBuilder.mContext.getResources().getDimensionPixelSize(
5085                        R.dimen.notification_text_margin_top);
5086                contentView.setViewPadding(onlyViewId, 0, topPadding, 0, 0);
5087            }
5088
5089            return contentView;
5090        }
5091
5092        private void handleInboxImageMargin(RemoteViews contentView, int id, boolean first) {
5093            int endMargin = 0;
5094            if (first) {
5095                final int max = mBuilder.mN.extras.getInt(EXTRA_PROGRESS_MAX, 0);
5096                final boolean ind = mBuilder.mN.extras.getBoolean(EXTRA_PROGRESS_INDETERMINATE);
5097                boolean hasProgress = max != 0 || ind;
5098                if (mBuilder.mN.hasLargeIcon() && !hasProgress) {
5099                    endMargin = R.dimen.notification_content_picture_margin;
5100                }
5101            }
5102            contentView.setViewLayoutMarginEndDimen(id, endMargin);
5103        }
5104    }
5105
5106    /**
5107     * Notification style for media playback notifications.
5108     *
5109     * In the expanded form, {@link Notification#bigContentView}, up to 5
5110     * {@link Notification.Action}s specified with
5111     * {@link Notification.Builder#addAction(Action) addAction} will be
5112     * shown as icon-only pushbuttons, suitable for transport controls. The Bitmap given to
5113     * {@link Notification.Builder#setLargeIcon(android.graphics.Bitmap) setLargeIcon()} will be
5114     * treated as album artwork.
5115     *
5116     * Unlike the other styles provided here, MediaStyle can also modify the standard-size
5117     * {@link Notification#contentView}; by providing action indices to
5118     * {@link #setShowActionsInCompactView(int...)} you can promote up to 3 actions to be displayed
5119     * in the standard view alongside the usual content.
5120     *
5121     * Notifications created with MediaStyle will have their category set to
5122     * {@link Notification#CATEGORY_TRANSPORT CATEGORY_TRANSPORT} unless you set a different
5123     * category using {@link Notification.Builder#setCategory(String) setCategory()}.
5124     *
5125     * Finally, if you attach a {@link android.media.session.MediaSession.Token} using
5126     * {@link android.app.Notification.MediaStyle#setMediaSession(MediaSession.Token)},
5127     * the System UI can identify this as a notification representing an active media session
5128     * and respond accordingly (by showing album artwork in the lockscreen, for example).
5129     *
5130     * To use this style with your Notification, feed it to
5131     * {@link Notification.Builder#setStyle(android.app.Notification.Style)} like so:
5132     * <pre class="prettyprint">
5133     * Notification noti = new Notification.Builder()
5134     *     .setSmallIcon(R.drawable.ic_stat_player)
5135     *     .setContentTitle(&quot;Track title&quot;)
5136     *     .setContentText(&quot;Artist - Album&quot;)
5137     *     .setLargeIcon(albumArtBitmap))
5138     *     .setStyle(<b>new Notification.MediaStyle()</b>
5139     *         .setMediaSession(mySession))
5140     *     .build();
5141     * </pre>
5142     *
5143     * @see Notification#bigContentView
5144     */
5145    public static class MediaStyle extends Style {
5146        static final int MAX_MEDIA_BUTTONS_IN_COMPACT = 3;
5147        static final int MAX_MEDIA_BUTTONS = 5;
5148
5149        private int[] mActionsToShowInCompact = null;
5150        private MediaSession.Token mToken;
5151
5152        public MediaStyle() {
5153        }
5154
5155        /**
5156         * @deprecated use {@code MediaStyle()}.
5157         */
5158        @Deprecated
5159        public MediaStyle(Builder builder) {
5160            setBuilder(builder);
5161        }
5162
5163        /**
5164         * Request up to 3 actions (by index in the order of addition) to be shown in the compact
5165         * notification view.
5166         *
5167         * @param actions the indices of the actions to show in the compact notification view
5168         */
5169        public MediaStyle setShowActionsInCompactView(int...actions) {
5170            mActionsToShowInCompact = actions;
5171            return this;
5172        }
5173
5174        /**
5175         * Attach a {@link android.media.session.MediaSession.Token} to this Notification
5176         * to provide additional playback information and control to the SystemUI.
5177         */
5178        public MediaStyle setMediaSession(MediaSession.Token token) {
5179            mToken = token;
5180            return this;
5181        }
5182
5183        /**
5184         * @hide
5185         */
5186        @Override
5187        public Notification buildStyled(Notification wip) {
5188            super.buildStyled(wip);
5189            if (wip.category == null) {
5190                wip.category = Notification.CATEGORY_TRANSPORT;
5191            }
5192            return wip;
5193        }
5194
5195        /**
5196         * @hide
5197         */
5198        @Override
5199        public RemoteViews makeContentView() {
5200            return makeMediaContentView();
5201        }
5202
5203        /**
5204         * @hide
5205         */
5206        @Override
5207        public RemoteViews makeBigContentView() {
5208            return makeMediaBigContentView();
5209        }
5210
5211        /**
5212         * @hide
5213         */
5214        @Override
5215        public RemoteViews makeHeadsUpContentView() {
5216            RemoteViews expanded = makeMediaBigContentView();
5217            return expanded != null ? expanded : makeMediaContentView();
5218        }
5219
5220        /** @hide */
5221        @Override
5222        public void addExtras(Bundle extras) {
5223            super.addExtras(extras);
5224
5225            if (mToken != null) {
5226                extras.putParcelable(EXTRA_MEDIA_SESSION, mToken);
5227            }
5228            if (mActionsToShowInCompact != null) {
5229                extras.putIntArray(EXTRA_COMPACT_ACTIONS, mActionsToShowInCompact);
5230            }
5231        }
5232
5233        /**
5234         * @hide
5235         */
5236        @Override
5237        protected void restoreFromExtras(Bundle extras) {
5238            super.restoreFromExtras(extras);
5239
5240            if (extras.containsKey(EXTRA_MEDIA_SESSION)) {
5241                mToken = extras.getParcelable(EXTRA_MEDIA_SESSION);
5242            }
5243            if (extras.containsKey(EXTRA_COMPACT_ACTIONS)) {
5244                mActionsToShowInCompact = extras.getIntArray(EXTRA_COMPACT_ACTIONS);
5245            }
5246        }
5247
5248        private RemoteViews generateMediaActionButton(Action action, int color) {
5249            final boolean tombstone = (action.actionIntent == null);
5250            RemoteViews button = new BuilderRemoteViews(mBuilder.mContext.getApplicationInfo(),
5251                    R.layout.notification_material_media_action);
5252            button.setImageViewIcon(R.id.action0, action.getIcon());
5253            button.setDrawableParameters(R.id.action0, false, -1, color, PorterDuff.Mode.SRC_ATOP,
5254                    -1);
5255            if (!tombstone) {
5256                button.setOnClickPendingIntent(R.id.action0, action.actionIntent);
5257            }
5258            button.setContentDescription(R.id.action0, action.title);
5259            return button;
5260        }
5261
5262        private RemoteViews makeMediaContentView() {
5263            RemoteViews view = mBuilder.applyStandardTemplate(
5264                    R.layout.notification_template_material_media, false /* hasProgress */);
5265
5266            final int numActions = mBuilder.mActions.size();
5267            final int N = mActionsToShowInCompact == null
5268                    ? 0
5269                    : Math.min(mActionsToShowInCompact.length, MAX_MEDIA_BUTTONS_IN_COMPACT);
5270            if (N > 0) {
5271                view.removeAllViews(com.android.internal.R.id.media_actions);
5272                for (int i = 0; i < N; i++) {
5273                    if (i >= numActions) {
5274                        throw new IllegalArgumentException(String.format(
5275                                "setShowActionsInCompactView: action %d out of bounds (max %d)",
5276                                i, numActions - 1));
5277                    }
5278
5279                    final Action action = mBuilder.mActions.get(mActionsToShowInCompact[i]);
5280                    final RemoteViews button = generateMediaActionButton(action,
5281                            mBuilder.resolveContrastColor());
5282                    view.addView(com.android.internal.R.id.media_actions, button);
5283                }
5284            }
5285            handleImage(view);
5286            // handle the content margin
5287            int endMargin = R.dimen.notification_content_margin_end;
5288            if (mBuilder.mN.hasLargeIcon()) {
5289                endMargin = R.dimen.notification_content_plus_picture_margin_end;
5290            }
5291            view.setViewLayoutMarginEndDimen(R.id.notification_main_column, endMargin);
5292            return view;
5293        }
5294
5295        private RemoteViews makeMediaBigContentView() {
5296            final int actionCount = Math.min(mBuilder.mActions.size(), MAX_MEDIA_BUTTONS);
5297            // Dont add an expanded view if there is no more content to be revealed
5298            int actionsInCompact = mActionsToShowInCompact == null
5299                    ? 0
5300                    : Math.min(mActionsToShowInCompact.length, MAX_MEDIA_BUTTONS_IN_COMPACT);
5301            if (!mBuilder.mN.hasLargeIcon() && actionCount <= actionsInCompact) {
5302                return null;
5303            }
5304            RemoteViews big = mBuilder.applyStandardTemplate(
5305                    R.layout.notification_template_material_big_media,
5306                    false);
5307
5308            if (actionCount > 0) {
5309                big.removeAllViews(com.android.internal.R.id.media_actions);
5310                for (int i = 0; i < actionCount; i++) {
5311                    final RemoteViews button = generateMediaActionButton(mBuilder.mActions.get(i),
5312                            mBuilder.resolveContrastColor());
5313                    big.addView(com.android.internal.R.id.media_actions, button);
5314                }
5315            }
5316            handleImage(big);
5317            return big;
5318        }
5319
5320        private void handleImage(RemoteViews contentView) {
5321            if (mBuilder.mN.hasLargeIcon()) {
5322                contentView.setViewLayoutMarginEndDimen(R.id.line1, 0);
5323                contentView.setViewLayoutMarginEndDimen(R.id.text, 0);
5324            }
5325        }
5326
5327        /**
5328         * @hide
5329         */
5330        @Override
5331        protected boolean hasProgress() {
5332            return false;
5333        }
5334    }
5335
5336    /**
5337     * Notification style for custom views that are decorated by the system
5338     *
5339     * <p>Instead of providing a notification that is completely custom, a developer can set this
5340     * style and still obtain system decorations like the notification header with the expand
5341     * affordance and actions.
5342     *
5343     * <p>Use {@link android.app.Notification.Builder#setCustomContentView(RemoteViews)},
5344     * {@link android.app.Notification.Builder#setCustomBigContentView(RemoteViews)} and
5345     * {@link android.app.Notification.Builder#setCustomHeadsUpContentView(RemoteViews)} to set the
5346     * corresponding custom views to display.
5347     *
5348     * To use this style with your Notification, feed it to
5349     * {@link Notification.Builder#setStyle(android.app.Notification.Style)} like so:
5350     * <pre class="prettyprint">
5351     * Notification noti = new Notification.Builder()
5352     *     .setSmallIcon(R.drawable.ic_stat_player)
5353     *     .setLargeIcon(albumArtBitmap))
5354     *     .setCustomContentView(contentView);
5355     *     .setStyle(<b>new Notification.DecoratedCustomViewStyle()</b>)
5356     *     .build();
5357     * </pre>
5358     */
5359    public static class DecoratedCustomViewStyle extends Style {
5360
5361        public DecoratedCustomViewStyle() {
5362        }
5363
5364        /**
5365         * @hide
5366         */
5367        public boolean displayCustomViewInline() {
5368            return true;
5369        }
5370
5371        /**
5372         * @hide
5373         */
5374        @Override
5375        public RemoteViews makeContentView() {
5376            return makeStandardTemplateWithCustomContent(mBuilder.mN.contentView);
5377        }
5378
5379        /**
5380         * @hide
5381         */
5382        @Override
5383        public RemoteViews makeBigContentView() {
5384            return makeDecoratedBigContentView();
5385        }
5386
5387        /**
5388         * @hide
5389         */
5390        @Override
5391        public RemoteViews makeHeadsUpContentView() {
5392            return makeDecoratedHeadsUpContentView();
5393        }
5394
5395        private RemoteViews makeDecoratedHeadsUpContentView() {
5396            RemoteViews headsUpContentView = mBuilder.mN.headsUpContentView == null
5397                    ? mBuilder.mN.contentView
5398                    : mBuilder.mN.headsUpContentView;
5399            if (mBuilder.mActions.size() == 0) {
5400               return makeStandardTemplateWithCustomContent(headsUpContentView);
5401            }
5402            RemoteViews remoteViews = mBuilder.applyStandardTemplateWithActions(
5403                        mBuilder.getBigBaseLayoutResource());
5404            buildIntoRemoteViewContent(remoteViews, headsUpContentView);
5405            return remoteViews;
5406        }
5407
5408        private RemoteViews makeStandardTemplateWithCustomContent(RemoteViews customContent) {
5409            RemoteViews remoteViews = mBuilder.applyStandardTemplate(
5410                    mBuilder.getBaseLayoutResource());
5411            buildIntoRemoteViewContent(remoteViews, customContent);
5412            return remoteViews;
5413        }
5414
5415        private RemoteViews makeDecoratedBigContentView() {
5416            RemoteViews bigContentView = mBuilder.mN.bigContentView == null
5417                    ? mBuilder.mN.contentView
5418                    : mBuilder.mN.bigContentView;
5419            if (mBuilder.mActions.size() == 0) {
5420                return makeStandardTemplateWithCustomContent(bigContentView);
5421            }
5422            RemoteViews remoteViews = mBuilder.applyStandardTemplateWithActions(
5423                    mBuilder.getBigBaseLayoutResource());
5424            buildIntoRemoteViewContent(remoteViews, bigContentView);
5425            return remoteViews;
5426        }
5427
5428        private void buildIntoRemoteViewContent(RemoteViews remoteViews,
5429                RemoteViews customContent) {
5430            if (customContent != null) {
5431                // Need to clone customContent before adding, because otherwise it can no longer be
5432                // parceled independently of remoteViews.
5433                customContent = customContent.clone();
5434                remoteViews.removeAllViews(R.id.notification_main_column);
5435                remoteViews.addView(R.id.notification_main_column, customContent);
5436            }
5437            // also update the end margin if there is an image
5438            int endMargin = R.dimen.notification_content_margin_end;
5439            if (mBuilder.mN.hasLargeIcon()) {
5440                endMargin = R.dimen.notification_content_plus_picture_margin_end;
5441            }
5442            remoteViews.setViewLayoutMarginEndDimen(R.id.notification_main_column, endMargin);
5443        }
5444    }
5445
5446    /**
5447     * Notification style for media custom views that are decorated by the system
5448     *
5449     * <p>Instead of providing a media notification that is completely custom, a developer can set
5450     * this style and still obtain system decorations like the notification header with the expand
5451     * affordance and actions.
5452     *
5453     * <p>Use {@link android.app.Notification.Builder#setCustomContentView(RemoteViews)},
5454     * {@link android.app.Notification.Builder#setCustomBigContentView(RemoteViews)} and
5455     * {@link android.app.Notification.Builder#setCustomHeadsUpContentView(RemoteViews)} to set the
5456     * corresponding custom views to display.
5457     *
5458     * To use this style with your Notification, feed it to
5459     * {@link Notification.Builder#setStyle(android.app.Notification.Style)} like so:
5460     * <pre class="prettyprint">
5461     * Notification noti = new Notification.Builder()
5462     *     .setSmallIcon(R.drawable.ic_stat_player)
5463     *     .setLargeIcon(albumArtBitmap))
5464     *     .setCustomContentView(contentView);
5465     *     .setStyle(<b>new Notification.DecoratedMediaCustomViewStyle()</b>
5466     *          .setMediaSession(mySession))
5467     *     .build();
5468     * </pre>
5469     *
5470     * @see android.app.Notification.DecoratedCustomViewStyle
5471     * @see android.app.Notification.MediaStyle
5472     */
5473    public static class DecoratedMediaCustomViewStyle extends MediaStyle {
5474
5475        public DecoratedMediaCustomViewStyle() {
5476        }
5477
5478        /**
5479         * @hide
5480         */
5481        public boolean displayCustomViewInline() {
5482            return true;
5483        }
5484
5485        /**
5486         * @hide
5487         */
5488        @Override
5489        public RemoteViews makeContentView() {
5490            RemoteViews remoteViews = super.makeContentView();
5491            return buildIntoRemoteView(remoteViews, R.id.notification_content_container,
5492                    mBuilder.mN.contentView);
5493        }
5494
5495        /**
5496         * @hide
5497         */
5498        @Override
5499        public RemoteViews makeBigContentView() {
5500            RemoteViews customRemoteView = mBuilder.mN.bigContentView != null
5501                    ? mBuilder.mN.bigContentView
5502                    : mBuilder.mN.contentView;
5503            return makeBigContentViewWithCustomContent(customRemoteView);
5504        }
5505
5506        private RemoteViews makeBigContentViewWithCustomContent(RemoteViews customRemoteView) {
5507            RemoteViews remoteViews = super.makeBigContentView();
5508            if (remoteViews != null) {
5509                return buildIntoRemoteView(remoteViews, R.id.notification_main_column,
5510                        customRemoteView);
5511            } else if (customRemoteView != mBuilder.mN.contentView){
5512                remoteViews = super.makeContentView();
5513                return buildIntoRemoteView(remoteViews, R.id.notification_content_container,
5514                        customRemoteView);
5515            } else {
5516                return null;
5517            }
5518        }
5519
5520        /**
5521         * @hide
5522         */
5523        @Override
5524        public RemoteViews makeHeadsUpContentView() {
5525            RemoteViews customRemoteView = mBuilder.mN.headsUpContentView != null
5526                    ? mBuilder.mN.headsUpContentView
5527                    : mBuilder.mN.contentView;
5528            return makeBigContentViewWithCustomContent(customRemoteView);
5529        }
5530
5531        private RemoteViews buildIntoRemoteView(RemoteViews remoteViews, int id,
5532                RemoteViews customContent) {
5533            if (customContent != null) {
5534                // Need to clone customContent before adding, because otherwise it can no longer be
5535                // parceled independently of remoteViews.
5536                customContent = customContent.clone();
5537                remoteViews.removeAllViews(id);
5538                remoteViews.addView(id, customContent);
5539            }
5540            return remoteViews;
5541        }
5542    }
5543
5544    // When adding a new Style subclass here, don't forget to update
5545    // Builder.getNotificationStyleClass.
5546
5547    /**
5548     * Extender interface for use with {@link Builder#extend}. Extenders may be used to add
5549     * metadata or change options on a notification builder.
5550     */
5551    public interface Extender {
5552        /**
5553         * Apply this extender to a notification builder.
5554         * @param builder the builder to be modified.
5555         * @return the build object for chaining.
5556         */
5557        public Builder extend(Builder builder);
5558    }
5559
5560    /**
5561     * Helper class to add wearable extensions to notifications.
5562     * <p class="note"> See
5563     * <a href="{@docRoot}wear/notifications/creating.html">Creating Notifications
5564     * for Android Wear</a> for more information on how to use this class.
5565     * <p>
5566     * To create a notification with wearable extensions:
5567     * <ol>
5568     *   <li>Create a {@link android.app.Notification.Builder}, setting any desired
5569     *   properties.
5570     *   <li>Create a {@link android.app.Notification.WearableExtender}.
5571     *   <li>Set wearable-specific properties using the
5572     *   {@code add} and {@code set} methods of {@link android.app.Notification.WearableExtender}.
5573     *   <li>Call {@link android.app.Notification.Builder#extend} to apply the extensions to a
5574     *   notification.
5575     *   <li>Post the notification to the notification system with the
5576     *   {@code NotificationManager.notify(...)} methods.
5577     * </ol>
5578     *
5579     * <pre class="prettyprint">
5580     * Notification notif = new Notification.Builder(mContext)
5581     *         .setContentTitle(&quot;New mail from &quot; + sender.toString())
5582     *         .setContentText(subject)
5583     *         .setSmallIcon(R.drawable.new_mail)
5584     *         .extend(new Notification.WearableExtender()
5585     *                 .setContentIcon(R.drawable.new_mail))
5586     *         .build();
5587     * NotificationManager notificationManger =
5588     *         (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
5589     * notificationManger.notify(0, notif);</pre>
5590     *
5591     * <p>Wearable extensions can be accessed on an existing notification by using the
5592     * {@code WearableExtender(Notification)} constructor,
5593     * and then using the {@code get} methods to access values.
5594     *
5595     * <pre class="prettyprint">
5596     * Notification.WearableExtender wearableExtender = new Notification.WearableExtender(
5597     *         notification);
5598     * List&lt;Notification&gt; pages = wearableExtender.getPages();</pre>
5599     */
5600    public static final class WearableExtender implements Extender {
5601        /**
5602         * Sentinel value for an action index that is unset.
5603         */
5604        public static final int UNSET_ACTION_INDEX = -1;
5605
5606        /**
5607         * Size value for use with {@link #setCustomSizePreset} to show this notification with
5608         * default sizing.
5609         * <p>For custom display notifications created using {@link #setDisplayIntent},
5610         * the default is {@link #SIZE_MEDIUM}. All other notifications size automatically based
5611         * on their content.
5612         */
5613        public static final int SIZE_DEFAULT = 0;
5614
5615        /**
5616         * Size value for use with {@link #setCustomSizePreset} to show this notification
5617         * with an extra small size.
5618         * <p>This value is only applicable for custom display notifications created using
5619         * {@link #setDisplayIntent}.
5620         */
5621        public static final int SIZE_XSMALL = 1;
5622
5623        /**
5624         * Size value for use with {@link #setCustomSizePreset} to show this notification
5625         * with a small size.
5626         * <p>This value is only applicable for custom display notifications created using
5627         * {@link #setDisplayIntent}.
5628         */
5629        public static final int SIZE_SMALL = 2;
5630
5631        /**
5632         * Size value for use with {@link #setCustomSizePreset} to show this notification
5633         * with a medium size.
5634         * <p>This value is only applicable for custom display notifications created using
5635         * {@link #setDisplayIntent}.
5636         */
5637        public static final int SIZE_MEDIUM = 3;
5638
5639        /**
5640         * Size value for use with {@link #setCustomSizePreset} to show this notification
5641         * with a large size.
5642         * <p>This value is only applicable for custom display notifications created using
5643         * {@link #setDisplayIntent}.
5644         */
5645        public static final int SIZE_LARGE = 4;
5646
5647        /**
5648         * Size value for use with {@link #setCustomSizePreset} to show this notification
5649         * full screen.
5650         * <p>This value is only applicable for custom display notifications created using
5651         * {@link #setDisplayIntent}.
5652         */
5653        public static final int SIZE_FULL_SCREEN = 5;
5654
5655        /**
5656         * Sentinel value for use with {@link #setHintScreenTimeout} to keep the screen on for a
5657         * short amount of time when this notification is displayed on the screen. This
5658         * is the default value.
5659         */
5660        public static final int SCREEN_TIMEOUT_SHORT = 0;
5661
5662        /**
5663         * Sentinel value for use with {@link #setHintScreenTimeout} to keep the screen on
5664         * for a longer amount of time when this notification is displayed on the screen.
5665         */
5666        public static final int SCREEN_TIMEOUT_LONG = -1;
5667
5668        /** Notification extra which contains wearable extensions */
5669        private static final String EXTRA_WEARABLE_EXTENSIONS = "android.wearable.EXTENSIONS";
5670
5671        // Keys within EXTRA_WEARABLE_EXTENSIONS for wearable options.
5672        private static final String KEY_ACTIONS = "actions";
5673        private static final String KEY_FLAGS = "flags";
5674        private static final String KEY_DISPLAY_INTENT = "displayIntent";
5675        private static final String KEY_PAGES = "pages";
5676        private static final String KEY_BACKGROUND = "background";
5677        private static final String KEY_CONTENT_ICON = "contentIcon";
5678        private static final String KEY_CONTENT_ICON_GRAVITY = "contentIconGravity";
5679        private static final String KEY_CONTENT_ACTION_INDEX = "contentActionIndex";
5680        private static final String KEY_CUSTOM_SIZE_PRESET = "customSizePreset";
5681        private static final String KEY_CUSTOM_CONTENT_HEIGHT = "customContentHeight";
5682        private static final String KEY_GRAVITY = "gravity";
5683        private static final String KEY_HINT_SCREEN_TIMEOUT = "hintScreenTimeout";
5684        private static final String KEY_DISMISSAL_ID = "dismissalId";
5685
5686        // Flags bitwise-ored to mFlags
5687        private static final int FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE = 0x1;
5688        private static final int FLAG_HINT_HIDE_ICON = 1 << 1;
5689        private static final int FLAG_HINT_SHOW_BACKGROUND_ONLY = 1 << 2;
5690        private static final int FLAG_START_SCROLL_BOTTOM = 1 << 3;
5691        private static final int FLAG_HINT_AVOID_BACKGROUND_CLIPPING = 1 << 4;
5692        private static final int FLAG_BIG_PICTURE_AMBIENT = 1 << 5;
5693        private static final int FLAG_HINT_CONTENT_INTENT_LAUNCHES_ACTIVITY = 1 << 6;
5694
5695        // Default value for flags integer
5696        private static final int DEFAULT_FLAGS = FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE;
5697
5698        private static final int DEFAULT_CONTENT_ICON_GRAVITY = Gravity.END;
5699        private static final int DEFAULT_GRAVITY = Gravity.BOTTOM;
5700
5701        private ArrayList<Action> mActions = new ArrayList<Action>();
5702        private int mFlags = DEFAULT_FLAGS;
5703        private PendingIntent mDisplayIntent;
5704        private ArrayList<Notification> mPages = new ArrayList<Notification>();
5705        private Bitmap mBackground;
5706        private int mContentIcon;
5707        private int mContentIconGravity = DEFAULT_CONTENT_ICON_GRAVITY;
5708        private int mContentActionIndex = UNSET_ACTION_INDEX;
5709        private int mCustomSizePreset = SIZE_DEFAULT;
5710        private int mCustomContentHeight;
5711        private int mGravity = DEFAULT_GRAVITY;
5712        private int mHintScreenTimeout;
5713        private String mDismissalId;
5714
5715        /**
5716         * Create a {@link android.app.Notification.WearableExtender} with default
5717         * options.
5718         */
5719        public WearableExtender() {
5720        }
5721
5722        public WearableExtender(Notification notif) {
5723            Bundle wearableBundle = notif.extras.getBundle(EXTRA_WEARABLE_EXTENSIONS);
5724            if (wearableBundle != null) {
5725                List<Action> actions = wearableBundle.getParcelableArrayList(KEY_ACTIONS);
5726                if (actions != null) {
5727                    mActions.addAll(actions);
5728                }
5729
5730                mFlags = wearableBundle.getInt(KEY_FLAGS, DEFAULT_FLAGS);
5731                mDisplayIntent = wearableBundle.getParcelable(KEY_DISPLAY_INTENT);
5732
5733                Notification[] pages = getNotificationArrayFromBundle(
5734                        wearableBundle, KEY_PAGES);
5735                if (pages != null) {
5736                    Collections.addAll(mPages, pages);
5737                }
5738
5739                mBackground = wearableBundle.getParcelable(KEY_BACKGROUND);
5740                mContentIcon = wearableBundle.getInt(KEY_CONTENT_ICON);
5741                mContentIconGravity = wearableBundle.getInt(KEY_CONTENT_ICON_GRAVITY,
5742                        DEFAULT_CONTENT_ICON_GRAVITY);
5743                mContentActionIndex = wearableBundle.getInt(KEY_CONTENT_ACTION_INDEX,
5744                        UNSET_ACTION_INDEX);
5745                mCustomSizePreset = wearableBundle.getInt(KEY_CUSTOM_SIZE_PRESET,
5746                        SIZE_DEFAULT);
5747                mCustomContentHeight = wearableBundle.getInt(KEY_CUSTOM_CONTENT_HEIGHT);
5748                mGravity = wearableBundle.getInt(KEY_GRAVITY, DEFAULT_GRAVITY);
5749                mHintScreenTimeout = wearableBundle.getInt(KEY_HINT_SCREEN_TIMEOUT);
5750                mDismissalId = wearableBundle.getString(KEY_DISMISSAL_ID);
5751            }
5752        }
5753
5754        /**
5755         * Apply wearable extensions to a notification that is being built. This is typically
5756         * called by the {@link android.app.Notification.Builder#extend} method of
5757         * {@link android.app.Notification.Builder}.
5758         */
5759        @Override
5760        public Notification.Builder extend(Notification.Builder builder) {
5761            Bundle wearableBundle = new Bundle();
5762
5763            if (!mActions.isEmpty()) {
5764                wearableBundle.putParcelableArrayList(KEY_ACTIONS, mActions);
5765            }
5766            if (mFlags != DEFAULT_FLAGS) {
5767                wearableBundle.putInt(KEY_FLAGS, mFlags);
5768            }
5769            if (mDisplayIntent != null) {
5770                wearableBundle.putParcelable(KEY_DISPLAY_INTENT, mDisplayIntent);
5771            }
5772            if (!mPages.isEmpty()) {
5773                wearableBundle.putParcelableArray(KEY_PAGES, mPages.toArray(
5774                        new Notification[mPages.size()]));
5775            }
5776            if (mBackground != null) {
5777                wearableBundle.putParcelable(KEY_BACKGROUND, mBackground);
5778            }
5779            if (mContentIcon != 0) {
5780                wearableBundle.putInt(KEY_CONTENT_ICON, mContentIcon);
5781            }
5782            if (mContentIconGravity != DEFAULT_CONTENT_ICON_GRAVITY) {
5783                wearableBundle.putInt(KEY_CONTENT_ICON_GRAVITY, mContentIconGravity);
5784            }
5785            if (mContentActionIndex != UNSET_ACTION_INDEX) {
5786                wearableBundle.putInt(KEY_CONTENT_ACTION_INDEX,
5787                        mContentActionIndex);
5788            }
5789            if (mCustomSizePreset != SIZE_DEFAULT) {
5790                wearableBundle.putInt(KEY_CUSTOM_SIZE_PRESET, mCustomSizePreset);
5791            }
5792            if (mCustomContentHeight != 0) {
5793                wearableBundle.putInt(KEY_CUSTOM_CONTENT_HEIGHT, mCustomContentHeight);
5794            }
5795            if (mGravity != DEFAULT_GRAVITY) {
5796                wearableBundle.putInt(KEY_GRAVITY, mGravity);
5797            }
5798            if (mHintScreenTimeout != 0) {
5799                wearableBundle.putInt(KEY_HINT_SCREEN_TIMEOUT, mHintScreenTimeout);
5800            }
5801            if (mDismissalId != null) {
5802                wearableBundle.putString(KEY_DISMISSAL_ID, mDismissalId);
5803            }
5804
5805            builder.getExtras().putBundle(EXTRA_WEARABLE_EXTENSIONS, wearableBundle);
5806            return builder;
5807        }
5808
5809        @Override
5810        public WearableExtender clone() {
5811            WearableExtender that = new WearableExtender();
5812            that.mActions = new ArrayList<Action>(this.mActions);
5813            that.mFlags = this.mFlags;
5814            that.mDisplayIntent = this.mDisplayIntent;
5815            that.mPages = new ArrayList<Notification>(this.mPages);
5816            that.mBackground = this.mBackground;
5817            that.mContentIcon = this.mContentIcon;
5818            that.mContentIconGravity = this.mContentIconGravity;
5819            that.mContentActionIndex = this.mContentActionIndex;
5820            that.mCustomSizePreset = this.mCustomSizePreset;
5821            that.mCustomContentHeight = this.mCustomContentHeight;
5822            that.mGravity = this.mGravity;
5823            that.mHintScreenTimeout = this.mHintScreenTimeout;
5824            that.mDismissalId = this.mDismissalId;
5825            return that;
5826        }
5827
5828        /**
5829         * Add a wearable action to this notification.
5830         *
5831         * <p>When wearable actions are added using this method, the set of actions that
5832         * show on a wearable device splits from devices that only show actions added
5833         * using {@link android.app.Notification.Builder#addAction}. This allows for customization
5834         * of which actions display on different devices.
5835         *
5836         * @param action the action to add to this notification
5837         * @return this object for method chaining
5838         * @see android.app.Notification.Action
5839         */
5840        public WearableExtender addAction(Action action) {
5841            mActions.add(action);
5842            return this;
5843        }
5844
5845        /**
5846         * Adds wearable actions to this notification.
5847         *
5848         * <p>When wearable actions are added using this method, the set of actions that
5849         * show on a wearable device splits from devices that only show actions added
5850         * using {@link android.app.Notification.Builder#addAction}. This allows for customization
5851         * of which actions display on different devices.
5852         *
5853         * @param actions the actions to add to this notification
5854         * @return this object for method chaining
5855         * @see android.app.Notification.Action
5856         */
5857        public WearableExtender addActions(List<Action> actions) {
5858            mActions.addAll(actions);
5859            return this;
5860        }
5861
5862        /**
5863         * Clear all wearable actions present on this builder.
5864         * @return this object for method chaining.
5865         * @see #addAction
5866         */
5867        public WearableExtender clearActions() {
5868            mActions.clear();
5869            return this;
5870        }
5871
5872        /**
5873         * Get the wearable actions present on this notification.
5874         */
5875        public List<Action> getActions() {
5876            return mActions;
5877        }
5878
5879        /**
5880         * Set an intent to launch inside of an activity view when displaying
5881         * this notification. The {@link PendingIntent} provided should be for an activity.
5882         *
5883         * <pre class="prettyprint">
5884         * Intent displayIntent = new Intent(context, MyDisplayActivity.class);
5885         * PendingIntent displayPendingIntent = PendingIntent.getActivity(context,
5886         *         0, displayIntent, PendingIntent.FLAG_UPDATE_CURRENT);
5887         * Notification notif = new Notification.Builder(context)
5888         *         .extend(new Notification.WearableExtender()
5889         *                 .setDisplayIntent(displayPendingIntent)
5890         *                 .setCustomSizePreset(Notification.WearableExtender.SIZE_MEDIUM))
5891         *         .build();</pre>
5892         *
5893         * <p>The activity to launch needs to allow embedding, must be exported, and
5894         * should have an empty task affinity. It is also recommended to use the device
5895         * default light theme.
5896         *
5897         * <p>Example AndroidManifest.xml entry:
5898         * <pre class="prettyprint">
5899         * &lt;activity android:name=&quot;com.example.MyDisplayActivity&quot;
5900         *     android:exported=&quot;true&quot;
5901         *     android:allowEmbedded=&quot;true&quot;
5902         *     android:taskAffinity=&quot;&quot;
5903         *     android:theme=&quot;@android:style/Theme.DeviceDefault.Light&quot; /&gt;</pre>
5904         *
5905         * @param intent the {@link PendingIntent} for an activity
5906         * @return this object for method chaining
5907         * @see android.app.Notification.WearableExtender#getDisplayIntent
5908         */
5909        public WearableExtender setDisplayIntent(PendingIntent intent) {
5910            mDisplayIntent = intent;
5911            return this;
5912        }
5913
5914        /**
5915         * Get the intent to launch inside of an activity view when displaying this
5916         * notification. This {@code PendingIntent} should be for an activity.
5917         */
5918        public PendingIntent getDisplayIntent() {
5919            return mDisplayIntent;
5920        }
5921
5922        /**
5923         * Add an additional page of content to display with this notification. The current
5924         * notification forms the first page, and pages added using this function form
5925         * subsequent pages. This field can be used to separate a notification into multiple
5926         * sections.
5927         *
5928         * @param page the notification to add as another page
5929         * @return this object for method chaining
5930         * @see android.app.Notification.WearableExtender#getPages
5931         */
5932        public WearableExtender addPage(Notification page) {
5933            mPages.add(page);
5934            return this;
5935        }
5936
5937        /**
5938         * Add additional pages of content to display with this notification. The current
5939         * notification forms the first page, and pages added using this function form
5940         * subsequent pages. This field can be used to separate a notification into multiple
5941         * sections.
5942         *
5943         * @param pages a list of notifications
5944         * @return this object for method chaining
5945         * @see android.app.Notification.WearableExtender#getPages
5946         */
5947        public WearableExtender addPages(List<Notification> pages) {
5948            mPages.addAll(pages);
5949            return this;
5950        }
5951
5952        /**
5953         * Clear all additional pages present on this builder.
5954         * @return this object for method chaining.
5955         * @see #addPage
5956         */
5957        public WearableExtender clearPages() {
5958            mPages.clear();
5959            return this;
5960        }
5961
5962        /**
5963         * Get the array of additional pages of content for displaying this notification. The
5964         * current notification forms the first page, and elements within this array form
5965         * subsequent pages. This field can be used to separate a notification into multiple
5966         * sections.
5967         * @return the pages for this notification
5968         */
5969        public List<Notification> getPages() {
5970            return mPages;
5971        }
5972
5973        /**
5974         * Set a background image to be displayed behind the notification content.
5975         * Contrary to the {@link android.app.Notification.BigPictureStyle}, this background
5976         * will work with any notification style.
5977         *
5978         * @param background the background bitmap
5979         * @return this object for method chaining
5980         * @see android.app.Notification.WearableExtender#getBackground
5981         */
5982        public WearableExtender setBackground(Bitmap background) {
5983            mBackground = background;
5984            return this;
5985        }
5986
5987        /**
5988         * Get a background image to be displayed behind the notification content.
5989         * Contrary to the {@link android.app.Notification.BigPictureStyle}, this background
5990         * will work with any notification style.
5991         *
5992         * @return the background image
5993         * @see android.app.Notification.WearableExtender#setBackground
5994         */
5995        public Bitmap getBackground() {
5996            return mBackground;
5997        }
5998
5999        /**
6000         * Set an icon that goes with the content of this notification.
6001         */
6002        public WearableExtender setContentIcon(int icon) {
6003            mContentIcon = icon;
6004            return this;
6005        }
6006
6007        /**
6008         * Get an icon that goes with the content of this notification.
6009         */
6010        public int getContentIcon() {
6011            return mContentIcon;
6012        }
6013
6014        /**
6015         * Set the gravity that the content icon should have within the notification display.
6016         * Supported values include {@link android.view.Gravity#START} and
6017         * {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}.
6018         * @see #setContentIcon
6019         */
6020        public WearableExtender setContentIconGravity(int contentIconGravity) {
6021            mContentIconGravity = contentIconGravity;
6022            return this;
6023        }
6024
6025        /**
6026         * Get the gravity that the content icon should have within the notification display.
6027         * Supported values include {@link android.view.Gravity#START} and
6028         * {@link android.view.Gravity#END}. The default value is {@link android.view.Gravity#END}.
6029         * @see #getContentIcon
6030         */
6031        public int getContentIconGravity() {
6032            return mContentIconGravity;
6033        }
6034
6035        /**
6036         * Set an action from this notification's actions to be clickable with the content of
6037         * this notification. This action will no longer display separately from the
6038         * notification's content.
6039         *
6040         * <p>For notifications with multiple pages, child pages can also have content actions
6041         * set, although the list of available actions comes from the main notification and not
6042         * from the child page's notification.
6043         *
6044         * @param actionIndex The index of the action to hoist onto the current notification page.
6045         *                    If wearable actions were added to the main notification, this index
6046         *                    will apply to that list, otherwise it will apply to the regular
6047         *                    actions list.
6048         */
6049        public WearableExtender setContentAction(int actionIndex) {
6050            mContentActionIndex = actionIndex;
6051            return this;
6052        }
6053
6054        /**
6055         * Get the index of the notification action, if any, that was specified as being clickable
6056         * with the content of this notification. This action will no longer display separately
6057         * from the notification's content.
6058         *
6059         * <p>For notifications with multiple pages, child pages can also have content actions
6060         * set, although the list of available actions comes from the main notification and not
6061         * from the child page's notification.
6062         *
6063         * <p>If wearable specific actions were added to the main notification, this index will
6064         * apply to that list, otherwise it will apply to the regular actions list.
6065         *
6066         * @return the action index or {@link #UNSET_ACTION_INDEX} if no action was selected.
6067         */
6068        public int getContentAction() {
6069            return mContentActionIndex;
6070        }
6071
6072        /**
6073         * Set the gravity that this notification should have within the available viewport space.
6074         * Supported values include {@link android.view.Gravity#TOP},
6075         * {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}.
6076         * The default value is {@link android.view.Gravity#BOTTOM}.
6077         */
6078        public WearableExtender setGravity(int gravity) {
6079            mGravity = gravity;
6080            return this;
6081        }
6082
6083        /**
6084         * Get the gravity that this notification should have within the available viewport space.
6085         * Supported values include {@link android.view.Gravity#TOP},
6086         * {@link android.view.Gravity#CENTER_VERTICAL} and {@link android.view.Gravity#BOTTOM}.
6087         * The default value is {@link android.view.Gravity#BOTTOM}.
6088         */
6089        public int getGravity() {
6090            return mGravity;
6091        }
6092
6093        /**
6094         * Set the custom size preset for the display of this notification out of the available
6095         * presets found in {@link android.app.Notification.WearableExtender}, e.g.
6096         * {@link #SIZE_LARGE}.
6097         * <p>Some custom size presets are only applicable for custom display notifications created
6098         * using {@link android.app.Notification.WearableExtender#setDisplayIntent}. Check the
6099         * documentation for the preset in question. See also
6100         * {@link #setCustomContentHeight} and {@link #getCustomSizePreset}.
6101         */
6102        public WearableExtender setCustomSizePreset(int sizePreset) {
6103            mCustomSizePreset = sizePreset;
6104            return this;
6105        }
6106
6107        /**
6108         * Get the custom size preset for the display of this notification out of the available
6109         * presets found in {@link android.app.Notification.WearableExtender}, e.g.
6110         * {@link #SIZE_LARGE}.
6111         * <p>Some custom size presets are only applicable for custom display notifications created
6112         * using {@link #setDisplayIntent}. Check the documentation for the preset in question.
6113         * See also {@link #setCustomContentHeight} and {@link #setCustomSizePreset}.
6114         */
6115        public int getCustomSizePreset() {
6116            return mCustomSizePreset;
6117        }
6118
6119        /**
6120         * Set the custom height in pixels for the display of this notification's content.
6121         * <p>This option is only available for custom display notifications created
6122         * using {@link android.app.Notification.WearableExtender#setDisplayIntent}. See also
6123         * {@link android.app.Notification.WearableExtender#setCustomSizePreset} and
6124         * {@link #getCustomContentHeight}.
6125         */
6126        public WearableExtender setCustomContentHeight(int height) {
6127            mCustomContentHeight = height;
6128            return this;
6129        }
6130
6131        /**
6132         * Get the custom height in pixels for the display of this notification's content.
6133         * <p>This option is only available for custom display notifications created
6134         * using {@link #setDisplayIntent}. See also {@link #setCustomSizePreset} and
6135         * {@link #setCustomContentHeight}.
6136         */
6137        public int getCustomContentHeight() {
6138            return mCustomContentHeight;
6139        }
6140
6141        /**
6142         * Set whether the scrolling position for the contents of this notification should start
6143         * at the bottom of the contents instead of the top when the contents are too long to
6144         * display within the screen.  Default is false (start scroll at the top).
6145         */
6146        public WearableExtender setStartScrollBottom(boolean startScrollBottom) {
6147            setFlag(FLAG_START_SCROLL_BOTTOM, startScrollBottom);
6148            return this;
6149        }
6150
6151        /**
6152         * Get whether the scrolling position for the contents of this notification should start
6153         * at the bottom of the contents instead of the top when the contents are too long to
6154         * display within the screen. Default is false (start scroll at the top).
6155         */
6156        public boolean getStartScrollBottom() {
6157            return (mFlags & FLAG_START_SCROLL_BOTTOM) != 0;
6158        }
6159
6160        /**
6161         * Set whether the content intent is available when the wearable device is not connected
6162         * to a companion device.  The user can still trigger this intent when the wearable device
6163         * is offline, but a visual hint will indicate that the content intent may not be available.
6164         * Defaults to true.
6165         */
6166        public WearableExtender setContentIntentAvailableOffline(
6167                boolean contentIntentAvailableOffline) {
6168            setFlag(FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE, contentIntentAvailableOffline);
6169            return this;
6170        }
6171
6172        /**
6173         * Get whether the content intent is available when the wearable device is not connected
6174         * to a companion device.  The user can still trigger this intent when the wearable device
6175         * is offline, but a visual hint will indicate that the content intent may not be available.
6176         * Defaults to true.
6177         */
6178        public boolean getContentIntentAvailableOffline() {
6179            return (mFlags & FLAG_CONTENT_INTENT_AVAILABLE_OFFLINE) != 0;
6180        }
6181
6182        /**
6183         * Set a hint that this notification's icon should not be displayed.
6184         * @param hintHideIcon {@code true} to hide the icon, {@code false} otherwise.
6185         * @return this object for method chaining
6186         */
6187        public WearableExtender setHintHideIcon(boolean hintHideIcon) {
6188            setFlag(FLAG_HINT_HIDE_ICON, hintHideIcon);
6189            return this;
6190        }
6191
6192        /**
6193         * Get a hint that this notification's icon should not be displayed.
6194         * @return {@code true} if this icon should not be displayed, false otherwise.
6195         * The default value is {@code false} if this was never set.
6196         */
6197        public boolean getHintHideIcon() {
6198            return (mFlags & FLAG_HINT_HIDE_ICON) != 0;
6199        }
6200
6201        /**
6202         * Set a visual hint that only the background image of this notification should be
6203         * displayed, and other semantic content should be hidden. This hint is only applicable
6204         * to sub-pages added using {@link #addPage}.
6205         */
6206        public WearableExtender setHintShowBackgroundOnly(boolean hintShowBackgroundOnly) {
6207            setFlag(FLAG_HINT_SHOW_BACKGROUND_ONLY, hintShowBackgroundOnly);
6208            return this;
6209        }
6210
6211        /**
6212         * Get a visual hint that only the background image of this notification should be
6213         * displayed, and other semantic content should be hidden. This hint is only applicable
6214         * to sub-pages added using {@link android.app.Notification.WearableExtender#addPage}.
6215         */
6216        public boolean getHintShowBackgroundOnly() {
6217            return (mFlags & FLAG_HINT_SHOW_BACKGROUND_ONLY) != 0;
6218        }
6219
6220        /**
6221         * Set a hint that this notification's background should not be clipped if possible,
6222         * and should instead be resized to fully display on the screen, retaining the aspect
6223         * ratio of the image. This can be useful for images like barcodes or qr codes.
6224         * @param hintAvoidBackgroundClipping {@code true} to avoid clipping if possible.
6225         * @return this object for method chaining
6226         */
6227        public WearableExtender setHintAvoidBackgroundClipping(
6228                boolean hintAvoidBackgroundClipping) {
6229            setFlag(FLAG_HINT_AVOID_BACKGROUND_CLIPPING, hintAvoidBackgroundClipping);
6230            return this;
6231        }
6232
6233        /**
6234         * Get a hint that this notification's background should not be clipped if possible,
6235         * and should instead be resized to fully display on the screen, retaining the aspect
6236         * ratio of the image. This can be useful for images like barcodes or qr codes.
6237         * @return {@code true} if it's ok if the background is clipped on the screen, false
6238         * otherwise. The default value is {@code false} if this was never set.
6239         */
6240        public boolean getHintAvoidBackgroundClipping() {
6241            return (mFlags & FLAG_HINT_AVOID_BACKGROUND_CLIPPING) != 0;
6242        }
6243
6244        /**
6245         * Set a hint that the screen should remain on for at least this duration when
6246         * this notification is displayed on the screen.
6247         * @param timeout The requested screen timeout in milliseconds. Can also be either
6248         *     {@link #SCREEN_TIMEOUT_SHORT} or {@link #SCREEN_TIMEOUT_LONG}.
6249         * @return this object for method chaining
6250         */
6251        public WearableExtender setHintScreenTimeout(int timeout) {
6252            mHintScreenTimeout = timeout;
6253            return this;
6254        }
6255
6256        /**
6257         * Get the duration, in milliseconds, that the screen should remain on for
6258         * when this notification is displayed.
6259         * @return the duration in milliseconds if > 0, or either one of the sentinel values
6260         *     {@link #SCREEN_TIMEOUT_SHORT} or {@link #SCREEN_TIMEOUT_LONG}.
6261         */
6262        public int getHintScreenTimeout() {
6263            return mHintScreenTimeout;
6264        }
6265
6266        /**
6267         * Set a hint that this notification's {@link BigPictureStyle} (if present) should be
6268         * converted to low-bit and displayed in ambient mode, especially useful for barcodes and
6269         * qr codes, as well as other simple black-and-white tickets.
6270         * @param hintAmbientBigPicture {@code true} to enable converstion and ambient.
6271         * @return this object for method chaining
6272         */
6273        public WearableExtender setHintAmbientBigPicture(boolean hintAmbientBigPicture) {
6274            setFlag(FLAG_BIG_PICTURE_AMBIENT, hintAmbientBigPicture);
6275            return this;
6276        }
6277
6278        /**
6279         * Get a hint that this notification's {@link BigPictureStyle} (if present) should be
6280         * converted to low-bit and displayed in ambient mode, especially useful for barcodes and
6281         * qr codes, as well as other simple black-and-white tickets.
6282         * @return {@code true} if it should be displayed in ambient, false otherwise
6283         * otherwise. The default value is {@code false} if this was never set.
6284         */
6285        public boolean getHintAmbientBigPicture() {
6286            return (mFlags & FLAG_BIG_PICTURE_AMBIENT) != 0;
6287        }
6288
6289        /**
6290         * Set a hint that this notification's content intent will launch an {@link Activity}
6291         * directly, telling the platform that it can generate the appropriate transitions.
6292         * @param hintContentIntentLaunchesActivity {@code true} if the content intent will launch
6293         * an activity and transitions should be generated, false otherwise.
6294         * @return this object for method chaining
6295         */
6296        public WearableExtender setHintContentIntentLaunchesActivity(
6297                boolean hintContentIntentLaunchesActivity) {
6298            setFlag(FLAG_HINT_CONTENT_INTENT_LAUNCHES_ACTIVITY, hintContentIntentLaunchesActivity);
6299            return this;
6300        }
6301
6302        /**
6303         * Get a hint that this notification's content intent will launch an {@link Activity}
6304         * directly, telling the platform that it can generate the appropriate transitions
6305         * @return {@code true} if the content intent will launch an activity and transitions should
6306         * be generated, false otherwise. The default value is {@code false} if this was never set.
6307         */
6308        public boolean getHintContentIntentLaunchesActivity() {
6309            return (mFlags & FLAG_HINT_CONTENT_INTENT_LAUNCHES_ACTIVITY) != 0;
6310        }
6311
6312        /**
6313         * When you post a notification, if you set the dismissal id field, then when that
6314         * notification is canceled, notifications on other wearables and the paired Android phone
6315         * having that same dismissal id will also be canceled.  Note that this only works if you
6316         * have notification bridge mode set to NO_BRIDGING in your Wear app manifest.  See
6317         * <a href="{@docRoot}wear/notifications/index.html">Adding Wearable Features to
6318         * Notifications</a> for more information on how to use the bridge mode feature.
6319         * @param dismissalId the dismissal id of the notification.
6320         * @return this object for method chaining
6321         */
6322        public WearableExtender setDismissalId(String dismissalId) {
6323            mDismissalId = dismissalId;
6324            return this;
6325        }
6326
6327        /**
6328         * Returns the dismissal id of the notification.
6329         * @return the dismissal id of the notification or null if it has not been set.
6330         */
6331        public String getDismissalId() {
6332            return mDismissalId;
6333        }
6334
6335        private void setFlag(int mask, boolean value) {
6336            if (value) {
6337                mFlags |= mask;
6338            } else {
6339                mFlags &= ~mask;
6340            }
6341        }
6342    }
6343
6344    /**
6345     * <p>Helper class to add Android Auto extensions to notifications. To create a notification
6346     * with car extensions:
6347     *
6348     * <ol>
6349     *  <li>Create an {@link Notification.Builder}, setting any desired
6350     *  properties.
6351     *  <li>Create a {@link CarExtender}.
6352     *  <li>Set car-specific properties using the {@code add} and {@code set} methods of
6353     *  {@link CarExtender}.
6354     *  <li>Call {@link Notification.Builder#extend(Notification.Extender)}
6355     *  to apply the extensions to a notification.
6356     * </ol>
6357     *
6358     * <pre class="prettyprint">
6359     * Notification notification = new Notification.Builder(context)
6360     *         ...
6361     *         .extend(new CarExtender()
6362     *                 .set*(...))
6363     *         .build();
6364     * </pre>
6365     *
6366     * <p>Car extensions can be accessed on an existing notification by using the
6367     * {@code CarExtender(Notification)} constructor, and then using the {@code get} methods
6368     * to access values.
6369     */
6370    public static final class CarExtender implements Extender {
6371        private static final String TAG = "CarExtender";
6372
6373        private static final String EXTRA_CAR_EXTENDER = "android.car.EXTENSIONS";
6374        private static final String EXTRA_LARGE_ICON = "large_icon";
6375        private static final String EXTRA_CONVERSATION = "car_conversation";
6376        private static final String EXTRA_COLOR = "app_color";
6377
6378        private Bitmap mLargeIcon;
6379        private UnreadConversation mUnreadConversation;
6380        private int mColor = Notification.COLOR_DEFAULT;
6381
6382        /**
6383         * Create a {@link CarExtender} with default options.
6384         */
6385        public CarExtender() {
6386        }
6387
6388        /**
6389         * Create a {@link CarExtender} from the CarExtender options of an existing Notification.
6390         *
6391         * @param notif The notification from which to copy options.
6392         */
6393        public CarExtender(Notification notif) {
6394            Bundle carBundle = notif.extras == null ?
6395                    null : notif.extras.getBundle(EXTRA_CAR_EXTENDER);
6396            if (carBundle != null) {
6397                mLargeIcon = carBundle.getParcelable(EXTRA_LARGE_ICON);
6398                mColor = carBundle.getInt(EXTRA_COLOR, Notification.COLOR_DEFAULT);
6399
6400                Bundle b = carBundle.getBundle(EXTRA_CONVERSATION);
6401                mUnreadConversation = UnreadConversation.getUnreadConversationFromBundle(b);
6402            }
6403        }
6404
6405        /**
6406         * Apply car extensions to a notification that is being built. This is typically called by
6407         * the {@link Notification.Builder#extend(Notification.Extender)}
6408         * method of {@link Notification.Builder}.
6409         */
6410        @Override
6411        public Notification.Builder extend(Notification.Builder builder) {
6412            Bundle carExtensions = new Bundle();
6413
6414            if (mLargeIcon != null) {
6415                carExtensions.putParcelable(EXTRA_LARGE_ICON, mLargeIcon);
6416            }
6417            if (mColor != Notification.COLOR_DEFAULT) {
6418                carExtensions.putInt(EXTRA_COLOR, mColor);
6419            }
6420
6421            if (mUnreadConversation != null) {
6422                Bundle b = mUnreadConversation.getBundleForUnreadConversation();
6423                carExtensions.putBundle(EXTRA_CONVERSATION, b);
6424            }
6425
6426            builder.getExtras().putBundle(EXTRA_CAR_EXTENDER, carExtensions);
6427            return builder;
6428        }
6429
6430        /**
6431         * Sets the accent color to use when Android Auto presents the notification.
6432         *
6433         * Android Auto uses the color set with {@link Notification.Builder#setColor(int)}
6434         * to accent the displayed notification. However, not all colors are acceptable in an
6435         * automotive setting. This method can be used to override the color provided in the
6436         * notification in such a situation.
6437         */
6438        public CarExtender setColor(@ColorInt int color) {
6439            mColor = color;
6440            return this;
6441        }
6442
6443        /**
6444         * Gets the accent color.
6445         *
6446         * @see #setColor
6447         */
6448        @ColorInt
6449        public int getColor() {
6450            return mColor;
6451        }
6452
6453        /**
6454         * Sets the large icon of the car notification.
6455         *
6456         * If no large icon is set in the extender, Android Auto will display the icon
6457         * specified by {@link Notification.Builder#setLargeIcon(android.graphics.Bitmap)}
6458         *
6459         * @param largeIcon The large icon to use in the car notification.
6460         * @return This object for method chaining.
6461         */
6462        public CarExtender setLargeIcon(Bitmap largeIcon) {
6463            mLargeIcon = largeIcon;
6464            return this;
6465        }
6466
6467        /**
6468         * Gets the large icon used in this car notification, or null if no icon has been set.
6469         *
6470         * @return The large icon for the car notification.
6471         * @see CarExtender#setLargeIcon
6472         */
6473        public Bitmap getLargeIcon() {
6474            return mLargeIcon;
6475        }
6476
6477        /**
6478         * Sets the unread conversation in a message notification.
6479         *
6480         * @param unreadConversation The unread part of the conversation this notification conveys.
6481         * @return This object for method chaining.
6482         */
6483        public CarExtender setUnreadConversation(UnreadConversation unreadConversation) {
6484            mUnreadConversation = unreadConversation;
6485            return this;
6486        }
6487
6488        /**
6489         * Returns the unread conversation conveyed by this notification.
6490         * @see #setUnreadConversation(UnreadConversation)
6491         */
6492        public UnreadConversation getUnreadConversation() {
6493            return mUnreadConversation;
6494        }
6495
6496        /**
6497         * A class which holds the unread messages from a conversation.
6498         */
6499        public static class UnreadConversation {
6500            private static final String KEY_AUTHOR = "author";
6501            private static final String KEY_TEXT = "text";
6502            private static final String KEY_MESSAGES = "messages";
6503            private static final String KEY_REMOTE_INPUT = "remote_input";
6504            private static final String KEY_ON_REPLY = "on_reply";
6505            private static final String KEY_ON_READ = "on_read";
6506            private static final String KEY_PARTICIPANTS = "participants";
6507            private static final String KEY_TIMESTAMP = "timestamp";
6508
6509            private final String[] mMessages;
6510            private final RemoteInput mRemoteInput;
6511            private final PendingIntent mReplyPendingIntent;
6512            private final PendingIntent mReadPendingIntent;
6513            private final String[] mParticipants;
6514            private final long mLatestTimestamp;
6515
6516            UnreadConversation(String[] messages, RemoteInput remoteInput,
6517                    PendingIntent replyPendingIntent, PendingIntent readPendingIntent,
6518                    String[] participants, long latestTimestamp) {
6519                mMessages = messages;
6520                mRemoteInput = remoteInput;
6521                mReadPendingIntent = readPendingIntent;
6522                mReplyPendingIntent = replyPendingIntent;
6523                mParticipants = participants;
6524                mLatestTimestamp = latestTimestamp;
6525            }
6526
6527            /**
6528             * Gets the list of messages conveyed by this notification.
6529             */
6530            public String[] getMessages() {
6531                return mMessages;
6532            }
6533
6534            /**
6535             * Gets the remote input that will be used to convey the response to a message list, or
6536             * null if no such remote input exists.
6537             */
6538            public RemoteInput getRemoteInput() {
6539                return mRemoteInput;
6540            }
6541
6542            /**
6543             * Gets the pending intent that will be triggered when the user replies to this
6544             * notification.
6545             */
6546            public PendingIntent getReplyPendingIntent() {
6547                return mReplyPendingIntent;
6548            }
6549
6550            /**
6551             * Gets the pending intent that Android Auto will send after it reads aloud all messages
6552             * in this object's message list.
6553             */
6554            public PendingIntent getReadPendingIntent() {
6555                return mReadPendingIntent;
6556            }
6557
6558            /**
6559             * Gets the participants in the conversation.
6560             */
6561            public String[] getParticipants() {
6562                return mParticipants;
6563            }
6564
6565            /**
6566             * Gets the firs participant in the conversation.
6567             */
6568            public String getParticipant() {
6569                return mParticipants.length > 0 ? mParticipants[0] : null;
6570            }
6571
6572            /**
6573             * Gets the timestamp of the conversation.
6574             */
6575            public long getLatestTimestamp() {
6576                return mLatestTimestamp;
6577            }
6578
6579            Bundle getBundleForUnreadConversation() {
6580                Bundle b = new Bundle();
6581                String author = null;
6582                if (mParticipants != null && mParticipants.length > 1) {
6583                    author = mParticipants[0];
6584                }
6585                Parcelable[] messages = new Parcelable[mMessages.length];
6586                for (int i = 0; i < messages.length; i++) {
6587                    Bundle m = new Bundle();
6588                    m.putString(KEY_TEXT, mMessages[i]);
6589                    m.putString(KEY_AUTHOR, author);
6590                    messages[i] = m;
6591                }
6592                b.putParcelableArray(KEY_MESSAGES, messages);
6593                if (mRemoteInput != null) {
6594                    b.putParcelable(KEY_REMOTE_INPUT, mRemoteInput);
6595                }
6596                b.putParcelable(KEY_ON_REPLY, mReplyPendingIntent);
6597                b.putParcelable(KEY_ON_READ, mReadPendingIntent);
6598                b.putStringArray(KEY_PARTICIPANTS, mParticipants);
6599                b.putLong(KEY_TIMESTAMP, mLatestTimestamp);
6600                return b;
6601            }
6602
6603            static UnreadConversation getUnreadConversationFromBundle(Bundle b) {
6604                if (b == null) {
6605                    return null;
6606                }
6607                Parcelable[] parcelableMessages = b.getParcelableArray(KEY_MESSAGES);
6608                String[] messages = null;
6609                if (parcelableMessages != null) {
6610                    String[] tmp = new String[parcelableMessages.length];
6611                    boolean success = true;
6612                    for (int i = 0; i < tmp.length; i++) {
6613                        if (!(parcelableMessages[i] instanceof Bundle)) {
6614                            success = false;
6615                            break;
6616                        }
6617                        tmp[i] = ((Bundle) parcelableMessages[i]).getString(KEY_TEXT);
6618                        if (tmp[i] == null) {
6619                            success = false;
6620                            break;
6621                        }
6622                    }
6623                    if (success) {
6624                        messages = tmp;
6625                    } else {
6626                        return null;
6627                    }
6628                }
6629
6630                PendingIntent onRead = b.getParcelable(KEY_ON_READ);
6631                PendingIntent onReply = b.getParcelable(KEY_ON_REPLY);
6632
6633                RemoteInput remoteInput = b.getParcelable(KEY_REMOTE_INPUT);
6634
6635                String[] participants = b.getStringArray(KEY_PARTICIPANTS);
6636                if (participants == null || participants.length != 1) {
6637                    return null;
6638                }
6639
6640                return new UnreadConversation(messages,
6641                        remoteInput,
6642                        onReply,
6643                        onRead,
6644                        participants, b.getLong(KEY_TIMESTAMP));
6645            }
6646        };
6647
6648        /**
6649         * Builder class for {@link CarExtender.UnreadConversation} objects.
6650         */
6651        public static class Builder {
6652            private final List<String> mMessages = new ArrayList<String>();
6653            private final String mParticipant;
6654            private RemoteInput mRemoteInput;
6655            private PendingIntent mReadPendingIntent;
6656            private PendingIntent mReplyPendingIntent;
6657            private long mLatestTimestamp;
6658
6659            /**
6660             * Constructs a new builder for {@link CarExtender.UnreadConversation}.
6661             *
6662             * @param name The name of the other participant in the conversation.
6663             */
6664            public Builder(String name) {
6665                mParticipant = name;
6666            }
6667
6668            /**
6669             * Appends a new unread message to the list of messages for this conversation.
6670             *
6671             * The messages should be added from oldest to newest.
6672             *
6673             * @param message The text of the new unread message.
6674             * @return This object for method chaining.
6675             */
6676            public Builder addMessage(String message) {
6677                mMessages.add(message);
6678                return this;
6679            }
6680
6681            /**
6682             * Sets the pending intent and remote input which will convey the reply to this
6683             * notification.
6684             *
6685             * @param pendingIntent The pending intent which will be triggered on a reply.
6686             * @param remoteInput The remote input parcelable which will carry the reply.
6687             * @return This object for method chaining.
6688             *
6689             * @see CarExtender.UnreadConversation#getRemoteInput
6690             * @see CarExtender.UnreadConversation#getReplyPendingIntent
6691             */
6692            public Builder setReplyAction(
6693                    PendingIntent pendingIntent, RemoteInput remoteInput) {
6694                mRemoteInput = remoteInput;
6695                mReplyPendingIntent = pendingIntent;
6696
6697                return this;
6698            }
6699
6700            /**
6701             * Sets the pending intent that will be sent once the messages in this notification
6702             * are read.
6703             *
6704             * @param pendingIntent The pending intent to use.
6705             * @return This object for method chaining.
6706             */
6707            public Builder setReadPendingIntent(PendingIntent pendingIntent) {
6708                mReadPendingIntent = pendingIntent;
6709                return this;
6710            }
6711
6712            /**
6713             * Sets the timestamp of the most recent message in an unread conversation.
6714             *
6715             * If a messaging notification has been posted by your application and has not
6716             * yet been cancelled, posting a later notification with the same id and tag
6717             * but without a newer timestamp may result in Android Auto not displaying a
6718             * heads up notification for the later notification.
6719             *
6720             * @param timestamp The timestamp of the most recent message in the conversation.
6721             * @return This object for method chaining.
6722             */
6723            public Builder setLatestTimestamp(long timestamp) {
6724                mLatestTimestamp = timestamp;
6725                return this;
6726            }
6727
6728            /**
6729             * Builds a new unread conversation object.
6730             *
6731             * @return The new unread conversation object.
6732             */
6733            public UnreadConversation build() {
6734                String[] messages = mMessages.toArray(new String[mMessages.size()]);
6735                String[] participants = { mParticipant };
6736                return new UnreadConversation(messages, mRemoteInput, mReplyPendingIntent,
6737                        mReadPendingIntent, participants, mLatestTimestamp);
6738            }
6739        }
6740    }
6741
6742    /**
6743     * Get an array of Notification objects from a parcelable array bundle field.
6744     * Update the bundle to have a typed array so fetches in the future don't need
6745     * to do an array copy.
6746     */
6747    private static Notification[] getNotificationArrayFromBundle(Bundle bundle, String key) {
6748        Parcelable[] array = bundle.getParcelableArray(key);
6749        if (array instanceof Notification[] || array == null) {
6750            return (Notification[]) array;
6751        }
6752        Notification[] typedArray = Arrays.copyOf(array, array.length,
6753                Notification[].class);
6754        bundle.putParcelableArray(key, typedArray);
6755        return typedArray;
6756    }
6757
6758    private static class BuilderRemoteViews extends RemoteViews {
6759        public BuilderRemoteViews(Parcel parcel) {
6760            super(parcel);
6761        }
6762
6763        public BuilderRemoteViews(ApplicationInfo appInfo, int layoutId) {
6764            super(appInfo, layoutId);
6765        }
6766
6767        @Override
6768        public BuilderRemoteViews clone() {
6769            Parcel p = Parcel.obtain();
6770            writeToParcel(p, 0);
6771            p.setDataPosition(0);
6772            BuilderRemoteViews brv = new BuilderRemoteViews(p);
6773            p.recycle();
6774            return brv;
6775        }
6776    }
6777}
6778