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