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