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 
17 package android.app;
18 
19 import android.annotation.IntDef;
20 import android.annotation.NonNull;
21 import android.annotation.Nullable;
22 import android.annotation.SdkConstant;
23 import android.annotation.SystemApi;
24 import android.annotation.SystemService;
25 import android.annotation.TestApi;
26 import android.app.Notification.Builder;
27 import android.compat.annotation.UnsupportedAppUsage;
28 import android.content.ComponentName;
29 import android.content.Context;
30 import android.content.Intent;
31 import android.content.pm.ParceledListSlice;
32 import android.content.pm.ShortcutInfo;
33 import android.graphics.drawable.Icon;
34 import android.net.Uri;
35 import android.os.Build;
36 import android.os.Bundle;
37 import android.os.Handler;
38 import android.os.IBinder;
39 import android.os.Parcel;
40 import android.os.Parcelable;
41 import android.os.RemoteException;
42 import android.os.ServiceManager;
43 import android.os.StrictMode;
44 import android.os.UserHandle;
45 import android.provider.Settings.Global;
46 import android.service.notification.Adjustment;
47 import android.service.notification.Condition;
48 import android.service.notification.StatusBarNotification;
49 import android.service.notification.ZenModeConfig;
50 import android.service.notification.ZenPolicy;
51 import android.util.Log;
52 import android.util.proto.ProtoOutputStream;
53 
54 import java.lang.annotation.Retention;
55 import java.lang.annotation.RetentionPolicy;
56 import java.util.ArrayList;
57 import java.util.Arrays;
58 import java.util.HashMap;
59 import java.util.List;
60 import java.util.Map;
61 import java.util.Objects;
62 
63 /**
64  * Class to notify the user of events that happen.  This is how you tell
65  * the user that something has happened in the background. {@more}
66  *
67  * Notifications can take different forms:
68  * <ul>
69  *      <li>A persistent icon that goes in the status bar and is accessible
70  *          through the launcher, (when the user selects it, a designated Intent
71  *          can be launched),</li>
72  *      <li>Turning on or flashing LEDs on the device, or</li>
73  *      <li>Alerting the user by flashing the backlight, playing a sound,
74  *          or vibrating.</li>
75  * </ul>
76  *
77  * <p>
78  * Each of the notify methods takes an int id parameter and optionally a
79  * {@link String} tag parameter, which may be {@code null}.  These parameters
80  * are used to form a pair (tag, id), or ({@code null}, id) if tag is
81  * unspecified.  This pair identifies this notification from your app to the
82  * system, so that pair should be unique within your app.  If you call one
83  * of the notify methods with a (tag, id) pair that is currently active and
84  * a new set of notification parameters, it will be updated.  For example,
85  * if you pass a new status bar icon, the old icon in the status bar will
86  * be replaced with the new one.  This is also the same tag and id you pass
87  * to the {@link #cancel(int)} or {@link #cancel(String, int)} method to clear
88  * this notification.
89  *
90  * <div class="special reference">
91  * <h3>Developer Guides</h3>
92  * <p>For a guide to creating notifications, read the
93  * <a href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Status Bar Notifications</a>
94  * developer guide.</p>
95  * </div>
96  *
97  * @see android.app.Notification
98  */
99 @SystemService(Context.NOTIFICATION_SERVICE)
100 public class NotificationManager {
101     private static String TAG = "NotificationManager";
102     private static boolean localLOGV = false;
103 
104     /**
105      * Intent that is broadcast when an application is blocked or unblocked.
106      *
107      * This broadcast is only sent to the app whose block state has changed.
108      *
109      * Input: nothing
110      * Output: {@link #EXTRA_BLOCKED_STATE}
111      */
112     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
113     public static final String ACTION_APP_BLOCK_STATE_CHANGED =
114             "android.app.action.APP_BLOCK_STATE_CHANGED";
115 
116     /**
117      * Intent that is broadcast when a {@link NotificationChannel} is blocked
118      * (when {@link NotificationChannel#getImportance()} is {@link #IMPORTANCE_NONE}) or unblocked
119      * (when {@link NotificationChannel#getImportance()} is anything other than
120      * {@link #IMPORTANCE_NONE}).
121      *
122      * This broadcast is only sent to the app that owns the channel that has changed.
123      *
124      * Input: nothing
125      * Output: {@link #EXTRA_NOTIFICATION_CHANNEL_ID}
126      * Output: {@link #EXTRA_BLOCKED_STATE}
127      */
128     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
129     public static final String ACTION_NOTIFICATION_CHANNEL_BLOCK_STATE_CHANGED =
130             "android.app.action.NOTIFICATION_CHANNEL_BLOCK_STATE_CHANGED";
131 
132     /**
133      * Extra for {@link #ACTION_NOTIFICATION_CHANNEL_BLOCK_STATE_CHANGED} containing the id of the
134      * {@link NotificationChannel} which has a new blocked state.
135      *
136      * The value will be the {@link NotificationChannel#getId()} of the channel.
137      */
138     public static final String EXTRA_NOTIFICATION_CHANNEL_ID =
139             "android.app.extra.NOTIFICATION_CHANNEL_ID";
140 
141     /**
142      * Extra for {@link #ACTION_NOTIFICATION_CHANNEL_GROUP_BLOCK_STATE_CHANGED} containing the id
143      * of the {@link NotificationChannelGroup} which has a new blocked state.
144      *
145      * The value will be the {@link NotificationChannelGroup#getId()} of the group.
146      */
147     public static final String EXTRA_NOTIFICATION_CHANNEL_GROUP_ID =
148             "android.app.extra.NOTIFICATION_CHANNEL_GROUP_ID";
149 
150 
151     /**
152      * Extra for {@link #ACTION_NOTIFICATION_CHANNEL_BLOCK_STATE_CHANGED} or
153      * {@link #ACTION_NOTIFICATION_CHANNEL_GROUP_BLOCK_STATE_CHANGED} containing the new blocked
154      * state as a boolean.
155      *
156      * The value will be {@code true} if this channel or group is now blocked and {@code false} if
157      * this channel or group is now unblocked.
158      */
159     public static final String EXTRA_BLOCKED_STATE = "android.app.extra.BLOCKED_STATE";
160 
161     /**
162      * Intent that is broadcast when a {@link NotificationChannelGroup} is
163      * {@link NotificationChannelGroup#isBlocked() blocked} or unblocked.
164      *
165      * This broadcast is only sent to the app that owns the channel group that has changed.
166      *
167      * Input: nothing
168      * Output: {@link #EXTRA_NOTIFICATION_CHANNEL_GROUP_ID}
169      * Output: {@link #EXTRA_BLOCKED_STATE}
170      */
171     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
172     public static final String ACTION_NOTIFICATION_CHANNEL_GROUP_BLOCK_STATE_CHANGED =
173             "android.app.action.NOTIFICATION_CHANNEL_GROUP_BLOCK_STATE_CHANGED";
174 
175     /**
176      * Intent that is broadcast when the status of an {@link AutomaticZenRule} has changed.
177      *
178      * <p>Use this to know whether you need to continue monitor to device state in order to
179      * provide up-to-date states (with {@link #setAutomaticZenRuleState(String, Condition)}) for
180      * this rule.</p>
181      *
182      * Input: nothing
183      * Output: {@link #EXTRA_AUTOMATIC_ZEN_RULE_ID}
184      * Output: {@link #EXTRA_AUTOMATIC_ZEN_RULE_STATUS}
185      */
186     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
187     public static final String ACTION_AUTOMATIC_ZEN_RULE_STATUS_CHANGED =
188             "android.app.action.AUTOMATIC_ZEN_RULE_STATUS_CHANGED";
189 
190     /**
191      * Integer extra for {@link #ACTION_AUTOMATIC_ZEN_RULE_STATUS_CHANGED} containing the state of
192      * the {@link AutomaticZenRule}.
193      *
194      * <p>
195      *     The value will be one of {@link #AUTOMATIC_RULE_STATUS_ENABLED},
196      *     {@link #AUTOMATIC_RULE_STATUS_DISABLED}, {@link #AUTOMATIC_RULE_STATUS_REMOVED},
197      *     {@link #AUTOMATIC_RULE_STATUS_UNKNOWN}.
198      * </p>
199      */
200     public static final String EXTRA_AUTOMATIC_ZEN_RULE_STATUS =
201             "android.app.extra.AUTOMATIC_ZEN_RULE_STATUS";
202 
203     /**
204      * String extra for {@link #ACTION_AUTOMATIC_ZEN_RULE_STATUS_CHANGED} containing the id of the
205      * {@link AutomaticZenRule} (see {@link #addAutomaticZenRule(AutomaticZenRule)}) that has
206      * changed.
207      */
208     public static final String EXTRA_AUTOMATIC_ZEN_RULE_ID =
209             "android.app.extra.AUTOMATIC_ZEN_RULE_ID";
210 
211     /** @hide */
212     @IntDef(prefix = { "AUTOMATIC_RULE_STATUS" }, value = {
213             AUTOMATIC_RULE_STATUS_ENABLED, AUTOMATIC_RULE_STATUS_DISABLED,
214             AUTOMATIC_RULE_STATUS_REMOVED, AUTOMATIC_RULE_STATUS_UNKNOWN
215     })
216     @Retention(RetentionPolicy.SOURCE)
217     public @interface AutomaticZenRuleStatus {}
218 
219     /**
220      * Constant value for {@link #EXTRA_AUTOMATIC_ZEN_RULE_STATUS} - the current status of the
221      * rule is unknown at your target sdk version, and you should continue to provide state changes
222      * via {@link #setAutomaticZenRuleState(String, Condition)}.
223      */
224     public static final int AUTOMATIC_RULE_STATUS_UNKNOWN = -1;
225 
226     /**
227      * Constant value for {@link #EXTRA_AUTOMATIC_ZEN_RULE_STATUS} - the given rule currently
228      * exists and is enabled. You should continue to provide state changes via
229      * {@link #setAutomaticZenRuleState(String, Condition)}.
230      */
231     public static final int AUTOMATIC_RULE_STATUS_ENABLED = 1;
232 
233     /**
234      * Constant value for {@link #EXTRA_AUTOMATIC_ZEN_RULE_STATUS} - the given rule currently
235      * exists but is disabled. You do not need to continue to provide state changes via
236      * {@link #setAutomaticZenRuleState(String, Condition)} until the rule is reenabled.
237      */
238     public static final int AUTOMATIC_RULE_STATUS_DISABLED = 2;
239 
240     /**
241      * Constant value for {@link #EXTRA_AUTOMATIC_ZEN_RULE_STATUS} - the given rule has been
242      * deleted. Further calls to {@link #setAutomaticZenRuleState(String, Condition)} will be
243      * ignored.
244      */
245     public static final int AUTOMATIC_RULE_STATUS_REMOVED = 3;
246 
247     /**
248      * Intent that is broadcast when the state of {@link #getEffectsSuppressor()} changes.
249      * This broadcast is only sent to registered receivers.
250      *
251      * @hide
252      */
253     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
254     public static final String ACTION_EFFECTS_SUPPRESSOR_CHANGED
255             = "android.os.action.ACTION_EFFECTS_SUPPRESSOR_CHANGED";
256 
257     /**
258      * Intent that is broadcast when the state of {@link #isNotificationPolicyAccessGranted()}
259      * changes.
260      *
261      * This broadcast is only sent to registered receivers, and only to the apps that have changed.
262      */
263     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
264     public static final String ACTION_NOTIFICATION_POLICY_ACCESS_GRANTED_CHANGED
265             = "android.app.action.NOTIFICATION_POLICY_ACCESS_GRANTED_CHANGED";
266 
267     /**
268      * Intent that is broadcast when the state of getNotificationPolicy() changes.
269      * This broadcast is only sent to registered receivers.
270      */
271     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
272     public static final String ACTION_NOTIFICATION_POLICY_CHANGED
273             = "android.app.action.NOTIFICATION_POLICY_CHANGED";
274 
275     /**
276      * Intent that is broadcast when the state of getCurrentInterruptionFilter() changes.
277      * This broadcast is only sent to registered receivers.
278      */
279     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
280     public static final String ACTION_INTERRUPTION_FILTER_CHANGED
281             = "android.app.action.INTERRUPTION_FILTER_CHANGED";
282 
283     /**
284      * Intent that is broadcast when the state of getCurrentInterruptionFilter() changes.
285      * @hide
286      */
287     @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
288     public static final String ACTION_INTERRUPTION_FILTER_CHANGED_INTERNAL
289             = "android.app.action.INTERRUPTION_FILTER_CHANGED_INTERNAL";
290 
291     /** @hide */
292     @IntDef(prefix = { "INTERRUPTION_FILTER_" }, value = {
293             INTERRUPTION_FILTER_NONE, INTERRUPTION_FILTER_PRIORITY, INTERRUPTION_FILTER_ALARMS,
294             INTERRUPTION_FILTER_ALL, INTERRUPTION_FILTER_UNKNOWN
295     })
296     @Retention(RetentionPolicy.SOURCE)
297     public @interface InterruptionFilter {}
298 
299     /**
300      * {@link #getCurrentInterruptionFilter() Interruption filter} constant -
301      *     Normal interruption filter - no notifications are suppressed.
302      */
303     public static final int INTERRUPTION_FILTER_ALL = 1;
304 
305     /**
306      * {@link #getCurrentInterruptionFilter() Interruption filter} constant -
307      *     Priority interruption filter - all notifications are suppressed except those that match
308      *     the priority criteria. Some audio streams are muted. See
309      *     {@link Policy#priorityCallSenders}, {@link Policy#priorityCategories},
310      *     {@link Policy#priorityMessageSenders} to define or query this criteria. Users can
311      *     additionally specify packages that can bypass this interruption filter.
312      */
313     public static final int INTERRUPTION_FILTER_PRIORITY = 2;
314 
315     /**
316      * {@link #getCurrentInterruptionFilter() Interruption filter} constant -
317      *     No interruptions filter - all notifications are suppressed and all audio streams (except
318      *     those used for phone calls) and vibrations are muted.
319      */
320     public static final int INTERRUPTION_FILTER_NONE = 3;
321 
322     /**
323      * {@link #getCurrentInterruptionFilter() Interruption filter} constant -
324      *     Alarms only interruption filter - all notifications except those of category
325      *     {@link Notification#CATEGORY_ALARM} are suppressed. Some audio streams are muted.
326      */
327     public static final int INTERRUPTION_FILTER_ALARMS = 4;
328 
329     /** {@link #getCurrentInterruptionFilter() Interruption filter} constant - returned when
330      * the value is unavailable for any reason.
331      */
332     public static final int INTERRUPTION_FILTER_UNKNOWN = 0;
333 
334     /** @hide */
335     @IntDef(prefix = { "IMPORTANCE_" }, value = {
336             IMPORTANCE_UNSPECIFIED, IMPORTANCE_NONE,
337             IMPORTANCE_MIN, IMPORTANCE_LOW, IMPORTANCE_DEFAULT, IMPORTANCE_HIGH
338     })
339     @Retention(RetentionPolicy.SOURCE)
340     public @interface Importance {}
341 
342     /**
343      * Activity Action: Launch an Automatic Zen Rule configuration screen
344      * <p>
345      * Input: Optionally, {@link #EXTRA_AUTOMATIC_RULE_ID}, if the configuration screen for an
346      * existing rule should be displayed. If the rule id is missing or null, apps should display
347      * a configuration screen where users can create a new instance of the rule.
348      * <p>
349      * Output: Nothing
350      * <p>
351      *     You can have multiple activities handling this intent, if you support multiple
352      *     {@link AutomaticZenRule rules}. In order for the system to properly display all of your
353      *     rule types so that users can create new instances or configure existing ones, you need
354      *     to add some extra metadata ({@link #META_DATA_AUTOMATIC_RULE_TYPE})
355      *     to your activity tag in your manifest. If you'd like to limit the number of rules a user
356      *     can create from this flow, you can additionally optionally include
357      *     {@link #META_DATA_RULE_INSTANCE_LIMIT}.
358      *
359      *     For example,
360      *     &lt;meta-data
361      *         android:name="android.app.zen.automatic.ruleType"
362      *         android:value="@string/my_condition_rule">
363      *     &lt;/meta-data>
364      *     &lt;meta-data
365      *         android:name="android.app.zen.automatic.ruleInstanceLimit"
366      *         android:value="1">
367      *     &lt;/meta-data>
368      * </p>
369      * </p>
370      *
371      * @see #addAutomaticZenRule(AutomaticZenRule)
372      */
373     @SdkConstant(SdkConstant.SdkConstantType.ACTIVITY_INTENT_ACTION)
374     public static final String ACTION_AUTOMATIC_ZEN_RULE =
375             "android.app.action.AUTOMATIC_ZEN_RULE";
376 
377     /**
378      * Used as an optional string extra on {@link #ACTION_AUTOMATIC_ZEN_RULE} intents. If
379      * provided, contains the id of the {@link AutomaticZenRule} (as returned from
380      * {@link NotificationManager#addAutomaticZenRule(AutomaticZenRule)}) for which configuration
381      * settings should be displayed.
382      */
383     public static final String EXTRA_AUTOMATIC_RULE_ID = "android.app.extra.AUTOMATIC_RULE_ID";
384 
385     /**
386      * A required {@code meta-data} tag for activities that handle
387      * {@link #ACTION_AUTOMATIC_ZEN_RULE}.
388      *
389      * This tag should contain a localized name of the type of the zen rule provided by the
390      * activity.
391      */
392     public static final String META_DATA_AUTOMATIC_RULE_TYPE =
393             "android.service.zen.automatic.ruleType";
394 
395     /**
396      * An optional {@code meta-data} tag for activities that handle
397      * {@link #ACTION_AUTOMATIC_ZEN_RULE}.
398      *
399      * This tag should contain the maximum number of rule instances that
400      * can be created for this rule type. Omit or enter a value <= 0 to allow unlimited instances.
401      */
402     public static final String META_DATA_RULE_INSTANCE_LIMIT =
403             "android.service.zen.automatic.ruleInstanceLimit";
404 
405     /** Value signifying that the user has not expressed a per-app visibility override value.
406      * @hide */
407     public static final int VISIBILITY_NO_OVERRIDE = -1000;
408 
409     /**
410      * Value signifying that the user has not expressed an importance.
411      *
412      * This value is for persisting preferences, and should never be associated with
413      * an actual notification.
414      */
415     public static final int IMPORTANCE_UNSPECIFIED = -1000;
416 
417     /**
418      * A notification with no importance: does not show in the shade.
419      */
420     public static final int IMPORTANCE_NONE = 0;
421 
422     /**
423      * Min notification importance: only shows in the shade, below the fold.  This should
424      * not be used with {@link Service#startForeground(int, Notification) Service.startForeground}
425      * since a foreground service is supposed to be something the user cares about so it does
426      * not make semantic sense to mark its notification as minimum importance.  If you do this
427      * as of Android version {@link android.os.Build.VERSION_CODES#O}, the system will show
428      * a higher-priority notification about your app running in the background.
429      */
430     public static final int IMPORTANCE_MIN = 1;
431 
432     /**
433      * Low notification importance: Shows in the shade, and potentially in the status bar
434      * (see {@link #shouldHideSilentStatusBarIcons()}), but is not audibly intrusive.
435      */
436     public static final int IMPORTANCE_LOW = 2;
437 
438     /**
439      * Default notification importance: shows everywhere, makes noise, but does not visually
440      * intrude.
441      */
442     public static final int IMPORTANCE_DEFAULT = 3;
443 
444     /**
445      * Higher notification importance: shows everywhere, makes noise and peeks. May use full screen
446      * intents.
447      */
448     public static final int IMPORTANCE_HIGH = 4;
449 
450     /**
451      * Unused.
452      */
453     public static final int IMPORTANCE_MAX = 5;
454 
455     /**
456      * @hide
457      */
458     public static final int BUBBLE_PREFERENCE_NONE = 0;
459     /**
460      * @hide
461      */
462     public static final int BUBBLE_PREFERENCE_ALL = 1;
463     /**
464      * @hide
465      */
466     public static final int BUBBLE_PREFERENCE_SELECTED = 2;
467 
468     @UnsupportedAppUsage
469     private static INotificationManager sService;
470 
471     /** @hide */
472     @UnsupportedAppUsage
getService()473     static public INotificationManager getService()
474     {
475         if (sService != null) {
476             return sService;
477         }
478         IBinder b = ServiceManager.getService("notification");
479         sService = INotificationManager.Stub.asInterface(b);
480         return sService;
481     }
482 
483     @UnsupportedAppUsage
NotificationManager(Context context, Handler handler)484     /*package*/ NotificationManager(Context context, Handler handler)
485     {
486         mContext = context;
487     }
488 
489     /** {@hide} */
490     @UnsupportedAppUsage
from(Context context)491     public static NotificationManager from(Context context) {
492         return (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
493     }
494 
495     /**
496      * Post a notification to be shown in the status bar. If a notification with
497      * the same id has already been posted by your application and has not yet been canceled, it
498      * will be replaced by the updated information.
499      *
500      * @param id An identifier for this notification unique within your
501      *        application.
502      * @param notification A {@link Notification} object describing what to show the user. Must not
503      *        be null.
504      */
notify(int id, Notification notification)505     public void notify(int id, Notification notification)
506     {
507         notify(null, id, notification);
508     }
509 
510     /**
511      * Posts a notification to be shown in the status bar. If a notification with
512      * the same tag and id has already been posted by your application and has not yet been
513      * canceled, it will be replaced by the updated information.
514      *
515      * All {@link android.service.notification.NotificationListenerService listener services} will
516      * be granted {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} access to any {@link Uri uris}
517      * provided on this notification or the
518      * {@link NotificationChannel} this notification is posted to using
519      * {@link Context#grantUriPermission(String, Uri, int)}. Permission will be revoked when the
520      * notification is canceled, or you can revoke permissions with
521      * {@link Context#revokeUriPermission(Uri, int)}.
522      *
523      * @param tag A string identifier for this notification.  May be {@code null}.
524      * @param id An identifier for this notification.  The pair (tag, id) must be unique
525      *        within your application.
526      * @param notification A {@link Notification} object describing what to
527      *        show the user. Must not be null.
528      */
notify(String tag, int id, Notification notification)529     public void notify(String tag, int id, Notification notification)
530     {
531         notifyAsUser(tag, id, notification, mContext.getUser());
532     }
533 
534     /**
535      * Posts a notification as a specified package to be shown in the status bar. If a notification
536      * with the same tag and id has already been posted for that package and has not yet been
537      * canceled, it will be replaced by the updated information.
538      *
539      * All {@link android.service.notification.NotificationListenerService listener services} will
540      * be granted {@link Intent#FLAG_GRANT_READ_URI_PERMISSION} access to any {@link Uri uris}
541      * provided on this notification or the
542      * {@link NotificationChannel} this notification is posted to using
543      * {@link Context#grantUriPermission(String, Uri, int)}. Permission will be revoked when the
544      * notification is canceled, or you can revoke permissions with
545      * {@link Context#revokeUriPermission(Uri, int)}.
546      *
547      * @param targetPackage The package to post the notification as. The package must have granted
548      *                      you access to post notifications on their behalf with
549      *                      {@link #setNotificationDelegate(String)}.
550      * @param tag A string identifier for this notification.  May be {@code null}.
551      * @param id An identifier for this notification.  The pair (tag, id) must be unique
552      *        within your application.
553      * @param notification A {@link Notification} object describing what to
554      *        show the user. Must not be null.
555      */
notifyAsPackage(@onNull String targetPackage, @Nullable String tag, int id, @NonNull Notification notification)556     public void notifyAsPackage(@NonNull String targetPackage, @Nullable String tag, int id,
557             @NonNull Notification notification) {
558         INotificationManager service = getService();
559         String sender = mContext.getPackageName();
560 
561         try {
562             if (localLOGV) Log.v(TAG, sender + ": notify(" + id + ", " + notification + ")");
563             service.enqueueNotificationWithTag(targetPackage, sender, tag, id,
564                     fixNotification(notification), mContext.getUser().getIdentifier());
565         } catch (RemoteException e) {
566             throw e.rethrowFromSystemServer();
567         }
568     }
569 
570     /**
571      * @hide
572      */
573     @UnsupportedAppUsage
notifyAsUser(String tag, int id, Notification notification, UserHandle user)574     public void notifyAsUser(String tag, int id, Notification notification, UserHandle user)
575     {
576         INotificationManager service = getService();
577         String pkg = mContext.getPackageName();
578 
579         try {
580             if (localLOGV) Log.v(TAG, pkg + ": notify(" + id + ", " + notification + ")");
581             service.enqueueNotificationWithTag(pkg, mContext.getOpPackageName(), tag, id,
582                     fixNotification(notification), user.getIdentifier());
583         } catch (RemoteException e) {
584             throw e.rethrowFromSystemServer();
585         }
586     }
587 
fixNotification(Notification notification)588     private Notification fixNotification(Notification notification) {
589         String pkg = mContext.getPackageName();
590         // Fix the notification as best we can.
591         Notification.addFieldsFromContext(mContext, notification);
592 
593         if (notification.sound != null) {
594             notification.sound = notification.sound.getCanonicalUri();
595             if (StrictMode.vmFileUriExposureEnabled()) {
596                 notification.sound.checkFileUriExposed("Notification.sound");
597             }
598 
599         }
600         fixLegacySmallIcon(notification, pkg);
601         if (mContext.getApplicationInfo().targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
602             if (notification.getSmallIcon() == null) {
603                 throw new IllegalArgumentException("Invalid notification (no valid small icon): "
604                         + notification);
605             }
606         }
607 
608         notification.reduceImageSizes(mContext);
609         return Builder.maybeCloneStrippedForDelivery(notification);
610     }
611 
fixLegacySmallIcon(Notification n, String pkg)612     private void fixLegacySmallIcon(Notification n, String pkg) {
613         if (n.getSmallIcon() == null && n.icon != 0) {
614             n.setSmallIcon(Icon.createWithResource(pkg, n.icon));
615         }
616     }
617 
618     /**
619      * Cancels a previously posted notification.
620      *
621      *  <p>If the notification does not currently represent a
622      *  {@link Service#startForeground(int, Notification) foreground service}, it will be
623      *  removed from the UI and live
624      *  {@link android.service.notification.NotificationListenerService notification listeners}
625      *  will be informed so they can remove the notification from their UIs.</p>
626      */
cancel(int id)627     public void cancel(int id)
628     {
629         cancel(null, id);
630     }
631 
632     /**
633      * Cancels a previously posted notification.
634      *
635      *  <p>If the notification does not currently represent a
636      *  {@link Service#startForeground(int, Notification) foreground service}, it will be
637      *  removed from the UI and live
638      *  {@link android.service.notification.NotificationListenerService notification listeners}
639      *  will be informed so they can remove the notification from their UIs.</p>
640      */
cancel(@ullable String tag, int id)641     public void cancel(@Nullable String tag, int id)
642     {
643         cancelAsUser(tag, id, mContext.getUser());
644     }
645 
646     /**
647      * Cancels a previously posted notification.
648      *
649      * <p>If the notification does not currently represent a
650      * {@link Service#startForeground(int, Notification) foreground service}, it will be
651      * removed from the UI and live
652      * {@link android.service.notification.NotificationListenerService notification listeners}
653      * will be informed so they can remove the notification from their UIs.</p>
654      *
655      * <p>This method may be used by {@link #getNotificationDelegate() a notification delegate} to
656      * cancel notifications that they have posted via {@link #notifyAsPackage(String, String, int,
657      * Notification)}.</p>
658      *
659      * @param targetPackage The package to cancel the notification as. If this package is not your
660      *                      package, you can only cancel notifications you posted with
661      *                      {@link #notifyAsPackage(String, String, int, Notification).
662      * @param tag A string identifier for this notification.  May be {@code null}.
663      * @param id An identifier for this notification.
664      */
cancelAsPackage(@onNull String targetPackage, @Nullable String tag, int id)665     public void cancelAsPackage(@NonNull String targetPackage, @Nullable String tag, int id) {
666         INotificationManager service = getService();
667         try {
668             service.cancelNotificationWithTag(targetPackage, mContext.getOpPackageName(),
669                     tag, id, mContext.getUser().getIdentifier());
670         } catch (RemoteException e) {
671             throw e.rethrowFromSystemServer();
672         }
673     }
674 
675     /**
676      * @hide
677      */
678     @UnsupportedAppUsage
cancelAsUser(String tag, int id, UserHandle user)679     public void cancelAsUser(String tag, int id, UserHandle user)
680     {
681         INotificationManager service = getService();
682         String pkg = mContext.getPackageName();
683         if (localLOGV) Log.v(TAG, pkg + ": cancel(" + id + ")");
684         try {
685             service.cancelNotificationWithTag(
686                     pkg, mContext.getOpPackageName(), tag, id, user.getIdentifier());
687         } catch (RemoteException e) {
688             throw e.rethrowFromSystemServer();
689         }
690     }
691 
692     /**
693      * Cancel all previously shown notifications. See {@link #cancel} for the
694      * detailed behavior.
695      */
cancelAll()696     public void cancelAll()
697     {
698         INotificationManager service = getService();
699         String pkg = mContext.getPackageName();
700         if (localLOGV) Log.v(TAG, pkg + ": cancelAll()");
701         try {
702             service.cancelAllNotifications(pkg, mContext.getUserId());
703         } catch (RemoteException e) {
704             throw e.rethrowFromSystemServer();
705         }
706     }
707 
708     /**
709      * Allows a package to post notifications on your behalf using
710      * {@link #notifyAsPackage(String, String, int, Notification)}.
711      *
712      * This can be used to allow persistent processes to post notifications based on messages
713      * received on your behalf from the cloud, without your process having to wake up.
714      *
715      * You can check if you have an allowed delegate with {@link #getNotificationDelegate()} and
716      * revoke your delegate by passing null to this method.
717      *
718      * @param delegate Package name of the app which can send notifications on your behalf.
719      */
setNotificationDelegate(@ullable String delegate)720     public void setNotificationDelegate(@Nullable String delegate) {
721         INotificationManager service = getService();
722         String pkg = mContext.getPackageName();
723         if (localLOGV) Log.v(TAG, pkg + ": cancelAll()");
724         try {
725             service.setNotificationDelegate(pkg, delegate);
726         } catch (RemoteException e) {
727             throw e.rethrowFromSystemServer();
728         }
729     }
730 
731     /**
732      * Returns the {@link #setNotificationDelegate(String) delegate} that can post notifications on
733      * your behalf, if there currently is one.
734      */
getNotificationDelegate()735     public @Nullable String getNotificationDelegate() {
736         INotificationManager service = getService();
737         String pkg = mContext.getPackageName();
738         try {
739             return service.getNotificationDelegate(pkg);
740         } catch (RemoteException e) {
741             throw e.rethrowFromSystemServer();
742         }
743     }
744 
745     /**
746      * Returns whether you are allowed to post notifications on behalf of a given package, with
747      * {@link #notifyAsPackage(String, String, int, Notification)}.
748      *
749      * See {@link #setNotificationDelegate(String)}.
750      */
canNotifyAsPackage(@onNull String pkg)751     public boolean canNotifyAsPackage(@NonNull String pkg) {
752         INotificationManager service = getService();
753         try {
754             return service.canNotifyAsPackage(mContext.getPackageName(), pkg, mContext.getUserId());
755         } catch (RemoteException e) {
756             throw e.rethrowFromSystemServer();
757         }
758     }
759 
760     /**
761      * Creates a group container for {@link NotificationChannel} objects.
762      *
763      * This can be used to rename an existing group.
764      * <p>
765      *     Group information is only used for presentation, not for behavior. Groups are optional
766      *     for channels, and you can have a mix of channels that belong to groups and channels
767      *     that do not.
768      * </p>
769      * <p>
770      *     For example, if your application supports multiple accounts, and those accounts will
771      *     have similar channels, you can create a group for each account with account specific
772      *     labels instead of appending account information to each channel's label.
773      * </p>
774      *
775      * @param group The group to create
776      */
createNotificationChannelGroup(@onNull NotificationChannelGroup group)777     public void createNotificationChannelGroup(@NonNull NotificationChannelGroup group) {
778         createNotificationChannelGroups(Arrays.asList(group));
779     }
780 
781     /**
782      * Creates multiple notification channel groups.
783      *
784      * @param groups The list of groups to create
785      */
createNotificationChannelGroups(@onNull List<NotificationChannelGroup> groups)786     public void createNotificationChannelGroups(@NonNull List<NotificationChannelGroup> groups) {
787         INotificationManager service = getService();
788         try {
789             service.createNotificationChannelGroups(mContext.getPackageName(),
790                     new ParceledListSlice(groups));
791         } catch (RemoteException e) {
792             throw e.rethrowFromSystemServer();
793         }
794     }
795 
796     /**
797      * Creates a notification channel that notifications can be posted to.
798      *
799      * This can also be used to restore a deleted channel and to update an existing channel's
800      * name, description, group, and/or importance.
801      *
802      * <p>The name and description should only be changed if the locale changes
803      * or in response to the user renaming this channel. For example, if a user has a channel
804      * named 'John Doe' that represents messages from a 'John Doe', and 'John Doe' changes his name
805      * to 'John Smith,' the channel can be renamed to match.
806      *
807      * <p>The importance of an existing channel will only be changed if the new importance is lower
808      * than the current value and the user has not altered any settings on this channel.
809      *
810      * <p>The group an existing channel will only be changed if the channel does not already
811      * belong to a group.
812      *
813      * All other fields are ignored for channels that already exist.
814      *
815      * @param channel  the channel to create.  Note that the created channel may differ from this
816      *                 value. If the provided channel is malformed, a RemoteException will be
817      *                 thrown.
818      */
createNotificationChannel(@onNull NotificationChannel channel)819     public void createNotificationChannel(@NonNull NotificationChannel channel) {
820         createNotificationChannels(Arrays.asList(channel));
821     }
822 
823     /**
824      * Creates multiple notification channels that different notifications can be posted to. See
825      * {@link #createNotificationChannel(NotificationChannel)}.
826      *
827      * @param channels the list of channels to attempt to create.
828      */
createNotificationChannels(@onNull List<NotificationChannel> channels)829     public void createNotificationChannels(@NonNull List<NotificationChannel> channels) {
830         INotificationManager service = getService();
831         try {
832             service.createNotificationChannels(mContext.getPackageName(),
833                     new ParceledListSlice(channels));
834         } catch (RemoteException e) {
835             throw e.rethrowFromSystemServer();
836         }
837     }
838 
839     /**
840      * Returns the notification channel settings for a given channel id.
841      *
842      * <p>The channel must belong to your package, or to a package you are an approved notification
843      * delegate for (see {@link #canNotifyAsPackage(String)}), or it will not be returned. To query
844      * a channel as a notification delegate, call this method from a context created for that
845      * package (see {@link Context#createPackageContext(String, int)}).</p>
846      */
getNotificationChannel(String channelId)847     public NotificationChannel getNotificationChannel(String channelId) {
848         INotificationManager service = getService();
849         try {
850             return service.getNotificationChannel(mContext.getOpPackageName(),
851                     mContext.getUserId(), mContext.getPackageName(), channelId);
852         } catch (RemoteException e) {
853             throw e.rethrowFromSystemServer();
854         }
855     }
856 
857     /**
858      * Returns the notification channel settings for a given channel and
859      * {@link ShortcutInfo#getId() conversation id}.
860      *
861      * <p>The channel must belong to your package, or to a package you are an approved notification
862      * delegate for (see {@link #canNotifyAsPackage(String)}), or it will not be returned. To query
863      * a channel as a notification delegate, call this method from a context created for that
864      * package (see {@link Context#createPackageContext(String, int)}).</p>
865      */
getNotificationChannel(@onNull String channelId, @NonNull String conversationId)866     public @Nullable NotificationChannel getNotificationChannel(@NonNull String channelId,
867             @NonNull String conversationId) {
868         INotificationManager service = getService();
869         try {
870             return service.getConversationNotificationChannel(mContext.getOpPackageName(),
871                     mContext.getUserId(), mContext.getPackageName(), channelId, true,
872                     conversationId);
873         } catch (RemoteException e) {
874             throw e.rethrowFromSystemServer();
875         }
876     }
877 
878     /**
879      * Returns all notification channels belonging to the calling package.
880      *
881      * <p>Approved notification delegates (see {@link #canNotifyAsPackage(String)}) can query
882      * notification channels belonging to packages they are the delegate for. To do so, call this
883      * method from a context created for that package (see
884      * {@link Context#createPackageContext(String, int)}).</p>
885      */
getNotificationChannels()886     public List<NotificationChannel> getNotificationChannels() {
887         INotificationManager service = getService();
888         try {
889             return service.getNotificationChannels(mContext.getOpPackageName(),
890                     mContext.getPackageName(), mContext.getUserId()).getList();
891         } catch (RemoteException e) {
892             throw e.rethrowFromSystemServer();
893         }
894     }
895 
896     /**
897      * Deletes the given notification channel.
898      *
899      * <p>If you {@link #createNotificationChannel(NotificationChannel) create} a new channel with
900      * this same id, the deleted channel will be un-deleted with all of the same settings it
901      * had before it was deleted.
902      */
deleteNotificationChannel(String channelId)903     public void deleteNotificationChannel(String channelId) {
904         INotificationManager service = getService();
905         try {
906             service.deleteNotificationChannel(mContext.getPackageName(), channelId);
907         } catch (RemoteException e) {
908             throw e.rethrowFromSystemServer();
909         }
910     }
911 
912     /**
913      * Returns the notification channel group settings for a given channel group id.
914      *
915      * The channel group must belong to your package, or null will be returned.
916      */
getNotificationChannelGroup(String channelGroupId)917     public NotificationChannelGroup getNotificationChannelGroup(String channelGroupId) {
918         INotificationManager service = getService();
919         try {
920             return service.getNotificationChannelGroup(mContext.getPackageName(), channelGroupId);
921         } catch (RemoteException e) {
922             throw e.rethrowFromSystemServer();
923         }
924     }
925 
926     /**
927      * Returns all notification channel groups belonging to the calling app.
928      */
getNotificationChannelGroups()929     public List<NotificationChannelGroup> getNotificationChannelGroups() {
930         INotificationManager service = getService();
931         try {
932             final ParceledListSlice<NotificationChannelGroup> parceledList =
933                     service.getNotificationChannelGroups(mContext.getPackageName());
934             if (parceledList != null) {
935                 return parceledList.getList();
936             }
937         } catch (RemoteException e) {
938             throw e.rethrowFromSystemServer();
939         }
940         return new ArrayList<>();
941     }
942 
943     /**
944      * Deletes the given notification channel group, and all notification channels that
945      * belong to it.
946      */
deleteNotificationChannelGroup(String groupId)947     public void deleteNotificationChannelGroup(String groupId) {
948         INotificationManager service = getService();
949         try {
950             service.deleteNotificationChannelGroup(mContext.getPackageName(), groupId);
951         } catch (RemoteException e) {
952             throw e.rethrowFromSystemServer();
953         }
954     }
955 
956     /**
957      * @hide
958      */
959     @TestApi
getEffectsSuppressor()960     public ComponentName getEffectsSuppressor() {
961         INotificationManager service = getService();
962         try {
963             return service.getEffectsSuppressor();
964         } catch (RemoteException e) {
965             throw e.rethrowFromSystemServer();
966         }
967     }
968 
969     /**
970      * @hide
971      */
972     @TestApi
matchesCallFilter(Bundle extras)973     public boolean matchesCallFilter(Bundle extras) {
974         INotificationManager service = getService();
975         try {
976             return service.matchesCallFilter(extras);
977         } catch (RemoteException e) {
978             throw e.rethrowFromSystemServer();
979         }
980     }
981 
982     /**
983      * @hide
984      */
isSystemConditionProviderEnabled(String path)985     public boolean isSystemConditionProviderEnabled(String path) {
986         INotificationManager service = getService();
987         try {
988             return service.isSystemConditionProviderEnabled(path);
989         } catch (RemoteException e) {
990             throw e.rethrowFromSystemServer();
991         }
992     }
993 
994     /**
995      * @hide
996      */
997     @UnsupportedAppUsage
setZenMode(int mode, Uri conditionId, String reason)998     public void setZenMode(int mode, Uri conditionId, String reason) {
999         INotificationManager service = getService();
1000         try {
1001             service.setZenMode(mode, conditionId, reason);
1002         } catch (RemoteException e) {
1003             throw e.rethrowFromSystemServer();
1004         }
1005     }
1006 
1007     /**
1008      * @hide
1009      */
getZenMode()1010     public int getZenMode() {
1011         INotificationManager service = getService();
1012         try {
1013             return service.getZenMode();
1014         } catch (RemoteException e) {
1015             throw e.rethrowFromSystemServer();
1016         }
1017     }
1018 
1019     /**
1020      * @hide
1021      */
1022     @UnsupportedAppUsage
getZenModeConfig()1023     public ZenModeConfig getZenModeConfig() {
1024         INotificationManager service = getService();
1025         try {
1026             return service.getZenModeConfig();
1027         } catch (RemoteException e) {
1028             throw e.rethrowFromSystemServer();
1029         }
1030     }
1031 
1032     /**
1033      * Returns the currently applied notification policy.
1034      *
1035      * <p>
1036      * If {@link #getCurrentInterruptionFilter} is equal to {@link #INTERRUPTION_FILTER_ALL},
1037      * then the consolidated notification policy will match the default notification policy
1038      * returned by {@link #getNotificationPolicy}.
1039      * </p>
1040      */
getConsolidatedNotificationPolicy()1041     public @NonNull NotificationManager.Policy getConsolidatedNotificationPolicy() {
1042         INotificationManager service = getService();
1043         try {
1044             return service.getConsolidatedNotificationPolicy();
1045         } catch (RemoteException e) {
1046             throw e.rethrowFromSystemServer();
1047         }
1048     }
1049 
1050     /**
1051      * @hide
1052      */
getRuleInstanceCount(ComponentName owner)1053     public int getRuleInstanceCount(ComponentName owner) {
1054         INotificationManager service = getService();
1055         try {
1056             return service.getRuleInstanceCount(owner);
1057         } catch (RemoteException e) {
1058             throw e.rethrowFromSystemServer();
1059         }
1060     }
1061 
1062     /**
1063      * Returns AutomaticZenRules owned by the caller.
1064      *
1065      * <p>
1066      * Throws a SecurityException if policy access is not granted to this package.
1067      * See {@link #isNotificationPolicyAccessGranted}.
1068      */
getAutomaticZenRules()1069     public Map<String, AutomaticZenRule> getAutomaticZenRules() {
1070         INotificationManager service = getService();
1071         try {
1072             List<ZenModeConfig.ZenRule> rules = service.getZenRules();
1073             Map<String, AutomaticZenRule> ruleMap = new HashMap<>();
1074             for (ZenModeConfig.ZenRule rule : rules) {
1075                 ruleMap.put(rule.id, new AutomaticZenRule(rule.name, rule.component,
1076                         rule.configurationActivity, rule.conditionId, rule.zenPolicy,
1077                         zenModeToInterruptionFilter(rule.zenMode), rule.enabled,
1078                         rule.creationTime));
1079             }
1080             return ruleMap;
1081         } catch (RemoteException e) {
1082             throw e.rethrowFromSystemServer();
1083         }
1084     }
1085 
1086     /**
1087      * Returns the AutomaticZenRule with the given id, if it exists and the caller has access.
1088      *
1089      * <p>
1090      * Throws a SecurityException if policy access is not granted to this package.
1091      * See {@link #isNotificationPolicyAccessGranted}.
1092      *
1093      * <p>
1094      * Returns null if there are no zen rules that match the given id, or if the calling package
1095      * doesn't own the matching rule. See {@link AutomaticZenRule#getOwner}.
1096      */
getAutomaticZenRule(String id)1097     public AutomaticZenRule getAutomaticZenRule(String id) {
1098         INotificationManager service = getService();
1099         try {
1100             return service.getAutomaticZenRule(id);
1101         } catch (RemoteException e) {
1102             throw e.rethrowFromSystemServer();
1103         }
1104     }
1105 
1106     /**
1107      * Creates the given zen rule.
1108      *
1109      * <p>
1110      * Throws a SecurityException if policy access is not granted to this package.
1111      * See {@link #isNotificationPolicyAccessGranted}.
1112      *
1113      * @param automaticZenRule the rule to create.
1114      * @return The id of the newly created rule; null if the rule could not be created.
1115      */
addAutomaticZenRule(AutomaticZenRule automaticZenRule)1116     public String addAutomaticZenRule(AutomaticZenRule automaticZenRule) {
1117         INotificationManager service = getService();
1118         try {
1119             return service.addAutomaticZenRule(automaticZenRule);
1120         } catch (RemoteException e) {
1121             throw e.rethrowFromSystemServer();
1122         }
1123     }
1124 
1125     /**
1126      * Updates the given zen rule.
1127      *
1128      * <p>
1129      * Throws a SecurityException if policy access is not granted to this package.
1130      * See {@link #isNotificationPolicyAccessGranted}.
1131      *
1132      * <p>
1133      * Callers can only update rules that they own. See {@link AutomaticZenRule#getOwner}.
1134      * @param id The id of the rule to update
1135      * @param automaticZenRule the rule to update.
1136      * @return Whether the rule was successfully updated.
1137      */
updateAutomaticZenRule(String id, AutomaticZenRule automaticZenRule)1138     public boolean updateAutomaticZenRule(String id, AutomaticZenRule automaticZenRule) {
1139         INotificationManager service = getService();
1140         try {
1141             return service.updateAutomaticZenRule(id, automaticZenRule);
1142         } catch (RemoteException e) {
1143             throw e.rethrowFromSystemServer();
1144         }
1145     }
1146 
1147     /**
1148      * Informs the notification manager that the state of an {@link AutomaticZenRule} has changed.
1149      * Use this method to put the system into Do Not Disturb mode or request that it exits Do Not
1150      * Disturb mode. The calling app must own the provided {@link android.app.AutomaticZenRule}.
1151      * <p>
1152      *     This method can be used in conjunction with or as a replacement to
1153      *     {@link android.service.notification.ConditionProviderService#notifyCondition(Condition)}.
1154      * </p>
1155      * @param id The id of the rule whose state should change
1156      * @param condition The new state of this rule
1157      */
setAutomaticZenRuleState(@onNull String id, @NonNull Condition condition)1158     public void setAutomaticZenRuleState(@NonNull String id, @NonNull Condition condition) {
1159         INotificationManager service = getService();
1160         try {
1161             service.setAutomaticZenRuleState(id, condition);
1162         } catch (RemoteException e) {
1163             throw e.rethrowFromSystemServer();
1164         }
1165     }
1166 
1167     /**
1168      * Deletes the automatic zen rule with the given id.
1169      *
1170      * <p>
1171      * Throws a SecurityException if policy access is not granted to this package.
1172      * See {@link #isNotificationPolicyAccessGranted}.
1173      *
1174      * <p>
1175      * Callers can only delete rules that they own. See {@link AutomaticZenRule#getOwner}.
1176      * @param id the id of the rule to delete.
1177      * @return Whether the rule was successfully deleted.
1178      */
removeAutomaticZenRule(String id)1179     public boolean removeAutomaticZenRule(String id) {
1180         INotificationManager service = getService();
1181         try {
1182             return service.removeAutomaticZenRule(id);
1183         } catch (RemoteException e) {
1184             throw e.rethrowFromSystemServer();
1185         }
1186     }
1187 
1188     /**
1189      * Deletes all automatic zen rules owned by the given package.
1190      *
1191      * @hide
1192      */
removeAutomaticZenRules(String packageName)1193     public boolean removeAutomaticZenRules(String packageName) {
1194         INotificationManager service = getService();
1195         try {
1196             return service.removeAutomaticZenRules(packageName);
1197         } catch (RemoteException e) {
1198             throw e.rethrowFromSystemServer();
1199         }
1200     }
1201 
1202     /**
1203      * Returns the user specified importance for notifications from the calling
1204      * package.
1205      */
getImportance()1206     public @Importance int getImportance() {
1207         INotificationManager service = getService();
1208         try {
1209             return service.getPackageImportance(mContext.getPackageName());
1210         } catch (RemoteException e) {
1211             throw e.rethrowFromSystemServer();
1212         }
1213     }
1214 
1215     /**
1216      * Returns whether notifications from the calling package are blocked.
1217      */
areNotificationsEnabled()1218     public boolean areNotificationsEnabled() {
1219         INotificationManager service = getService();
1220         try {
1221             return service.areNotificationsEnabled(mContext.getPackageName());
1222         } catch (RemoteException e) {
1223             throw e.rethrowFromSystemServer();
1224         }
1225     }
1226 
1227 
1228     /**
1229      * Gets whether all notifications posted by this app can appear outside of the
1230      * notification shade, floating over other apps' content.
1231      *
1232      * <p>This value will be ignored for notifications that are posted to channels that do not
1233      * allow bubbles ({@link NotificationChannel#canBubble()}.
1234      *
1235      * @see Notification#getBubbleMetadata()
1236      */
areBubblesAllowed()1237     public boolean areBubblesAllowed() {
1238         INotificationManager service = getService();
1239         try {
1240             return service.areBubblesAllowed(mContext.getPackageName());
1241         } catch (RemoteException e) {
1242             throw e.rethrowFromSystemServer();
1243         }
1244     }
1245 
1246     /**
1247      * Silences the current notification sound, if ones currently playing.
1248      * <p>
1249      * It is intended to handle use-cases such as silencing a ringing call
1250      * when the user presses the volume button during ringing.
1251      * <p>
1252      * If this method is called prior to when the notification begins playing, the sound will not be
1253      * silenced.  As such it is not intended as a means to avoid playing of a sound.
1254      * @hide
1255      */
silenceNotificationSound()1256     public void silenceNotificationSound() {
1257         INotificationManager service = getService();
1258         try {
1259             service.silenceNotificationSound();
1260         } catch (RemoteException e) {
1261             throw e.rethrowFromSystemServer();
1262         }
1263     }
1264 
1265     /**
1266      * Returns whether notifications from this package are temporarily hidden. This
1267      * could be done because the package was marked as distracting to the user via
1268      * {@code PackageManager#setDistractingPackageRestrictions(String[], int)} or because the
1269      * package is {@code PackageManager#setPackagesSuspended(String[], boolean, PersistableBundle,
1270      * PersistableBundle, SuspendDialogInfo) suspended}.
1271      */
areNotificationsPaused()1272     public boolean areNotificationsPaused() {
1273         INotificationManager service = getService();
1274         try {
1275             return service.isPackagePaused(mContext.getPackageName());
1276         } catch (RemoteException e) {
1277             throw e.rethrowFromSystemServer();
1278         }
1279     }
1280 
1281     /**
1282      * Checks the ability to modify notification do not disturb policy for the calling package.
1283      *
1284      * <p>
1285      * Returns true if the calling package can modify notification policy.
1286      *
1287      * <p>
1288      * Apps can request policy access by sending the user to the activity that matches the system
1289      * intent action {@link android.provider.Settings#ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS}.
1290      *
1291      * <p>
1292      * Use {@link #ACTION_NOTIFICATION_POLICY_ACCESS_GRANTED_CHANGED} to listen for
1293      * user grant or denial of this access.
1294      */
isNotificationPolicyAccessGranted()1295     public boolean isNotificationPolicyAccessGranted() {
1296         INotificationManager service = getService();
1297         try {
1298             return service.isNotificationPolicyAccessGranted(mContext.getOpPackageName());
1299         } catch (RemoteException e) {
1300             throw e.rethrowFromSystemServer();
1301         }
1302     }
1303 
1304     /**
1305      * Checks whether the user has approved a given
1306      * {@link android.service.notification.NotificationListenerService}.
1307      *
1308      * <p>
1309      * The listener service must belong to the calling app.
1310      *
1311      * <p>
1312      * Apps can request notification listener access by sending the user to the activity that
1313      * matches the system intent action
1314      * {@link android.provider.Settings#ACTION_NOTIFICATION_LISTENER_SETTINGS}.
1315      */
isNotificationListenerAccessGranted(ComponentName listener)1316     public boolean isNotificationListenerAccessGranted(ComponentName listener) {
1317         INotificationManager service = getService();
1318         try {
1319             return service.isNotificationListenerAccessGranted(listener);
1320         } catch (RemoteException e) {
1321             throw e.rethrowFromSystemServer();
1322         }
1323     }
1324 
1325     /**
1326      * Checks whether the user has approved a given
1327      * {@link android.service.notification.NotificationAssistantService}.
1328      *
1329      * <p>
1330      * The assistant service must belong to the calling app.
1331      *
1332      * <p>
1333      * Apps can request notification assistant access by sending the user to the activity that
1334      * matches the system intent action
1335      * TODO: STOPSHIP: Add correct intent
1336      * {@link android.provider.Settings#ACTION_MANAGE_DEFAULT_APPS_SETTINGS}.
1337      * @hide
1338      */
1339     @SystemApi
1340     @TestApi
isNotificationAssistantAccessGranted(@onNull ComponentName assistant)1341     public boolean isNotificationAssistantAccessGranted(@NonNull ComponentName assistant) {
1342         INotificationManager service = getService();
1343         try {
1344             return service.isNotificationAssistantAccessGranted(assistant);
1345         } catch (RemoteException e) {
1346             throw e.rethrowFromSystemServer();
1347         }
1348     }
1349 
1350     /**
1351      * Returns whether the user wants silent notifications (see {@link #IMPORTANCE_LOW} to appear
1352      * in the status bar.
1353      *
1354      * <p>Only available for {@link #isNotificationListenerAccessGranted(ComponentName) notification
1355      * listeners}.
1356      */
shouldHideSilentStatusBarIcons()1357     public boolean shouldHideSilentStatusBarIcons() {
1358         INotificationManager service = getService();
1359         try {
1360             return service.shouldHideSilentStatusIcons(mContext.getOpPackageName());
1361         } catch (RemoteException e) {
1362             throw e.rethrowFromSystemServer();
1363         }
1364     }
1365 
1366     /**
1367      * Returns the list of {@link android.service.notification.Adjustment adjustment keys} that can
1368      * be modified by the current {@link android.service.notification.NotificationAssistantService}.
1369      *
1370      * <p>Only callable by the current
1371      * {@link android.service.notification.NotificationAssistantService}.
1372      * See {@link #isNotificationAssistantAccessGranted(ComponentName)}</p>
1373      * @hide
1374      */
1375     @SystemApi
1376     @TestApi
getAllowedAssistantAdjustments()1377     public @NonNull @Adjustment.Keys List<String> getAllowedAssistantAdjustments() {
1378         INotificationManager service = getService();
1379         try {
1380             return service.getAllowedAssistantAdjustments(mContext.getOpPackageName());
1381         } catch (RemoteException e) {
1382             throw e.rethrowFromSystemServer();
1383         }
1384     }
1385 
1386     /**
1387      * @hide
1388      */
1389     @TestApi
allowAssistantAdjustment(String capability)1390     public void allowAssistantAdjustment(String capability) {
1391         INotificationManager service = getService();
1392         try {
1393             service.allowAssistantAdjustment(capability);
1394         } catch (RemoteException e) {
1395             throw e.rethrowFromSystemServer();
1396         }
1397     }
1398 
1399     /**
1400      * @hide
1401      */
1402     @TestApi
disallowAssistantAdjustment(String capability)1403     public void disallowAssistantAdjustment(String capability) {
1404         INotificationManager service = getService();
1405         try {
1406             service.disallowAssistantAdjustment(capability);
1407         } catch (RemoteException e) {
1408             throw e.rethrowFromSystemServer();
1409         }
1410     }
1411 
1412     /** @hide */
isNotificationPolicyAccessGrantedForPackage(String pkg)1413     public boolean isNotificationPolicyAccessGrantedForPackage(String pkg) {
1414         INotificationManager service = getService();
1415         try {
1416             return service.isNotificationPolicyAccessGrantedForPackage(pkg);
1417         } catch (RemoteException e) {
1418             throw e.rethrowFromSystemServer();
1419         }
1420     }
1421 
1422     /**
1423      * @hide
1424      */
getEnabledNotificationListenerPackages()1425     public List<String> getEnabledNotificationListenerPackages() {
1426         INotificationManager service = getService();
1427         try {
1428             return service.getEnabledNotificationListenerPackages();
1429         } catch (RemoteException e) {
1430             throw e.rethrowFromSystemServer();
1431         }
1432     }
1433 
1434     /**
1435      * Gets the current user-specified default notification policy.
1436      *
1437      * <p>
1438      */
getNotificationPolicy()1439     public Policy getNotificationPolicy() {
1440         INotificationManager service = getService();
1441         try {
1442             return service.getNotificationPolicy(mContext.getOpPackageName());
1443         } catch (RemoteException e) {
1444             throw e.rethrowFromSystemServer();
1445         }
1446     }
1447 
1448     /**
1449      * Sets the current notification policy.
1450      *
1451      * <p>
1452      * Only available if policy access is granted to this package.
1453      * See {@link #isNotificationPolicyAccessGranted}.
1454      *
1455      * @param policy The new desired policy.
1456      */
setNotificationPolicy(@onNull Policy policy)1457     public void setNotificationPolicy(@NonNull Policy policy) {
1458         checkRequired("policy", policy);
1459         INotificationManager service = getService();
1460         try {
1461             service.setNotificationPolicy(mContext.getOpPackageName(), policy);
1462         } catch (RemoteException e) {
1463             throw e.rethrowFromSystemServer();
1464         }
1465     }
1466 
1467     /** @hide */
setNotificationPolicyAccessGranted(String pkg, boolean granted)1468     public void setNotificationPolicyAccessGranted(String pkg, boolean granted) {
1469         INotificationManager service = getService();
1470         try {
1471             service.setNotificationPolicyAccessGranted(pkg, granted);
1472         } catch (RemoteException e) {
1473             throw e.rethrowFromSystemServer();
1474         }
1475     }
1476 
1477     /** @hide */
setNotificationListenerAccessGranted(ComponentName listener, boolean granted)1478     public void setNotificationListenerAccessGranted(ComponentName listener, boolean granted) {
1479         INotificationManager service = getService();
1480         try {
1481             service.setNotificationListenerAccessGranted(listener, granted);
1482         } catch (RemoteException e) {
1483             throw e.rethrowFromSystemServer();
1484         }
1485     }
1486 
1487     /** @hide */
setNotificationListenerAccessGrantedForUser(ComponentName listener, int userId, boolean granted)1488     public void setNotificationListenerAccessGrantedForUser(ComponentName listener, int userId,
1489             boolean granted) {
1490         INotificationManager service = getService();
1491         try {
1492             service.setNotificationListenerAccessGrantedForUser(listener, userId, granted);
1493         } catch (RemoteException e) {
1494             throw e.rethrowFromSystemServer();
1495         }
1496     }
1497 
1498     /**
1499      * Grants/revokes Notification Assistant access to {@code assistant} for current user.
1500      * To grant access for a particular user, obtain this service by using the {@link Context}
1501      * provided by {@link Context#createPackageContextAsUser}
1502      *
1503      * @param assistant Name of component to grant/revoke access or {@code null} to revoke access to
1504      *                  current assistant
1505      * @param granted Grant/revoke access
1506      * @hide
1507      */
1508     @SystemApi
1509     @TestApi
setNotificationAssistantAccessGranted(@ullable ComponentName assistant, boolean granted)1510     public void setNotificationAssistantAccessGranted(@Nullable ComponentName assistant,
1511             boolean granted) {
1512         INotificationManager service = getService();
1513         try {
1514             service.setNotificationAssistantAccessGranted(assistant, granted);
1515         } catch (RemoteException e) {
1516             throw e.rethrowFromSystemServer();
1517         }
1518     }
1519 
1520     /** @hide */
getEnabledNotificationListeners(int userId)1521     public List<ComponentName> getEnabledNotificationListeners(int userId) {
1522         INotificationManager service = getService();
1523         try {
1524             return service.getEnabledNotificationListeners(userId);
1525         } catch (RemoteException e) {
1526             throw e.rethrowFromSystemServer();
1527         }
1528     }
1529 
1530     /** @hide */
1531     @SystemApi
1532     @TestApi
getAllowedNotificationAssistant()1533     public @Nullable ComponentName getAllowedNotificationAssistant() {
1534         INotificationManager service = getService();
1535         try {
1536             return service.getAllowedNotificationAssistant();
1537         } catch (RemoteException e) {
1538             throw e.rethrowFromSystemServer();
1539         }
1540     }
1541 
1542 
1543     private Context mContext;
1544 
checkRequired(String name, Object value)1545     private static void checkRequired(String name, Object value) {
1546         if (value == null) {
1547             throw new IllegalArgumentException(name + " is required");
1548         }
1549     }
1550 
1551     /**
1552      * Notification policy configuration.  Represents user-preferences for notification
1553      * filtering.
1554      */
1555     public static class Policy implements android.os.Parcelable {
1556         /** Reminder notifications are prioritized. */
1557         public static final int PRIORITY_CATEGORY_REMINDERS = 1 << 0;
1558         /** Event notifications are prioritized. */
1559         public static final int PRIORITY_CATEGORY_EVENTS = 1 << 1;
1560         /** Message notifications are prioritized. */
1561         public static final int PRIORITY_CATEGORY_MESSAGES = 1 << 2;
1562         /** Calls are prioritized. */
1563         public static final int PRIORITY_CATEGORY_CALLS = 1 << 3;
1564         /** Calls from repeat callers are prioritized. */
1565         public static final int PRIORITY_CATEGORY_REPEAT_CALLERS = 1 << 4;
1566         /** Alarms are prioritized */
1567         public static final int PRIORITY_CATEGORY_ALARMS = 1 << 5;
1568         /** Media, game, voice navigation are prioritized */
1569         public static final int PRIORITY_CATEGORY_MEDIA = 1 << 6;
1570         /**System (catch-all for non-never suppressible sounds) are prioritized */
1571         public static final int PRIORITY_CATEGORY_SYSTEM = 1 << 7;
1572         /**
1573          * Conversations are allowed through DND.
1574          */
1575         public static final int PRIORITY_CATEGORY_CONVERSATIONS = 1 << 8;
1576 
1577         /**
1578          * @hide
1579          */
1580         public static final int[] ALL_PRIORITY_CATEGORIES = {
1581                 PRIORITY_CATEGORY_ALARMS,
1582                 PRIORITY_CATEGORY_MEDIA,
1583                 PRIORITY_CATEGORY_SYSTEM,
1584                 PRIORITY_CATEGORY_REMINDERS,
1585                 PRIORITY_CATEGORY_EVENTS,
1586                 PRIORITY_CATEGORY_MESSAGES,
1587                 PRIORITY_CATEGORY_CALLS,
1588                 PRIORITY_CATEGORY_REPEAT_CALLERS,
1589                 PRIORITY_CATEGORY_CONVERSATIONS,
1590         };
1591 
1592         /** @hide */
1593         @IntDef(prefix = { "PRIORITY_SENDERS_" }, value = {
1594                 PRIORITY_SENDERS_ANY,
1595                 PRIORITY_SENDERS_CONTACTS,
1596                 PRIORITY_SENDERS_STARRED,
1597         })
1598         @Retention(RetentionPolicy.SOURCE)
1599         public @interface PrioritySenders {}
1600 
1601         /** Any sender is prioritized. */
1602         public static final int PRIORITY_SENDERS_ANY = 0;
1603         /** Saved contacts are prioritized. */
1604         public static final int PRIORITY_SENDERS_CONTACTS = 1;
1605         /** Only starred contacts are prioritized. */
1606         public static final int PRIORITY_SENDERS_STARRED = 2;
1607 
1608 
1609         /** @hide */
1610         @IntDef(prefix = { "CONVERSATION_SENDERS_" }, value = {
1611                 CONVERSATION_SENDERS_ANYONE,
1612                 CONVERSATION_SENDERS_IMPORTANT,
1613                 CONVERSATION_SENDERS_NONE,
1614         })
1615         @Retention(RetentionPolicy.SOURCE)
1616         public @interface ConversationSenders {}
1617         /**
1618          * Used to indicate all conversations can bypass dnd.
1619          */
1620         public static final int CONVERSATION_SENDERS_ANYONE = ZenPolicy.CONVERSATION_SENDERS_ANYONE;
1621 
1622         /**
1623          * Used to indicate important conversations can bypass dnd.
1624          */
1625         public static final int CONVERSATION_SENDERS_IMPORTANT =
1626                 ZenPolicy.CONVERSATION_SENDERS_IMPORTANT;
1627 
1628         /**
1629          * Used to indicate no conversations can bypass dnd.
1630          */
1631         public static final int CONVERSATION_SENDERS_NONE = ZenPolicy.CONVERSATION_SENDERS_NONE;
1632 
1633         /** Notification categories to prioritize. Bitmask of PRIORITY_CATEGORY_* constants. */
1634         public final int priorityCategories;
1635 
1636         /** Notification senders to prioritize for calls. One of:
1637          * PRIORITY_SENDERS_ANY, PRIORITY_SENDERS_CONTACTS, PRIORITY_SENDERS_STARRED */
1638         public final int priorityCallSenders;
1639 
1640         /** Notification senders to prioritize for messages. One of:
1641          * PRIORITY_SENDERS_ANY, PRIORITY_SENDERS_CONTACTS, PRIORITY_SENDERS_STARRED */
1642         public final int priorityMessageSenders;
1643 
1644         /**
1645          * Notification senders to prioritize for conversations. One of:
1646          * {@link #CONVERSATION_SENDERS_NONE}, {@link #CONVERSATION_SENDERS_IMPORTANT},
1647          * {@link #CONVERSATION_SENDERS_ANYONE}.
1648          */
1649         public final int priorityConversationSenders;
1650 
1651         /**
1652          * @hide
1653          */
1654         public static final int CONVERSATION_SENDERS_UNSET = -1;
1655 
1656         /**
1657          * @hide
1658          */
1659         public static final int SUPPRESSED_EFFECTS_UNSET = -1;
1660 
1661         /**
1662          * Whether notifications suppressed by DND should not interrupt visually (e.g. with
1663          * notification lights or by turning the screen on) when the screen is off.
1664          *
1665          * @deprecated use {@link #SUPPRESSED_EFFECT_FULL_SCREEN_INTENT} and
1666          * {@link #SUPPRESSED_EFFECT_AMBIENT} and {@link #SUPPRESSED_EFFECT_LIGHTS} individually.
1667          */
1668         @Deprecated
1669         public static final int SUPPRESSED_EFFECT_SCREEN_OFF = 1 << 0;
1670         /**
1671          * Whether notifications suppressed by DND should not interrupt visually when the screen
1672          * is on (e.g. by peeking onto the screen).
1673          *
1674          * @deprecated use {@link #SUPPRESSED_EFFECT_PEEK}.
1675          */
1676         @Deprecated
1677         public static final int SUPPRESSED_EFFECT_SCREEN_ON = 1 << 1;
1678 
1679         /**
1680          * Whether {@link Notification#fullScreenIntent full screen intents} from
1681          * notifications intercepted by DND are blocked.
1682          */
1683         public static final int SUPPRESSED_EFFECT_FULL_SCREEN_INTENT = 1 << 2;
1684 
1685         /**
1686          * Whether {@link NotificationChannel#shouldShowLights() notification lights} from
1687          * notifications intercepted by DND are blocked.
1688          */
1689         public static final int SUPPRESSED_EFFECT_LIGHTS = 1 << 3;
1690 
1691         /**
1692          * Whether notifications intercepted by DND are prevented from peeking.
1693          */
1694         public static final int SUPPRESSED_EFFECT_PEEK = 1 << 4;
1695 
1696         /**
1697          * Whether notifications intercepted by DND are prevented from appearing in the status bar,
1698          * on devices that support status bars.
1699          */
1700         public static final int SUPPRESSED_EFFECT_STATUS_BAR = 1 << 5;
1701 
1702         /**
1703          * Whether {@link NotificationChannel#canShowBadge() badges} from
1704          * notifications intercepted by DND are blocked on devices that support badging.
1705          */
1706         public static final int SUPPRESSED_EFFECT_BADGE = 1 << 6;
1707 
1708         /**
1709          * Whether notification intercepted by DND are prevented from appearing on ambient displays
1710          * on devices that support ambient display.
1711          */
1712         public static final int SUPPRESSED_EFFECT_AMBIENT = 1 << 7;
1713 
1714         /**
1715          * Whether notification intercepted by DND are prevented from appearing in notification
1716          * list views like the notification shade or lockscreen on devices that support those
1717          * views.
1718          */
1719         public static final int SUPPRESSED_EFFECT_NOTIFICATION_LIST = 1 << 8;
1720 
1721         private static final int[] ALL_SUPPRESSED_EFFECTS = {
1722                 SUPPRESSED_EFFECT_SCREEN_OFF,
1723                 SUPPRESSED_EFFECT_SCREEN_ON,
1724                 SUPPRESSED_EFFECT_FULL_SCREEN_INTENT,
1725                 SUPPRESSED_EFFECT_LIGHTS,
1726                 SUPPRESSED_EFFECT_PEEK,
1727                 SUPPRESSED_EFFECT_STATUS_BAR,
1728                 SUPPRESSED_EFFECT_BADGE,
1729                 SUPPRESSED_EFFECT_AMBIENT,
1730                 SUPPRESSED_EFFECT_NOTIFICATION_LIST
1731         };
1732 
1733         /**
1734          * Visual effects to suppress for a notification that is filtered by Do Not Disturb mode.
1735          * Bitmask of SUPPRESSED_EFFECT_* constants.
1736          */
1737         public final int suppressedVisualEffects;
1738 
1739         /**
1740          * @hide
1741          */
1742         public static final int STATE_CHANNELS_BYPASSING_DND = 1 << 0;
1743 
1744         /**
1745          * @hide
1746          */
1747         public static final int STATE_UNSET = -1;
1748 
1749         /**
1750          * Notification state information that is necessary to determine Do Not Disturb behavior.
1751          * Bitmask of STATE_* constants.
1752          * @hide
1753          */
1754         public final int state;
1755 
1756         /**
1757          * Constructs a policy for Do Not Disturb priority mode behavior.
1758          *
1759          * <p>
1760          *     Apps that target API levels below {@link Build.VERSION_CODES#P} cannot
1761          *     change user-designated values to allow or disallow
1762          *     {@link Policy#PRIORITY_CATEGORY_ALARMS}, {@link Policy#PRIORITY_CATEGORY_SYSTEM}, and
1763          *     {@link Policy#PRIORITY_CATEGORY_MEDIA} from bypassing dnd.
1764          *
1765          * @param priorityCategories bitmask of categories of notifications that can bypass DND.
1766          * @param priorityCallSenders which callers can bypass DND.
1767          * @param priorityMessageSenders which message senders can bypass DND.
1768          */
Policy(int priorityCategories, int priorityCallSenders, int priorityMessageSenders)1769         public Policy(int priorityCategories, int priorityCallSenders, int priorityMessageSenders) {
1770             this(priorityCategories, priorityCallSenders, priorityMessageSenders,
1771                     SUPPRESSED_EFFECTS_UNSET, STATE_UNSET, CONVERSATION_SENDERS_UNSET);
1772         }
1773 
1774         /**
1775          * Constructs a policy for Do Not Disturb priority mode behavior.
1776          *
1777          * <p>
1778          *     Apps that target API levels below {@link Build.VERSION_CODES#R} cannot
1779          *     change user-designated values to allow or disallow
1780          *     {@link Policy#PRIORITY_CATEGORY_CONVERSATIONS}, from bypassing dnd.
1781          * <p>
1782          *     Additionally, apps that target API levels below {@link Build.VERSION_CODES#P} can
1783          *     only modify the {@link #SUPPRESSED_EFFECT_SCREEN_ON} and
1784          *     {@link #SUPPRESSED_EFFECT_SCREEN_OFF} bits of the suppressed visual effects field.
1785          *     All other suppressed effects will be ignored and reconstituted from the screen on
1786          *     and screen off values.
1787          * <p>
1788          *     Apps that target {@link Build.VERSION_CODES#P} or above can set any
1789          *     suppressed visual effects. However, if any suppressed effects >
1790          *     {@link #SUPPRESSED_EFFECT_SCREEN_ON} are set, {@link #SUPPRESSED_EFFECT_SCREEN_ON}
1791          *     and {@link #SUPPRESSED_EFFECT_SCREEN_OFF} will be ignored and reconstituted from
1792          *     the more specific suppressed visual effect bits. Apps should migrate to targeting
1793          *     specific effects instead of the deprecated {@link #SUPPRESSED_EFFECT_SCREEN_ON} and
1794          *     {@link #SUPPRESSED_EFFECT_SCREEN_OFF} effects.
1795          *
1796          * @param priorityCategories bitmask of categories of notifications that can bypass DND.
1797          * @param priorityCallSenders which callers can bypass DND.
1798          * @param priorityMessageSenders which message senders can bypass DND.
1799          * @param suppressedVisualEffects which visual interruptions should be suppressed from
1800          *                                notifications that are filtered by DND.
1801          */
Policy(int priorityCategories, int priorityCallSenders, int priorityMessageSenders, int suppressedVisualEffects)1802         public Policy(int priorityCategories, int priorityCallSenders, int priorityMessageSenders,
1803                 int suppressedVisualEffects) {
1804             this(priorityCategories, priorityCallSenders, priorityMessageSenders,
1805                     suppressedVisualEffects, STATE_UNSET, CONVERSATION_SENDERS_UNSET);
1806         }
1807 
1808         /**
1809          * Constructs a policy for Do Not Disturb priority mode behavior.
1810          *
1811          * <p>
1812          *     Apps that target API levels below {@link Build.VERSION_CODES#P} cannot
1813          *     change user-designated values to allow or disallow
1814          *     {@link Policy#PRIORITY_CATEGORY_CONVERSATIONS} from bypassing dnd. If you do need
1815          *     to change them, use a {@link ZenPolicy} associated with an {@link AutomaticZenRule}
1816          *     instead of changing the global setting.
1817          * <p>
1818          *     Apps that target API levels below {@link Build.VERSION_CODES#P} cannot
1819          *     change user-designated values to allow or disallow
1820          *     {@link Policy#PRIORITY_CATEGORY_ALARMS},
1821          *     {@link Policy#PRIORITY_CATEGORY_SYSTEM}, and
1822          *     {@link Policy#PRIORITY_CATEGORY_MEDIA} from bypassing dnd.
1823          * <p>
1824          *     Additionally, apps that target API levels below {@link Build.VERSION_CODES#P} can
1825          *     only modify the {@link #SUPPRESSED_EFFECT_SCREEN_ON} and
1826          *     {@link #SUPPRESSED_EFFECT_SCREEN_OFF} bits of the suppressed visual effects field.
1827          *     All other suppressed effects will be ignored and reconstituted from the screen on
1828          *     and screen off values.
1829          * <p>
1830          *     Apps that target {@link Build.VERSION_CODES#P} or above can set any
1831          *     suppressed visual effects. However, if any suppressed effects >
1832          *     {@link #SUPPRESSED_EFFECT_SCREEN_ON} are set, {@link #SUPPRESSED_EFFECT_SCREEN_ON}
1833          *     and {@link #SUPPRESSED_EFFECT_SCREEN_OFF} will be ignored and reconstituted from
1834          *     the more specific suppressed visual effect bits. Apps should migrate to targeting
1835          *     specific effects instead of the deprecated {@link #SUPPRESSED_EFFECT_SCREEN_ON} and
1836          *     {@link #SUPPRESSED_EFFECT_SCREEN_OFF} effects.
1837          *
1838          * @param priorityCategories bitmask of categories of notifications that can bypass DND.
1839          * @param priorityCallSenders which callers can bypass DND.
1840          * @param priorityMessageSenders which message senders can bypass DND.
1841          * @param suppressedVisualEffects which visual interruptions should be suppressed from
1842          *                                notifications that are filtered by DND.
1843          */
Policy(int priorityCategories, @PrioritySenders int priorityCallSenders, @PrioritySenders int priorityMessageSenders, int suppressedVisualEffects, @ConversationSenders int priorityConversationSenders)1844         public Policy(int priorityCategories, @PrioritySenders int priorityCallSenders,
1845                 @PrioritySenders int priorityMessageSenders,
1846                 int suppressedVisualEffects, @ConversationSenders int priorityConversationSenders) {
1847             this(priorityCategories, priorityCallSenders, priorityMessageSenders,
1848                     suppressedVisualEffects, STATE_UNSET, priorityConversationSenders);
1849         }
1850 
1851         /** @hide */
Policy(int priorityCategories, int priorityCallSenders, int priorityMessageSenders, int suppressedVisualEffects, int state, int priorityConversationSenders)1852         public Policy(int priorityCategories, int priorityCallSenders, int priorityMessageSenders,
1853                 int suppressedVisualEffects, int state, int priorityConversationSenders) {
1854             this.priorityCategories = priorityCategories;
1855             this.priorityCallSenders = priorityCallSenders;
1856             this.priorityMessageSenders = priorityMessageSenders;
1857             this.suppressedVisualEffects = suppressedVisualEffects;
1858             this.state = state;
1859             this.priorityConversationSenders = priorityConversationSenders;
1860         }
1861 
1862 
1863         /** @hide */
Policy(Parcel source)1864         public Policy(Parcel source) {
1865             this(source.readInt(), source.readInt(), source.readInt(), source.readInt(),
1866                     source.readInt(), source.readInt());
1867         }
1868 
1869         @Override
writeToParcel(Parcel dest, int flags)1870         public void writeToParcel(Parcel dest, int flags) {
1871             dest.writeInt(priorityCategories);
1872             dest.writeInt(priorityCallSenders);
1873             dest.writeInt(priorityMessageSenders);
1874             dest.writeInt(suppressedVisualEffects);
1875             dest.writeInt(state);
1876             dest.writeInt(priorityConversationSenders);
1877         }
1878 
1879         @Override
describeContents()1880         public int describeContents() {
1881             return 0;
1882         }
1883 
1884         @Override
hashCode()1885         public int hashCode() {
1886             return Objects.hash(priorityCategories, priorityCallSenders, priorityMessageSenders,
1887                     suppressedVisualEffects, state, priorityConversationSenders);
1888         }
1889 
1890         @Override
equals(Object o)1891         public boolean equals(Object o) {
1892             if (!(o instanceof Policy)) return false;
1893             if (o == this) return true;
1894             final Policy other = (Policy) o;
1895             return other.priorityCategories == priorityCategories
1896                     && other.priorityCallSenders == priorityCallSenders
1897                     && other.priorityMessageSenders == priorityMessageSenders
1898                     && suppressedVisualEffectsEqual(suppressedVisualEffects,
1899                     other.suppressedVisualEffects)
1900                     && other.state == this.state
1901                     && other.priorityConversationSenders == this.priorityConversationSenders;
1902         }
1903 
suppressedVisualEffectsEqual(int suppressedEffects, int otherSuppressedVisualEffects)1904         private boolean suppressedVisualEffectsEqual(int suppressedEffects,
1905                 int otherSuppressedVisualEffects) {
1906             if (suppressedEffects == otherSuppressedVisualEffects) {
1907                 return true;
1908             }
1909 
1910             if ((suppressedEffects & SUPPRESSED_EFFECT_SCREEN_ON) != 0) {
1911                 suppressedEffects |= SUPPRESSED_EFFECT_PEEK;
1912             }
1913             if ((suppressedEffects & SUPPRESSED_EFFECT_SCREEN_OFF) != 0) {
1914                 suppressedEffects |= SUPPRESSED_EFFECT_FULL_SCREEN_INTENT;
1915                 suppressedEffects |= SUPPRESSED_EFFECT_LIGHTS;
1916                 suppressedEffects |= SUPPRESSED_EFFECT_AMBIENT;
1917             }
1918 
1919             if ((otherSuppressedVisualEffects & SUPPRESSED_EFFECT_SCREEN_ON) != 0) {
1920                 otherSuppressedVisualEffects |= SUPPRESSED_EFFECT_PEEK;
1921             }
1922             if ((otherSuppressedVisualEffects & SUPPRESSED_EFFECT_SCREEN_OFF) != 0) {
1923                 otherSuppressedVisualEffects |= SUPPRESSED_EFFECT_FULL_SCREEN_INTENT;
1924                 otherSuppressedVisualEffects |= SUPPRESSED_EFFECT_LIGHTS;
1925                 otherSuppressedVisualEffects |= SUPPRESSED_EFFECT_AMBIENT;
1926             }
1927 
1928             if ((suppressedEffects & SUPPRESSED_EFFECT_SCREEN_ON)
1929                     != (otherSuppressedVisualEffects & SUPPRESSED_EFFECT_SCREEN_ON)) {
1930                 int currSuppressedEffects = (suppressedEffects & SUPPRESSED_EFFECT_SCREEN_ON) != 0
1931                         ? otherSuppressedVisualEffects : suppressedEffects;
1932                 if ((currSuppressedEffects & SUPPRESSED_EFFECT_PEEK) == 0) {
1933                     return false;
1934                 }
1935             }
1936 
1937             if ((suppressedEffects & SUPPRESSED_EFFECT_SCREEN_OFF)
1938                     != (otherSuppressedVisualEffects & SUPPRESSED_EFFECT_SCREEN_OFF)) {
1939                 int currSuppressedEffects = (suppressedEffects & SUPPRESSED_EFFECT_SCREEN_OFF) != 0
1940                         ? otherSuppressedVisualEffects : suppressedEffects;
1941                 if ((currSuppressedEffects & SUPPRESSED_EFFECT_FULL_SCREEN_INTENT) == 0
1942                         || (currSuppressedEffects & SUPPRESSED_EFFECT_LIGHTS) == 0
1943                         || (currSuppressedEffects & SUPPRESSED_EFFECT_AMBIENT) == 0) {
1944                     return false;
1945                 }
1946             }
1947 
1948             int thisWithoutOldEffects = suppressedEffects
1949                     & ~SUPPRESSED_EFFECT_SCREEN_ON
1950                     & ~SUPPRESSED_EFFECT_SCREEN_OFF;
1951             int otherWithoutOldEffects = otherSuppressedVisualEffects
1952                     & ~SUPPRESSED_EFFECT_SCREEN_ON
1953                     & ~SUPPRESSED_EFFECT_SCREEN_OFF;
1954             return thisWithoutOldEffects == otherWithoutOldEffects;
1955         }
1956 
1957         @Override
toString()1958         public String toString() {
1959             return "NotificationManager.Policy["
1960                     + "priorityCategories=" + priorityCategoriesToString(priorityCategories)
1961                     + ",priorityCallSenders=" + prioritySendersToString(priorityCallSenders)
1962                     + ",priorityMessageSenders=" + prioritySendersToString(priorityMessageSenders)
1963                     + ",priorityConvSenders="
1964                     + conversationSendersToString(priorityConversationSenders)
1965                     + ",suppressedVisualEffects="
1966                     + suppressedEffectsToString(suppressedVisualEffects)
1967                     + ",areChannelsBypassingDnd=" + (((state & STATE_CHANNELS_BYPASSING_DND) != 0)
1968                         ? "true" : "false")
1969                     + "]";
1970         }
1971 
1972         /** @hide */
dumpDebug(ProtoOutputStream proto, long fieldId)1973         public void dumpDebug(ProtoOutputStream proto, long fieldId) {
1974             final long pToken = proto.start(fieldId);
1975 
1976             bitwiseToProtoEnum(proto, PolicyProto.PRIORITY_CATEGORIES, priorityCategories);
1977             proto.write(PolicyProto.PRIORITY_CALL_SENDER, priorityCallSenders);
1978             proto.write(PolicyProto.PRIORITY_MESSAGE_SENDER, priorityMessageSenders);
1979             bitwiseToProtoEnum(
1980                     proto, PolicyProto.SUPPRESSED_VISUAL_EFFECTS, suppressedVisualEffects);
1981 
1982             proto.end(pToken);
1983         }
1984 
bitwiseToProtoEnum(ProtoOutputStream proto, long fieldId, int data)1985         private static void bitwiseToProtoEnum(ProtoOutputStream proto, long fieldId, int data) {
1986             for (int i = 1; data > 0; ++i, data >>>= 1) {
1987                 if ((data & 1) == 1) {
1988                     proto.write(fieldId, i);
1989                 }
1990             }
1991         }
1992 
1993         /**
1994          * @hide
1995          */
getAllSuppressedVisualEffects()1996         public static int getAllSuppressedVisualEffects() {
1997             int effects = 0;
1998             for (int i = 0; i < ALL_SUPPRESSED_EFFECTS.length; i++) {
1999                 effects |= ALL_SUPPRESSED_EFFECTS[i];
2000             }
2001             return effects;
2002         }
2003 
2004         /**
2005          * @hide
2006          */
areAllVisualEffectsSuppressed(int effects)2007         public static boolean areAllVisualEffectsSuppressed(int effects) {
2008             for (int i = 0; i < ALL_SUPPRESSED_EFFECTS.length; i++) {
2009                 final int effect = ALL_SUPPRESSED_EFFECTS[i];
2010                 if ((effects & effect) == 0) {
2011                     return false;
2012                 }
2013             }
2014             return true;
2015         }
2016 
toggleEffects(int currentEffects, int[] effects, boolean suppress)2017         private static int toggleEffects(int currentEffects, int[] effects, boolean suppress) {
2018             for (int i = 0; i < effects.length; i++) {
2019                 final int effect = effects[i];
2020                 if (suppress) {
2021                     currentEffects |= effect;
2022                 } else {
2023                     currentEffects &= ~effect;
2024                 }
2025             }
2026             return currentEffects;
2027         }
2028 
suppressedEffectsToString(int effects)2029         public static String suppressedEffectsToString(int effects) {
2030             if (effects <= 0) return "";
2031             final StringBuilder sb = new StringBuilder();
2032             for (int i = 0; i < ALL_SUPPRESSED_EFFECTS.length; i++) {
2033                 final int effect = ALL_SUPPRESSED_EFFECTS[i];
2034                 if ((effects & effect) != 0) {
2035                     if (sb.length() > 0) sb.append(',');
2036                     sb.append(effectToString(effect));
2037                 }
2038                 effects &= ~effect;
2039             }
2040             if (effects != 0) {
2041                 if (sb.length() > 0) sb.append(',');
2042                 sb.append("UNKNOWN_").append(effects);
2043             }
2044             return sb.toString();
2045         }
2046 
priorityCategoriesToString(int priorityCategories)2047         public static String priorityCategoriesToString(int priorityCategories) {
2048             if (priorityCategories == 0) return "";
2049             final StringBuilder sb = new StringBuilder();
2050             for (int i = 0; i < ALL_PRIORITY_CATEGORIES.length; i++) {
2051                 final int priorityCategory = ALL_PRIORITY_CATEGORIES[i];
2052                 if ((priorityCategories & priorityCategory) != 0) {
2053                     if (sb.length() > 0) sb.append(',');
2054                     sb.append(priorityCategoryToString(priorityCategory));
2055                 }
2056                 priorityCategories &= ~priorityCategory;
2057             }
2058             if (priorityCategories != 0) {
2059                 if (sb.length() > 0) sb.append(',');
2060                 sb.append("PRIORITY_CATEGORY_UNKNOWN_").append(priorityCategories);
2061             }
2062             return sb.toString();
2063         }
2064 
effectToString(int effect)2065         private static String effectToString(int effect) {
2066             switch (effect) {
2067                 case SUPPRESSED_EFFECT_FULL_SCREEN_INTENT:
2068                     return "SUPPRESSED_EFFECT_FULL_SCREEN_INTENT";
2069                 case SUPPRESSED_EFFECT_LIGHTS:
2070                     return "SUPPRESSED_EFFECT_LIGHTS";
2071                 case SUPPRESSED_EFFECT_PEEK:
2072                     return "SUPPRESSED_EFFECT_PEEK";
2073                 case SUPPRESSED_EFFECT_STATUS_BAR:
2074                     return "SUPPRESSED_EFFECT_STATUS_BAR";
2075                 case SUPPRESSED_EFFECT_BADGE:
2076                     return "SUPPRESSED_EFFECT_BADGE";
2077                 case SUPPRESSED_EFFECT_AMBIENT:
2078                     return "SUPPRESSED_EFFECT_AMBIENT";
2079                 case SUPPRESSED_EFFECT_NOTIFICATION_LIST:
2080                     return "SUPPRESSED_EFFECT_NOTIFICATION_LIST";
2081                 case SUPPRESSED_EFFECT_SCREEN_OFF:
2082                     return "SUPPRESSED_EFFECT_SCREEN_OFF";
2083                 case SUPPRESSED_EFFECT_SCREEN_ON:
2084                     return "SUPPRESSED_EFFECT_SCREEN_ON";
2085                 case SUPPRESSED_EFFECTS_UNSET:
2086                     return "SUPPRESSED_EFFECTS_UNSET";
2087                 default: return "UNKNOWN_" + effect;
2088             }
2089         }
2090 
priorityCategoryToString(int priorityCategory)2091         private static String priorityCategoryToString(int priorityCategory) {
2092             switch (priorityCategory) {
2093                 case PRIORITY_CATEGORY_REMINDERS: return "PRIORITY_CATEGORY_REMINDERS";
2094                 case PRIORITY_CATEGORY_EVENTS: return "PRIORITY_CATEGORY_EVENTS";
2095                 case PRIORITY_CATEGORY_MESSAGES: return "PRIORITY_CATEGORY_MESSAGES";
2096                 case PRIORITY_CATEGORY_CALLS: return "PRIORITY_CATEGORY_CALLS";
2097                 case PRIORITY_CATEGORY_REPEAT_CALLERS: return "PRIORITY_CATEGORY_REPEAT_CALLERS";
2098                 case PRIORITY_CATEGORY_ALARMS: return "PRIORITY_CATEGORY_ALARMS";
2099                 case PRIORITY_CATEGORY_MEDIA: return "PRIORITY_CATEGORY_MEDIA";
2100                 case PRIORITY_CATEGORY_SYSTEM: return "PRIORITY_CATEGORY_SYSTEM";
2101                 case PRIORITY_CATEGORY_CONVERSATIONS: return "PRIORITY_CATEGORY_CONVERSATIONS";
2102                 default: return "PRIORITY_CATEGORY_UNKNOWN_" + priorityCategory;
2103             }
2104         }
2105 
prioritySendersToString(int prioritySenders)2106         public static String prioritySendersToString(int prioritySenders) {
2107             switch (prioritySenders) {
2108                 case PRIORITY_SENDERS_ANY: return "PRIORITY_SENDERS_ANY";
2109                 case PRIORITY_SENDERS_CONTACTS: return "PRIORITY_SENDERS_CONTACTS";
2110                 case PRIORITY_SENDERS_STARRED: return "PRIORITY_SENDERS_STARRED";
2111                 default: return "PRIORITY_SENDERS_UNKNOWN_" + prioritySenders;
2112             }
2113         }
2114 
2115         /**
2116          * @hide
2117          */
conversationSendersToString(int priorityConversationSenders)2118         public static @NonNull String conversationSendersToString(int priorityConversationSenders) {
2119             switch (priorityConversationSenders) {
2120                 case CONVERSATION_SENDERS_ANYONE:
2121                     return "anyone";
2122                 case CONVERSATION_SENDERS_IMPORTANT:
2123                     return "important";
2124                 case CONVERSATION_SENDERS_NONE:
2125                     return "none";
2126                 case CONVERSATION_SENDERS_UNSET:
2127                     return "unset";
2128             }
2129             return "invalidConversationType{" + priorityConversationSenders + "}";
2130         }
2131 
2132         public static final @android.annotation.NonNull Parcelable.Creator<Policy> CREATOR
2133                 = new Parcelable.Creator<Policy>() {
2134             @Override
2135             public Policy createFromParcel(Parcel in) {
2136                 return new Policy(in);
2137             }
2138 
2139             @Override
2140             public Policy[] newArray(int size) {
2141                 return new Policy[size];
2142             }
2143         };
2144 
2145         /** @hide **/
allowAlarms()2146         public boolean allowAlarms() {
2147             return (priorityCategories & PRIORITY_CATEGORY_ALARMS) != 0;
2148         }
2149 
2150         /** @hide **/
allowMedia()2151         public boolean allowMedia() {
2152             return (priorityCategories & PRIORITY_CATEGORY_MEDIA) != 0;
2153         }
2154 
2155         /** @hide **/
allowSystem()2156         public boolean allowSystem() {
2157             return (priorityCategories & PRIORITY_CATEGORY_SYSTEM) != 0;
2158         }
2159 
2160         /** @hide **/
allowRepeatCallers()2161         public boolean allowRepeatCallers() {
2162             return (priorityCategories & PRIORITY_CATEGORY_REPEAT_CALLERS) != 0;
2163         }
2164 
2165         /** @hide **/
allowCalls()2166         public boolean allowCalls() {
2167             return (priorityCategories & PRIORITY_CATEGORY_CALLS) != 0;
2168         }
2169 
2170         /** @hide **/
allowConversations()2171         public boolean allowConversations() {
2172             return (priorityCategories & PRIORITY_CATEGORY_CONVERSATIONS) != 0;
2173         }
2174 
2175         /** @hide **/
allowMessages()2176         public boolean allowMessages() {
2177             return (priorityCategories & PRIORITY_CATEGORY_MESSAGES) != 0;
2178         }
2179 
2180         /** @hide **/
allowEvents()2181         public boolean allowEvents() {
2182             return (priorityCategories & PRIORITY_CATEGORY_EVENTS) != 0;
2183         }
2184 
2185         /** @hide **/
allowReminders()2186         public boolean allowReminders() {
2187             return (priorityCategories & PRIORITY_CATEGORY_REMINDERS) != 0;
2188         }
2189 
2190         /** @hide **/
allowCallsFrom()2191         public int allowCallsFrom() {
2192             return priorityCallSenders;
2193         }
2194 
2195         /** @hide **/
allowMessagesFrom()2196         public int allowMessagesFrom() {
2197             return priorityMessageSenders;
2198         }
2199 
2200         /** @hide **/
allowConversationsFrom()2201         public int allowConversationsFrom() {
2202             return priorityConversationSenders;
2203         }
2204 
2205         /** @hide **/
showFullScreenIntents()2206         public boolean showFullScreenIntents() {
2207             return (suppressedVisualEffects & SUPPRESSED_EFFECT_FULL_SCREEN_INTENT) == 0;
2208         }
2209 
2210         /** @hide **/
showLights()2211         public boolean showLights() {
2212             return (suppressedVisualEffects & SUPPRESSED_EFFECT_LIGHTS) == 0;
2213         }
2214 
2215         /** @hide **/
showPeeking()2216         public boolean showPeeking() {
2217             return (suppressedVisualEffects & SUPPRESSED_EFFECT_PEEK) == 0;
2218         }
2219 
2220         /** @hide **/
showStatusBarIcons()2221         public boolean showStatusBarIcons() {
2222             return (suppressedVisualEffects & SUPPRESSED_EFFECT_STATUS_BAR) == 0;
2223         }
2224 
2225         /** @hide **/
showAmbient()2226         public boolean showAmbient() {
2227             return (suppressedVisualEffects & SUPPRESSED_EFFECT_AMBIENT) == 0;
2228         }
2229 
2230         /** @hide **/
showBadges()2231         public boolean showBadges() {
2232             return (suppressedVisualEffects & SUPPRESSED_EFFECT_BADGE) == 0;
2233         }
2234 
2235         /** @hide **/
showInNotificationList()2236         public boolean showInNotificationList() {
2237             return (suppressedVisualEffects & SUPPRESSED_EFFECT_NOTIFICATION_LIST) == 0;
2238         }
2239 
2240         /**
2241          * returns a deep copy of this policy
2242          * @hide
2243          */
copy()2244         public Policy copy() {
2245             final Parcel parcel = Parcel.obtain();
2246             try {
2247                 writeToParcel(parcel, 0);
2248                 parcel.setDataPosition(0);
2249                 return new Policy(parcel);
2250             } finally {
2251                 parcel.recycle();
2252             }
2253         }
2254     }
2255 
2256     /**
2257      * Recover a list of active notifications: ones that have been posted by the calling app that
2258      * have not yet been dismissed by the user or {@link #cancel(String, int)}ed by the app.
2259      *
2260      * <p><Each notification is embedded in a {@link StatusBarNotification} object, including the
2261      * original <code>tag</code> and <code>id</code> supplied to
2262      * {@link #notify(String, int, Notification) notify()}
2263      * (via {@link StatusBarNotification#getTag() getTag()} and
2264      * {@link StatusBarNotification#getId() getId()}) as well as a copy of the original
2265      * {@link Notification} object (via {@link StatusBarNotification#getNotification()}).
2266      * </p>
2267      * <p>From {@link Build.VERSION_CODES#Q}, will also return notifications you've posted as an
2268      * app's notification delegate via
2269      * {@link NotificationManager#notifyAsPackage(String, String, int, Notification)}.
2270      * </p>
2271      *
2272      * @return An array of {@link StatusBarNotification}.
2273      */
getActiveNotifications()2274     public StatusBarNotification[] getActiveNotifications() {
2275         final INotificationManager service = getService();
2276         final String pkg = mContext.getPackageName();
2277         try {
2278             final ParceledListSlice<StatusBarNotification> parceledList
2279                     = service.getAppActiveNotifications(pkg, mContext.getUserId());
2280             if (parceledList != null) {
2281                 final List<StatusBarNotification> list = parceledList.getList();
2282                 return list.toArray(new StatusBarNotification[list.size()]);
2283             }
2284         } catch (RemoteException e) {
2285             throw e.rethrowFromSystemServer();
2286         }
2287         return new StatusBarNotification[0];
2288     }
2289 
2290     /**
2291      * Gets the current notification interruption filter.
2292      * <p>
2293      * The interruption filter defines which notifications are allowed to
2294      * interrupt the user (e.g. via sound &amp; vibration) and is applied
2295      * globally.
2296      */
getCurrentInterruptionFilter()2297     public final @InterruptionFilter int getCurrentInterruptionFilter() {
2298         final INotificationManager service = getService();
2299         try {
2300             return zenModeToInterruptionFilter(service.getZenMode());
2301         } catch (RemoteException e) {
2302             throw e.rethrowFromSystemServer();
2303         }
2304     }
2305 
2306     /**
2307      * Sets the current notification interruption filter.
2308      * <p>
2309      * The interruption filter defines which notifications are allowed to
2310      * interrupt the user (e.g. via sound &amp; vibration) and is applied
2311      * globally.
2312      * <p>
2313      * Only available if policy access is granted to this package. See
2314      * {@link #isNotificationPolicyAccessGranted}.
2315      */
setInterruptionFilter(@nterruptionFilter int interruptionFilter)2316     public final void setInterruptionFilter(@InterruptionFilter int interruptionFilter) {
2317         final INotificationManager service = getService();
2318         try {
2319             service.setInterruptionFilter(mContext.getOpPackageName(), interruptionFilter);
2320         } catch (RemoteException e) {
2321             throw e.rethrowFromSystemServer();
2322         }
2323     }
2324 
2325     /** @hide */
zenModeToInterruptionFilter(int zen)2326     public static int zenModeToInterruptionFilter(int zen) {
2327         switch (zen) {
2328             case Global.ZEN_MODE_OFF: return INTERRUPTION_FILTER_ALL;
2329             case Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS: return INTERRUPTION_FILTER_PRIORITY;
2330             case Global.ZEN_MODE_ALARMS: return INTERRUPTION_FILTER_ALARMS;
2331             case Global.ZEN_MODE_NO_INTERRUPTIONS: return INTERRUPTION_FILTER_NONE;
2332             default: return INTERRUPTION_FILTER_UNKNOWN;
2333         }
2334     }
2335 
2336     /** @hide */
zenModeFromInterruptionFilter(int interruptionFilter, int defValue)2337     public static int zenModeFromInterruptionFilter(int interruptionFilter, int defValue) {
2338         switch (interruptionFilter) {
2339             case INTERRUPTION_FILTER_ALL: return Global.ZEN_MODE_OFF;
2340             case INTERRUPTION_FILTER_PRIORITY: return Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS;
2341             case INTERRUPTION_FILTER_ALARMS: return Global.ZEN_MODE_ALARMS;
2342             case INTERRUPTION_FILTER_NONE:  return Global.ZEN_MODE_NO_INTERRUPTIONS;
2343             default: return defValue;
2344         }
2345     }
2346 }
2347