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