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