Debian Codegraph @

core/java/android/app/NotificationManager.java

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