NotificationListenerService.java revision 9acd673c0deb2652a55c52b9b80515d84b1945dc
1/* 2 * Copyright (C) 2013 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 17package android.service.notification; 18 19import android.annotation.IntDef; 20import android.annotation.NonNull; 21import android.annotation.SdkConstant; 22import android.annotation.SystemApi; 23import android.annotation.TestApi; 24import android.app.ActivityManager; 25import android.app.INotificationManager; 26import android.app.Notification; 27import android.app.Notification.Builder; 28import android.app.NotificationChannel; 29import android.app.NotificationChannelGroup; 30import android.app.NotificationManager; 31import android.app.Person; 32import android.app.Service; 33import android.companion.CompanionDeviceManager; 34import android.content.ComponentName; 35import android.content.Context; 36import android.content.Intent; 37import android.content.pm.ParceledListSlice; 38import android.graphics.Bitmap; 39import android.graphics.drawable.BitmapDrawable; 40import android.graphics.drawable.Drawable; 41import android.graphics.drawable.Icon; 42import android.os.Build; 43import android.os.Bundle; 44import android.os.Handler; 45import android.os.IBinder; 46import android.os.Looper; 47import android.os.Message; 48import android.os.Parcel; 49import android.os.Parcelable; 50import android.os.RemoteException; 51import android.os.ServiceManager; 52import android.os.UserHandle; 53import android.util.ArrayMap; 54import android.util.ArraySet; 55import android.util.Log; 56import android.widget.RemoteViews; 57 58import com.android.internal.annotations.GuardedBy; 59import com.android.internal.annotations.VisibleForTesting; 60import com.android.internal.os.SomeArgs; 61 62import java.lang.annotation.Retention; 63import java.lang.annotation.RetentionPolicy; 64import java.util.ArrayList; 65import java.util.Collections; 66import java.util.List; 67 68/** 69 * A service that receives calls from the system when new notifications are 70 * posted or removed, or their ranking changed. 71 * <p>To extend this class, you must declare the service in your manifest file with 72 * the {@link android.Manifest.permission#BIND_NOTIFICATION_LISTENER_SERVICE} permission 73 * and include an intent filter with the {@link #SERVICE_INTERFACE} action. For example:</p> 74 * <pre> 75 * <service android:name=".NotificationListener" 76 * android:label="@string/service_name" 77 * android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"> 78 * <intent-filter> 79 * <action android:name="android.service.notification.NotificationListenerService" /> 80 * </intent-filter> 81 * </service></pre> 82 * 83 * <p>The service should wait for the {@link #onListenerConnected()} event 84 * before performing any operations. The {@link #requestRebind(ComponentName)} 85 * method is the <i>only</i> one that is safe to call before {@link #onListenerConnected()} 86 * or after {@link #onListenerDisconnected()}. 87 * </p> 88 * <p> Notification listeners cannot get notification access or be bound by the system on 89 * {@linkplain ActivityManager#isLowRamDevice() low-RAM} devices. The system also ignores 90 * notification listeners running in a work profile. A 91 * {@link android.app.admin.DevicePolicyManager} might block notifications originating from a work 92 * profile.</p> 93 */ 94public abstract class NotificationListenerService extends Service { 95 96 private final String TAG = getClass().getSimpleName(); 97 98 /** 99 * {@link #getCurrentInterruptionFilter() Interruption filter} constant - 100 * Normal interruption filter. 101 */ 102 public static final int INTERRUPTION_FILTER_ALL 103 = NotificationManager.INTERRUPTION_FILTER_ALL; 104 105 /** 106 * {@link #getCurrentInterruptionFilter() Interruption filter} constant - 107 * Priority interruption filter. 108 */ 109 public static final int INTERRUPTION_FILTER_PRIORITY 110 = NotificationManager.INTERRUPTION_FILTER_PRIORITY; 111 112 /** 113 * {@link #getCurrentInterruptionFilter() Interruption filter} constant - 114 * No interruptions filter. 115 */ 116 public static final int INTERRUPTION_FILTER_NONE 117 = NotificationManager.INTERRUPTION_FILTER_NONE; 118 119 /** 120 * {@link #getCurrentInterruptionFilter() Interruption filter} constant - 121 * Alarms only interruption filter. 122 */ 123 public static final int INTERRUPTION_FILTER_ALARMS 124 = NotificationManager.INTERRUPTION_FILTER_ALARMS; 125 126 /** {@link #getCurrentInterruptionFilter() Interruption filter} constant - returned when 127 * the value is unavailable for any reason. For example, before the notification listener 128 * is connected. 129 * 130 * {@see #onListenerConnected()} 131 */ 132 public static final int INTERRUPTION_FILTER_UNKNOWN 133 = NotificationManager.INTERRUPTION_FILTER_UNKNOWN; 134 135 /** {@link #getCurrentListenerHints() Listener hints} constant - the primary device UI 136 * should disable notification sound, vibrating and other visual or aural effects. 137 * This does not change the interruption filter, only the effects. **/ 138 public static final int HINT_HOST_DISABLE_EFFECTS = 1; 139 140 /** {@link #getCurrentListenerHints() Listener hints} constant - the primary device UI 141 * should disable notification sound, but not phone calls. 142 * This does not change the interruption filter, only the effects. **/ 143 public static final int HINT_HOST_DISABLE_NOTIFICATION_EFFECTS = 1 << 1; 144 145 /** {@link #getCurrentListenerHints() Listener hints} constant - the primary device UI 146 * should disable phone call sounds, buyt not notification sound. 147 * This does not change the interruption filter, only the effects. **/ 148 public static final int HINT_HOST_DISABLE_CALL_EFFECTS = 1 << 2; 149 150 /** 151 * Whether notification suppressed by DND should not interruption visually when the screen is 152 * off. 153 * 154 * @deprecated Use the more specific visual effects in {@link NotificationManager.Policy}. 155 */ 156 @Deprecated 157 public static final int SUPPRESSED_EFFECT_SCREEN_OFF = 158 NotificationManager.Policy.SUPPRESSED_EFFECT_SCREEN_OFF; 159 /** 160 * Whether notification suppressed by DND should not interruption visually when the screen is 161 * on. 162 * 163 * @deprecated Use the more specific visual effects in {@link NotificationManager.Policy}. 164 */ 165 @Deprecated 166 public static final int SUPPRESSED_EFFECT_SCREEN_ON = 167 NotificationManager.Policy.SUPPRESSED_EFFECT_SCREEN_ON; 168 169 170 // Notification cancellation reasons 171 172 /** Notification was canceled by the status bar reporting a notification click. */ 173 public static final int REASON_CLICK = 1; 174 /** Notification was canceled by the status bar reporting a user dismissal. */ 175 public static final int REASON_CANCEL = 2; 176 /** Notification was canceled by the status bar reporting a user dismiss all. */ 177 public static final int REASON_CANCEL_ALL = 3; 178 /** Notification was canceled by the status bar reporting an inflation error. */ 179 public static final int REASON_ERROR = 4; 180 /** Notification was canceled by the package manager modifying the package. */ 181 public static final int REASON_PACKAGE_CHANGED = 5; 182 /** Notification was canceled by the owning user context being stopped. */ 183 public static final int REASON_USER_STOPPED = 6; 184 /** Notification was canceled by the user banning the package. */ 185 public static final int REASON_PACKAGE_BANNED = 7; 186 /** Notification was canceled by the app canceling this specific notification. */ 187 public static final int REASON_APP_CANCEL = 8; 188 /** Notification was canceled by the app cancelling all its notifications. */ 189 public static final int REASON_APP_CANCEL_ALL = 9; 190 /** Notification was canceled by a listener reporting a user dismissal. */ 191 public static final int REASON_LISTENER_CANCEL = 10; 192 /** Notification was canceled by a listener reporting a user dismiss all. */ 193 public static final int REASON_LISTENER_CANCEL_ALL = 11; 194 /** Notification was canceled because it was a member of a canceled group. */ 195 public static final int REASON_GROUP_SUMMARY_CANCELED = 12; 196 /** Notification was canceled because it was an invisible member of a group. */ 197 public static final int REASON_GROUP_OPTIMIZATION = 13; 198 /** Notification was canceled by the device administrator suspending the package. */ 199 public static final int REASON_PACKAGE_SUSPENDED = 14; 200 /** Notification was canceled by the owning managed profile being turned off. */ 201 public static final int REASON_PROFILE_TURNED_OFF = 15; 202 /** Autobundled summary notification was canceled because its group was unbundled */ 203 public static final int REASON_UNAUTOBUNDLED = 16; 204 /** Notification was canceled by the user banning the channel. */ 205 public static final int REASON_CHANNEL_BANNED = 17; 206 /** Notification was snoozed. */ 207 public static final int REASON_SNOOZED = 18; 208 /** Notification was canceled due to timeout */ 209 public static final int REASON_TIMEOUT = 19; 210 211 /** 212 * The full trim of the StatusBarNotification including all its features. 213 * 214 * @hide 215 * @removed 216 */ 217 @SystemApi 218 public static final int TRIM_FULL = 0; 219 220 /** 221 * A light trim of the StatusBarNotification excluding the following features: 222 * 223 * <ol> 224 * <li>{@link Notification#tickerView tickerView}</li> 225 * <li>{@link Notification#contentView contentView}</li> 226 * <li>{@link Notification#largeIcon largeIcon}</li> 227 * <li>{@link Notification#bigContentView bigContentView}</li> 228 * <li>{@link Notification#headsUpContentView headsUpContentView}</li> 229 * <li>{@link Notification#EXTRA_LARGE_ICON extras[EXTRA_LARGE_ICON]}</li> 230 * <li>{@link Notification#EXTRA_LARGE_ICON_BIG extras[EXTRA_LARGE_ICON_BIG]}</li> 231 * <li>{@link Notification#EXTRA_PICTURE extras[EXTRA_PICTURE]}</li> 232 * <li>{@link Notification#EXTRA_BIG_TEXT extras[EXTRA_BIG_TEXT]}</li> 233 * </ol> 234 * 235 * @hide 236 * @removed 237 */ 238 @SystemApi 239 public static final int TRIM_LIGHT = 1; 240 241 242 /** @hide */ 243 @IntDef(prefix = { "NOTIFICATION_CHANNEL_OR_GROUP_" }, value = { 244 NOTIFICATION_CHANNEL_OR_GROUP_ADDED, 245 NOTIFICATION_CHANNEL_OR_GROUP_UPDATED, 246 NOTIFICATION_CHANNEL_OR_GROUP_DELETED 247 }) 248 @Retention(RetentionPolicy.SOURCE) 249 public @interface ChannelOrGroupModificationTypes {} 250 251 /** 252 * Channel or group modification reason provided to 253 * {@link #onNotificationChannelModified(String, UserHandle,NotificationChannel, int)} or 254 * {@link #onNotificationChannelGroupModified(String, UserHandle, NotificationChannelGroup, 255 * int)}- the provided object was created. 256 */ 257 public static final int NOTIFICATION_CHANNEL_OR_GROUP_ADDED = 1; 258 259 /** 260 * Channel or group modification reason provided to 261 * {@link #onNotificationChannelModified(String, UserHandle, NotificationChannel, int)} or 262 * {@link #onNotificationChannelGroupModified(String, UserHandle,NotificationChannelGroup, int)} 263 * - the provided object was updated. 264 */ 265 public static final int NOTIFICATION_CHANNEL_OR_GROUP_UPDATED = 2; 266 267 /** 268 * Channel or group modification reason provided to 269 * {@link #onNotificationChannelModified(String, UserHandle, NotificationChannel, int)} or 270 * {@link #onNotificationChannelGroupModified(String, UserHandle, NotificationChannelGroup, 271 * int)}- the provided object was deleted. 272 */ 273 public static final int NOTIFICATION_CHANNEL_OR_GROUP_DELETED = 3; 274 275 private final Object mLock = new Object(); 276 277 private Handler mHandler; 278 279 /** @hide */ 280 protected NotificationListenerWrapper mWrapper = null; 281 private boolean isConnected = false; 282 283 @GuardedBy("mLock") 284 private RankingMap mRankingMap; 285 286 /** 287 * @hide 288 */ 289 protected INotificationManager mNoMan; 290 291 /** 292 * Only valid after a successful call to (@link registerAsService}. 293 * @hide 294 */ 295 protected int mCurrentUser; 296 297 /** 298 * This context is required for system services since NotificationListenerService isn't 299 * started as a real Service and hence no context is available.. 300 * @hide 301 */ 302 protected Context mSystemContext; 303 304 /** 305 * The {@link Intent} that must be declared as handled by the service. 306 */ 307 @SdkConstant(SdkConstant.SdkConstantType.SERVICE_ACTION) 308 public static final String SERVICE_INTERFACE 309 = "android.service.notification.NotificationListenerService"; 310 311 @Override 312 protected void attachBaseContext(Context base) { 313 super.attachBaseContext(base); 314 mHandler = new MyHandler(getMainLooper()); 315 } 316 317 /** 318 * Implement this method to learn about new notifications as they are posted by apps. 319 * 320 * @param sbn A data structure encapsulating the original {@link android.app.Notification} 321 * object as well as its identifying information (tag and id) and source 322 * (package name). 323 */ 324 public void onNotificationPosted(StatusBarNotification sbn) { 325 // optional 326 } 327 328 /** 329 * Implement this method to learn about new notifications as they are posted by apps. 330 * 331 * @param sbn A data structure encapsulating the original {@link android.app.Notification} 332 * object as well as its identifying information (tag and id) and source 333 * (package name). 334 * @param rankingMap The current ranking map that can be used to retrieve ranking information 335 * for active notifications, including the newly posted one. 336 */ 337 public void onNotificationPosted(StatusBarNotification sbn, RankingMap rankingMap) { 338 onNotificationPosted(sbn); 339 } 340 341 /** 342 * Implement this method to learn when notifications are removed. 343 * <p> 344 * This might occur because the user has dismissed the notification using system UI (or another 345 * notification listener) or because the app has withdrawn the notification. 346 * <p> 347 * NOTE: The {@link StatusBarNotification} object you receive will be "light"; that is, the 348 * result from {@link StatusBarNotification#getNotification} may be missing some heavyweight 349 * fields such as {@link android.app.Notification#contentView} and 350 * {@link android.app.Notification#largeIcon}. However, all other fields on 351 * {@link StatusBarNotification}, sufficient to match this call with a prior call to 352 * {@link #onNotificationPosted(StatusBarNotification)}, will be intact. 353 * 354 * @param sbn A data structure encapsulating at least the original information (tag and id) 355 * and source (package name) used to post the {@link android.app.Notification} that 356 * was just removed. 357 */ 358 public void onNotificationRemoved(StatusBarNotification sbn) { 359 // optional 360 } 361 362 /** 363 * Implement this method to learn when notifications are removed. 364 * <p> 365 * This might occur because the user has dismissed the notification using system UI (or another 366 * notification listener) or because the app has withdrawn the notification. 367 * <p> 368 * NOTE: The {@link StatusBarNotification} object you receive will be "light"; that is, the 369 * result from {@link StatusBarNotification#getNotification} may be missing some heavyweight 370 * fields such as {@link android.app.Notification#contentView} and 371 * {@link android.app.Notification#largeIcon}. However, all other fields on 372 * {@link StatusBarNotification}, sufficient to match this call with a prior call to 373 * {@link #onNotificationPosted(StatusBarNotification)}, will be intact. 374 * 375 * @param sbn A data structure encapsulating at least the original information (tag and id) 376 * and source (package name) used to post the {@link android.app.Notification} that 377 * was just removed. 378 * @param rankingMap The current ranking map that can be used to retrieve ranking information 379 * for active notifications. 380 * 381 */ 382 public void onNotificationRemoved(StatusBarNotification sbn, RankingMap rankingMap) { 383 onNotificationRemoved(sbn); 384 } 385 386 387 /** 388 * Implement this method to learn when notifications are removed and why. 389 * <p> 390 * This might occur because the user has dismissed the notification using system UI (or another 391 * notification listener) or because the app has withdrawn the notification. 392 * <p> 393 * NOTE: The {@link StatusBarNotification} object you receive will be "light"; that is, the 394 * result from {@link StatusBarNotification#getNotification} may be missing some heavyweight 395 * fields such as {@link android.app.Notification#contentView} and 396 * {@link android.app.Notification#largeIcon}. However, all other fields on 397 * {@link StatusBarNotification}, sufficient to match this call with a prior call to 398 * {@link #onNotificationPosted(StatusBarNotification)}, will be intact. 399 * 400 ** @param sbn A data structure encapsulating at least the original information (tag and id) 401 * and source (package name) used to post the {@link android.app.Notification} that 402 * was just removed. 403 * @param rankingMap The current ranking map that can be used to retrieve ranking information 404 * for active notifications. 405 * @param reason see {@link #REASON_LISTENER_CANCEL}, etc. 406 */ 407 public void onNotificationRemoved(StatusBarNotification sbn, RankingMap rankingMap, 408 int reason) { 409 onNotificationRemoved(sbn, rankingMap); 410 } 411 412 /** 413 * NotificationStats are not populated for notification listeners, so fall back to 414 * {@link #onNotificationRemoved(StatusBarNotification, RankingMap, int)}. 415 * 416 * @hide 417 */ 418 @TestApi 419 public void onNotificationRemoved(StatusBarNotification sbn, RankingMap rankingMap, 420 NotificationStats stats, int reason) { 421 onNotificationRemoved(sbn, rankingMap, reason); 422 } 423 424 /** 425 * Implement this method to learn about when the listener is enabled and connected to 426 * the notification manager. You are safe to call {@link #getActiveNotifications()} 427 * at this time. 428 */ 429 public void onListenerConnected() { 430 // optional 431 } 432 433 /** 434 * Implement this method to learn about when the listener is disconnected from the 435 * notification manager.You will not receive any events after this call, and may only 436 * call {@link #requestRebind(ComponentName)} at this time. 437 */ 438 public void onListenerDisconnected() { 439 // optional 440 } 441 442 /** 443 * Implement this method to be notified when the notification ranking changes. 444 * 445 * @param rankingMap The current ranking map that can be used to retrieve ranking information 446 * for active notifications. 447 */ 448 public void onNotificationRankingUpdate(RankingMap rankingMap) { 449 // optional 450 } 451 452 /** 453 * Implement this method to be notified when the 454 * {@link #getCurrentListenerHints() Listener hints} change. 455 * 456 * @param hints The current {@link #getCurrentListenerHints() listener hints}. 457 */ 458 public void onListenerHintsChanged(int hints) { 459 // optional 460 } 461 462 /** 463 * Implement this method to learn about notification channel modifications. 464 * 465 * <p>The caller must have {@link CompanionDeviceManager#getAssociations() an associated 466 * device} in order to receive this callback. 467 * 468 * @param pkg The package the channel belongs to. 469 * @param user The user on which the change was made. 470 * @param channel The channel that has changed. 471 * @param modificationType One of {@link #NOTIFICATION_CHANNEL_OR_GROUP_ADDED}, 472 * {@link #NOTIFICATION_CHANNEL_OR_GROUP_UPDATED}, 473 * {@link #NOTIFICATION_CHANNEL_OR_GROUP_DELETED}. 474 */ 475 public void onNotificationChannelModified(String pkg, UserHandle user, 476 NotificationChannel channel, @ChannelOrGroupModificationTypes int modificationType) { 477 // optional 478 } 479 480 /** 481 * Implement this method to learn about notification channel group modifications. 482 * 483 * <p>The caller must have {@link CompanionDeviceManager#getAssociations() an associated 484 * device} in order to receive this callback. 485 * 486 * @param pkg The package the group belongs to. 487 * @param user The user on which the change was made. 488 * @param group The group that has changed. 489 * @param modificationType One of {@link #NOTIFICATION_CHANNEL_OR_GROUP_ADDED}, 490 * {@link #NOTIFICATION_CHANNEL_OR_GROUP_UPDATED}, 491 * {@link #NOTIFICATION_CHANNEL_OR_GROUP_DELETED}. 492 */ 493 public void onNotificationChannelGroupModified(String pkg, UserHandle user, 494 NotificationChannelGroup group, @ChannelOrGroupModificationTypes int modificationType) { 495 // optional 496 } 497 498 /** 499 * Implement this method to be notified when the 500 * {@link #getCurrentInterruptionFilter() interruption filter} changed. 501 * 502 * @param interruptionFilter The current 503 * {@link #getCurrentInterruptionFilter() interruption filter}. 504 */ 505 public void onInterruptionFilterChanged(int interruptionFilter) { 506 // optional 507 } 508 509 /** @hide */ 510 protected final INotificationManager getNotificationInterface() { 511 if (mNoMan == null) { 512 mNoMan = INotificationManager.Stub.asInterface( 513 ServiceManager.getService(Context.NOTIFICATION_SERVICE)); 514 } 515 return mNoMan; 516 } 517 518 /** 519 * Inform the notification manager about dismissal of a single notification. 520 * <p> 521 * Use this if your listener has a user interface that allows the user to dismiss individual 522 * notifications, similar to the behavior of Android's status bar and notification panel. 523 * It should be called after the user dismisses a single notification using your UI; 524 * upon being informed, the notification manager will actually remove the notification 525 * and you will get an {@link #onNotificationRemoved(StatusBarNotification)} callback. 526 * <p> 527 * <b>Note:</b> If your listener allows the user to fire a notification's 528 * {@link android.app.Notification#contentIntent} by tapping/clicking/etc., you should call 529 * this method at that time <i>if</i> the Notification in question has the 530 * {@link android.app.Notification#FLAG_AUTO_CANCEL} flag set. 531 * 532 * <p>The service should wait for the {@link #onListenerConnected()} event 533 * before performing this operation. 534 * 535 * @param pkg Package of the notifying app. 536 * @param tag Tag of the notification as specified by the notifying app in 537 * {@link android.app.NotificationManager#notify(String, int, android.app.Notification)}. 538 * @param id ID of the notification as specified by the notifying app in 539 * {@link android.app.NotificationManager#notify(String, int, android.app.Notification)}. 540 * <p> 541 * @deprecated Use {@link #cancelNotification(String key)} 542 * instead. Beginning with {@link android.os.Build.VERSION_CODES#LOLLIPOP} this method will no longer 543 * cancel the notification. It will continue to cancel the notification for applications 544 * whose {@code targetSdkVersion} is earlier than {@link android.os.Build.VERSION_CODES#LOLLIPOP}. 545 */ 546 @Deprecated 547 public final void cancelNotification(String pkg, String tag, int id) { 548 if (!isBound()) return; 549 try { 550 getNotificationInterface().cancelNotificationFromListener( 551 mWrapper, pkg, tag, id); 552 } catch (android.os.RemoteException ex) { 553 Log.v(TAG, "Unable to contact notification manager", ex); 554 } 555 } 556 557 /** 558 * Inform the notification manager about dismissal of a single notification. 559 * <p> 560 * Use this if your listener has a user interface that allows the user to dismiss individual 561 * notifications, similar to the behavior of Android's status bar and notification panel. 562 * It should be called after the user dismisses a single notification using your UI; 563 * upon being informed, the notification manager will actually remove the notification 564 * and you will get an {@link #onNotificationRemoved(StatusBarNotification)} callback. 565 * <p> 566 * <b>Note:</b> If your listener allows the user to fire a notification's 567 * {@link android.app.Notification#contentIntent} by tapping/clicking/etc., you should call 568 * this method at that time <i>if</i> the Notification in question has the 569 * {@link android.app.Notification#FLAG_AUTO_CANCEL} flag set. 570 * <p> 571 * 572 * <p>The service should wait for the {@link #onListenerConnected()} event 573 * before performing this operation. 574 * 575 * @param key Notification to dismiss from {@link StatusBarNotification#getKey()}. 576 */ 577 public final void cancelNotification(String key) { 578 if (!isBound()) return; 579 try { 580 getNotificationInterface().cancelNotificationsFromListener(mWrapper, 581 new String[] { key }); 582 } catch (android.os.RemoteException ex) { 583 Log.v(TAG, "Unable to contact notification manager", ex); 584 } 585 } 586 587 /** 588 * Inform the notification manager about dismissal of all notifications. 589 * <p> 590 * Use this if your listener has a user interface that allows the user to dismiss all 591 * notifications, similar to the behavior of Android's status bar and notification panel. 592 * It should be called after the user invokes the "dismiss all" function of your UI; 593 * upon being informed, the notification manager will actually remove all active notifications 594 * and you will get multiple {@link #onNotificationRemoved(StatusBarNotification)} callbacks. 595 * 596 * <p>The service should wait for the {@link #onListenerConnected()} event 597 * before performing this operation. 598 * 599 * {@see #cancelNotification(String, String, int)} 600 */ 601 public final void cancelAllNotifications() { 602 cancelNotifications(null /*all*/); 603 } 604 605 /** 606 * Inform the notification manager about dismissal of specific notifications. 607 * <p> 608 * Use this if your listener has a user interface that allows the user to dismiss 609 * multiple notifications at once. 610 * 611 * <p>The service should wait for the {@link #onListenerConnected()} event 612 * before performing this operation. 613 * 614 * @param keys Notifications to dismiss, or {@code null} to dismiss all. 615 * 616 * {@see #cancelNotification(String, String, int)} 617 */ 618 public final void cancelNotifications(String[] keys) { 619 if (!isBound()) return; 620 try { 621 getNotificationInterface().cancelNotificationsFromListener(mWrapper, keys); 622 } catch (android.os.RemoteException ex) { 623 Log.v(TAG, "Unable to contact notification manager", ex); 624 } 625 } 626 627 /** 628 * Inform the notification manager about snoozing a specific notification. 629 * <p> 630 * Use this if your listener has a user interface that allows the user to snooze a notification 631 * until a given {@link SnoozeCriterion}. It should be called after the user snoozes a single 632 * notification using your UI; upon being informed, the notification manager will actually 633 * remove the notification and you will get an 634 * {@link #onNotificationRemoved(StatusBarNotification)} callback. When the snoozing period 635 * expires, you will get a {@link #onNotificationPosted(StatusBarNotification, RankingMap)} 636 * callback for the notification. 637 * @param key The key of the notification to snooze 638 * @param snoozeCriterionId The{@link SnoozeCriterion#getId()} of a context to snooze the 639 * notification until. 640 * @hide 641 * @removed 642 */ 643 @SystemApi 644 public final void snoozeNotification(String key, String snoozeCriterionId) { 645 if (!isBound()) return; 646 try { 647 getNotificationInterface().snoozeNotificationUntilContextFromListener( 648 mWrapper, key, snoozeCriterionId); 649 } catch (android.os.RemoteException ex) { 650 Log.v(TAG, "Unable to contact notification manager", ex); 651 } 652 } 653 654 /** 655 * Inform the notification manager about snoozing a specific notification. 656 * <p> 657 * Use this if your listener has a user interface that allows the user to snooze a notification 658 * for a time. It should be called after the user snoozes a single notification using 659 * your UI; upon being informed, the notification manager will actually remove the notification 660 * and you will get an {@link #onNotificationRemoved(StatusBarNotification)} callback. When the 661 * snoozing period expires, you will get a 662 * {@link #onNotificationPosted(StatusBarNotification, RankingMap)} callback for the 663 * notification. 664 * @param key The key of the notification to snooze 665 * @param durationMs A duration to snooze the notification for, in milliseconds. 666 */ 667 public final void snoozeNotification(String key, long durationMs) { 668 if (!isBound()) return; 669 try { 670 getNotificationInterface().snoozeNotificationUntilFromListener( 671 mWrapper, key, durationMs); 672 } catch (android.os.RemoteException ex) { 673 Log.v(TAG, "Unable to contact notification manager", ex); 674 } 675 } 676 677 678 /** 679 * Inform the notification manager that these notifications have been viewed by the 680 * user. This should only be called when there is sufficient confidence that the user is 681 * looking at the notifications, such as when the notifications appear on the screen due to 682 * an explicit user interaction. 683 * 684 * <p>The service should wait for the {@link #onListenerConnected()} event 685 * before performing this operation. 686 * 687 * @param keys Notifications to mark as seen. 688 */ 689 public final void setNotificationsShown(String[] keys) { 690 if (!isBound()) return; 691 try { 692 getNotificationInterface().setNotificationsShownFromListener(mWrapper, keys); 693 } catch (android.os.RemoteException ex) { 694 Log.v(TAG, "Unable to contact notification manager", ex); 695 } 696 } 697 698 699 /** 700 * Updates a notification channel for a given package for a given user. This should only be used 701 * to reflect changes a user has made to the channel via the listener's user interface. 702 * 703 * <p>This method will throw a security exception if you don't have access to notifications 704 * for the given user.</p> 705 * <p>The caller must have {@link CompanionDeviceManager#getAssociations() an associated 706 * device} in order to use this method. 707 * 708 * @param pkg The package the channel belongs to. 709 * @param user The user the channel belongs to. 710 * @param channel the channel to update. 711 */ 712 public final void updateNotificationChannel(@NonNull String pkg, @NonNull UserHandle user, 713 @NonNull NotificationChannel channel) { 714 if (!isBound()) return; 715 try { 716 getNotificationInterface().updateNotificationChannelFromPrivilegedListener( 717 mWrapper, pkg, user, channel); 718 } catch (RemoteException e) { 719 Log.v(TAG, "Unable to contact notification manager", e); 720 throw e.rethrowFromSystemServer(); 721 } 722 } 723 724 /** 725 * Returns all notification channels belonging to the given package for a given user. 726 * 727 * <p>This method will throw a security exception if you don't have access to notifications 728 * for the given user.</p> 729 * <p>The caller must have {@link CompanionDeviceManager#getAssociations() an associated 730 * device} in order to use this method. 731 * 732 * @param pkg The package to retrieve channels for. 733 */ 734 public final List<NotificationChannel> getNotificationChannels(@NonNull String pkg, 735 @NonNull UserHandle user) { 736 if (!isBound()) return null; 737 try { 738 739 return getNotificationInterface().getNotificationChannelsFromPrivilegedListener( 740 mWrapper, pkg, user).getList(); 741 } catch (RemoteException e) { 742 Log.v(TAG, "Unable to contact notification manager", e); 743 throw e.rethrowFromSystemServer(); 744 } 745 } 746 747 /** 748 * Returns all notification channel groups belonging to the given package for a given user. 749 * 750 * <p>This method will throw a security exception if you don't have access to notifications 751 * for the given user.</p> 752 * <p>The caller must have {@link CompanionDeviceManager#getAssociations() an associated 753 * device} in order to use this method. 754 * 755 * @param pkg The package to retrieve channel groups for. 756 */ 757 public final List<NotificationChannelGroup> getNotificationChannelGroups(@NonNull String pkg, 758 @NonNull UserHandle user) { 759 if (!isBound()) return null; 760 try { 761 762 return getNotificationInterface().getNotificationChannelGroupsFromPrivilegedListener( 763 mWrapper, pkg, user).getList(); 764 } catch (RemoteException e) { 765 Log.v(TAG, "Unable to contact notification manager", e); 766 throw e.rethrowFromSystemServer(); 767 } 768 } 769 770 /** 771 * Sets the notification trim that will be received via {@link #onNotificationPosted}. 772 * 773 * <p> 774 * Setting a trim other than {@link #TRIM_FULL} enables listeners that don't need access to the 775 * full notification features right away to reduce their memory footprint. Full notifications 776 * can be requested on-demand via {@link #getActiveNotifications(int)}. 777 * 778 * <p> 779 * Set to {@link #TRIM_FULL} initially. 780 * 781 * <p>The service should wait for the {@link #onListenerConnected()} event 782 * before performing this operation. 783 * 784 * @hide 785 * @removed 786 * 787 * @param trim trim of the notifications to be passed via {@link #onNotificationPosted}. 788 * See <code>TRIM_*</code> constants. 789 */ 790 @SystemApi 791 public final void setOnNotificationPostedTrim(int trim) { 792 if (!isBound()) return; 793 try { 794 getNotificationInterface().setOnNotificationPostedTrimFromListener(mWrapper, trim); 795 } catch (RemoteException ex) { 796 Log.v(TAG, "Unable to contact notification manager", ex); 797 } 798 } 799 800 /** 801 * Request the list of outstanding notifications (that is, those that are visible to the 802 * current user). Useful when you don't know what's already been posted. 803 * 804 * <p>The service should wait for the {@link #onListenerConnected()} event 805 * before performing this operation. 806 * 807 * @return An array of active notifications, sorted in natural order. 808 */ 809 public StatusBarNotification[] getActiveNotifications() { 810 return getActiveNotifications(null, TRIM_FULL); 811 } 812 813 /** 814 * Like {@link #getActiveNotifications()}, but returns the list of currently snoozed 815 * notifications, for all users this listener has access to. 816 * 817 * <p>The service should wait for the {@link #onListenerConnected()} event 818 * before performing this operation. 819 * 820 * @return An array of snoozed notifications, sorted in natural order. 821 */ 822 public final StatusBarNotification[] getSnoozedNotifications() { 823 try { 824 ParceledListSlice<StatusBarNotification> parceledList = getNotificationInterface() 825 .getSnoozedNotificationsFromListener(mWrapper, TRIM_FULL); 826 return cleanUpNotificationList(parceledList); 827 } catch (android.os.RemoteException ex) { 828 Log.v(TAG, "Unable to contact notification manager", ex); 829 } 830 return null; 831 } 832 833 /** 834 * Request the list of outstanding notifications (that is, those that are visible to the 835 * current user). Useful when you don't know what's already been posted. 836 * 837 * @hide 838 * @removed 839 * 840 * @param trim trim of the notifications to be returned. See <code>TRIM_*</code> constants. 841 * @return An array of active notifications, sorted in natural order. 842 */ 843 @SystemApi 844 public StatusBarNotification[] getActiveNotifications(int trim) { 845 return getActiveNotifications(null, trim); 846 } 847 848 /** 849 * Request one or more notifications by key. Useful if you have been keeping track of 850 * notifications but didn't want to retain the bits, and now need to go back and extract 851 * more data out of those notifications. 852 * 853 * <p>The service should wait for the {@link #onListenerConnected()} event 854 * before performing this operation. 855 * 856 * @param keys the keys of the notifications to request 857 * @return An array of notifications corresponding to the requested keys, in the 858 * same order as the key list. 859 */ 860 public StatusBarNotification[] getActiveNotifications(String[] keys) { 861 return getActiveNotifications(keys, TRIM_FULL); 862 } 863 864 /** 865 * Request one or more notifications by key. Useful if you have been keeping track of 866 * notifications but didn't want to retain the bits, and now need to go back and extract 867 * more data out of those notifications. 868 * 869 * @hide 870 * @removed 871 * 872 * @param keys the keys of the notifications to request 873 * @param trim trim of the notifications to be returned. See <code>TRIM_*</code> constants. 874 * @return An array of notifications corresponding to the requested keys, in the 875 * same order as the key list. 876 */ 877 @SystemApi 878 public StatusBarNotification[] getActiveNotifications(String[] keys, int trim) { 879 if (!isBound()) 880 return null; 881 try { 882 ParceledListSlice<StatusBarNotification> parceledList = getNotificationInterface() 883 .getActiveNotificationsFromListener(mWrapper, keys, trim); 884 return cleanUpNotificationList(parceledList); 885 } catch (android.os.RemoteException ex) { 886 Log.v(TAG, "Unable to contact notification manager", ex); 887 } 888 return null; 889 } 890 891 private StatusBarNotification[] cleanUpNotificationList( 892 ParceledListSlice<StatusBarNotification> parceledList) { 893 List<StatusBarNotification> list = parceledList.getList(); 894 ArrayList<StatusBarNotification> corruptNotifications = null; 895 int N = list.size(); 896 for (int i = 0; i < N; i++) { 897 StatusBarNotification sbn = list.get(i); 898 Notification notification = sbn.getNotification(); 899 try { 900 // convert icon metadata to legacy format for older clients 901 createLegacyIconExtras(notification); 902 // populate remote views for older clients. 903 maybePopulateRemoteViews(notification); 904 // populate people for older clients. 905 maybePopulatePeople(notification); 906 } catch (IllegalArgumentException e) { 907 if (corruptNotifications == null) { 908 corruptNotifications = new ArrayList<>(N); 909 } 910 corruptNotifications.add(sbn); 911 Log.w(TAG, "get(Active/Snoozed)Notifications: can't rebuild notification from " + 912 sbn.getPackageName()); 913 } 914 } 915 if (corruptNotifications != null) { 916 list.removeAll(corruptNotifications); 917 } 918 return list.toArray(new StatusBarNotification[list.size()]); 919 } 920 921 /** 922 * Gets the set of hints representing current state. 923 * 924 * <p> 925 * The current state may differ from the requested state if the hint represents state 926 * shared across all listeners or a feature the notification host does not support or refuses 927 * to grant. 928 * 929 * <p>The service should wait for the {@link #onListenerConnected()} event 930 * before performing this operation. 931 * 932 * @return Zero or more of the HINT_ constants. 933 */ 934 public final int getCurrentListenerHints() { 935 if (!isBound()) return 0; 936 try { 937 return getNotificationInterface().getHintsFromListener(mWrapper); 938 } catch (android.os.RemoteException ex) { 939 Log.v(TAG, "Unable to contact notification manager", ex); 940 return 0; 941 } 942 } 943 944 /** 945 * Gets the current notification interruption filter active on the host. 946 * 947 * <p> 948 * The interruption filter defines which notifications are allowed to interrupt the user 949 * (e.g. via sound & vibration) and is applied globally. Listeners can find out whether 950 * a specific notification matched the interruption filter via 951 * {@link Ranking#matchesInterruptionFilter()}. 952 * <p> 953 * The current filter may differ from the previously requested filter if the notification host 954 * does not support or refuses to apply the requested filter, or if another component changed 955 * the filter in the meantime. 956 * <p> 957 * Listen for updates using {@link #onInterruptionFilterChanged(int)}. 958 * 959 * <p>The service should wait for the {@link #onListenerConnected()} event 960 * before performing this operation. 961 * 962 * @return One of the INTERRUPTION_FILTER_ constants, or INTERRUPTION_FILTER_UNKNOWN when 963 * unavailable. 964 */ 965 public final int getCurrentInterruptionFilter() { 966 if (!isBound()) return INTERRUPTION_FILTER_UNKNOWN; 967 try { 968 return getNotificationInterface().getInterruptionFilterFromListener(mWrapper); 969 } catch (android.os.RemoteException ex) { 970 Log.v(TAG, "Unable to contact notification manager", ex); 971 return INTERRUPTION_FILTER_UNKNOWN; 972 } 973 } 974 975 /** 976 * Sets the desired {@link #getCurrentListenerHints() listener hints}. 977 * 978 * <p> 979 * This is merely a request, the host may or may not choose to take action depending 980 * on other listener requests or other global state. 981 * <p> 982 * Listen for updates using {@link #onListenerHintsChanged(int)}. 983 * 984 * <p>The service should wait for the {@link #onListenerConnected()} event 985 * before performing this operation. 986 * 987 * @param hints One or more of the HINT_ constants. 988 */ 989 public final void requestListenerHints(int hints) { 990 if (!isBound()) return; 991 try { 992 getNotificationInterface().requestHintsFromListener(mWrapper, hints); 993 } catch (android.os.RemoteException ex) { 994 Log.v(TAG, "Unable to contact notification manager", ex); 995 } 996 } 997 998 /** 999 * Sets the desired {@link #getCurrentInterruptionFilter() interruption filter}. 1000 * 1001 * <p> 1002 * This is merely a request, the host may or may not choose to apply the requested 1003 * interruption filter depending on other listener requests or other global state. 1004 * <p> 1005 * Listen for updates using {@link #onInterruptionFilterChanged(int)}. 1006 * 1007 * <p>The service should wait for the {@link #onListenerConnected()} event 1008 * before performing this operation. 1009 * 1010 * @param interruptionFilter One of the INTERRUPTION_FILTER_ constants. 1011 */ 1012 public final void requestInterruptionFilter(int interruptionFilter) { 1013 if (!isBound()) return; 1014 try { 1015 getNotificationInterface() 1016 .requestInterruptionFilterFromListener(mWrapper, interruptionFilter); 1017 } catch (android.os.RemoteException ex) { 1018 Log.v(TAG, "Unable to contact notification manager", ex); 1019 } 1020 } 1021 1022 /** 1023 * Returns current ranking information. 1024 * 1025 * <p> 1026 * The returned object represents the current ranking snapshot and only 1027 * applies for currently active notifications. 1028 * <p> 1029 * Generally you should use the RankingMap that is passed with events such 1030 * as {@link #onNotificationPosted(StatusBarNotification, RankingMap)}, 1031 * {@link #onNotificationRemoved(StatusBarNotification, RankingMap)}, and 1032 * so on. This method should only be used when needing access outside of 1033 * such events, for example to retrieve the RankingMap right after 1034 * initialization. 1035 * 1036 * <p>The service should wait for the {@link #onListenerConnected()} event 1037 * before performing this operation. 1038 * 1039 * @return A {@link RankingMap} object providing access to ranking information 1040 */ 1041 public RankingMap getCurrentRanking() { 1042 synchronized (mLock) { 1043 return mRankingMap; 1044 } 1045 } 1046 1047 /** 1048 * This is not the lifecycle event you are looking for. 1049 * 1050 * <p>The service should wait for the {@link #onListenerConnected()} event 1051 * before performing any operations. 1052 */ 1053 @Override 1054 public IBinder onBind(Intent intent) { 1055 if (mWrapper == null) { 1056 mWrapper = new NotificationListenerWrapper(); 1057 } 1058 return mWrapper; 1059 } 1060 1061 /** @hide */ 1062 protected boolean isBound() { 1063 if (mWrapper == null) { 1064 Log.w(TAG, "Notification listener service not yet bound."); 1065 return false; 1066 } 1067 return true; 1068 } 1069 1070 @Override 1071 public void onDestroy() { 1072 onListenerDisconnected(); 1073 super.onDestroy(); 1074 } 1075 1076 /** 1077 * Directly register this service with the Notification Manager. 1078 * 1079 * <p>Only system services may use this call. It will fail for non-system callers. 1080 * Apps should ask the user to add their listener in Settings. 1081 * 1082 * @param context Context required for accessing resources. Since this service isn't 1083 * launched as a real Service when using this method, a context has to be passed in. 1084 * @param componentName the component that will consume the notification information 1085 * @param currentUser the user to use as the stream filter 1086 * @hide 1087 * @removed 1088 */ 1089 @SystemApi 1090 public void registerAsSystemService(Context context, ComponentName componentName, 1091 int currentUser) throws RemoteException { 1092 if (mWrapper == null) { 1093 mWrapper = new NotificationListenerWrapper(); 1094 } 1095 mSystemContext = context; 1096 INotificationManager noMan = getNotificationInterface(); 1097 mHandler = new MyHandler(context.getMainLooper()); 1098 mCurrentUser = currentUser; 1099 noMan.registerListener(mWrapper, componentName, currentUser); 1100 } 1101 1102 /** 1103 * Directly unregister this service from the Notification Manager. 1104 * 1105 * <p>This method will fail for listeners that were not registered 1106 * with (@link registerAsService). 1107 * @hide 1108 * @removed 1109 */ 1110 @SystemApi 1111 public void unregisterAsSystemService() throws RemoteException { 1112 if (mWrapper != null) { 1113 INotificationManager noMan = getNotificationInterface(); 1114 noMan.unregisterListener(mWrapper, mCurrentUser); 1115 } 1116 } 1117 1118 /** 1119 * Request that the listener be rebound, after a previous call to {@link #requestUnbind}. 1120 * 1121 * <p>This method will fail for listeners that have 1122 * not been granted the permission by the user. 1123 */ 1124 public static void requestRebind(ComponentName componentName) { 1125 INotificationManager noMan = INotificationManager.Stub.asInterface( 1126 ServiceManager.getService(Context.NOTIFICATION_SERVICE)); 1127 try { 1128 noMan.requestBindListener(componentName); 1129 } catch (RemoteException ex) { 1130 throw ex.rethrowFromSystemServer(); 1131 } 1132 } 1133 1134 /** 1135 * Request that the service be unbound. 1136 * 1137 * <p>Once this is called, you will no longer receive updates and no method calls are 1138 * guaranteed to be successful, until you next receive the {@link #onListenerConnected()} event. 1139 * The service will likely be killed by the system after this call. 1140 * 1141 * <p>The service should wait for the {@link #onListenerConnected()} event 1142 * before performing this operation. I know it's tempting, but you must wait. 1143 */ 1144 public final void requestUnbind() { 1145 if (mWrapper != null) { 1146 INotificationManager noMan = getNotificationInterface(); 1147 try { 1148 noMan.requestUnbindListener(mWrapper); 1149 // Disable future messages. 1150 isConnected = false; 1151 } catch (RemoteException ex) { 1152 throw ex.rethrowFromSystemServer(); 1153 } 1154 } 1155 } 1156 1157 /** Convert new-style Icons to legacy representations for pre-M clients. */ 1158 private void createLegacyIconExtras(Notification n) { 1159 Icon smallIcon = n.getSmallIcon(); 1160 Icon largeIcon = n.getLargeIcon(); 1161 if (smallIcon != null && smallIcon.getType() == Icon.TYPE_RESOURCE) { 1162 n.extras.putInt(Notification.EXTRA_SMALL_ICON, smallIcon.getResId()); 1163 n.icon = smallIcon.getResId(); 1164 } 1165 if (largeIcon != null) { 1166 Drawable d = largeIcon.loadDrawable(getContext()); 1167 if (d != null && d instanceof BitmapDrawable) { 1168 final Bitmap largeIconBits = ((BitmapDrawable) d).getBitmap(); 1169 n.extras.putParcelable(Notification.EXTRA_LARGE_ICON, largeIconBits); 1170 n.largeIcon = largeIconBits; 1171 } 1172 } 1173 } 1174 1175 /** 1176 * Populates remote views for pre-N targeting apps. 1177 */ 1178 private void maybePopulateRemoteViews(Notification notification) { 1179 if (getContext().getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N) { 1180 Builder builder = Builder.recoverBuilder(getContext(), notification); 1181 1182 // Some styles wrap Notification's contentView, bigContentView and headsUpContentView. 1183 // First inflate them all, only then set them to avoid recursive wrapping. 1184 RemoteViews content = builder.createContentView(); 1185 RemoteViews big = builder.createBigContentView(); 1186 RemoteViews headsUp = builder.createHeadsUpContentView(); 1187 1188 notification.contentView = content; 1189 notification.bigContentView = big; 1190 notification.headsUpContentView = headsUp; 1191 } 1192 } 1193 1194 /** 1195 * Populates remote views for pre-P targeting apps. 1196 */ 1197 private void maybePopulatePeople(Notification notification) { 1198 if (getContext().getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.P) { 1199 ArrayList<Person> people = notification.extras.getParcelableArrayList( 1200 Notification.EXTRA_PEOPLE_LIST); 1201 if (people != null && people.isEmpty()) { 1202 int size = people.size(); 1203 String[] peopleArray = new String[size]; 1204 for (int i = 0; i < size; i++) { 1205 Person person = people.get(i); 1206 peopleArray[i] = person.resolveToLegacyUri(); 1207 } 1208 notification.extras.putStringArray(Notification.EXTRA_PEOPLE, peopleArray); 1209 } 1210 } 1211 } 1212 1213 /** @hide */ 1214 protected class NotificationListenerWrapper extends INotificationListener.Stub { 1215 @Override 1216 public void onNotificationPosted(IStatusBarNotificationHolder sbnHolder, 1217 NotificationRankingUpdate update) { 1218 StatusBarNotification sbn; 1219 try { 1220 sbn = sbnHolder.get(); 1221 } catch (RemoteException e) { 1222 Log.w(TAG, "onNotificationPosted: Error receiving StatusBarNotification", e); 1223 return; 1224 } 1225 1226 try { 1227 // convert icon metadata to legacy format for older clients 1228 createLegacyIconExtras(sbn.getNotification()); 1229 maybePopulateRemoteViews(sbn.getNotification()); 1230 maybePopulatePeople(sbn.getNotification()); 1231 } catch (IllegalArgumentException e) { 1232 // warn and drop corrupt notification 1233 Log.w(TAG, "onNotificationPosted: can't rebuild notification from " + 1234 sbn.getPackageName()); 1235 sbn = null; 1236 } 1237 1238 // protect subclass from concurrent modifications of (@link mNotificationKeys}. 1239 synchronized (mLock) { 1240 applyUpdateLocked(update); 1241 if (sbn != null) { 1242 SomeArgs args = SomeArgs.obtain(); 1243 args.arg1 = sbn; 1244 args.arg2 = mRankingMap; 1245 mHandler.obtainMessage(MyHandler.MSG_ON_NOTIFICATION_POSTED, 1246 args).sendToTarget(); 1247 } else { 1248 // still pass along the ranking map, it may contain other information 1249 mHandler.obtainMessage(MyHandler.MSG_ON_NOTIFICATION_RANKING_UPDATE, 1250 mRankingMap).sendToTarget(); 1251 } 1252 } 1253 1254 } 1255 1256 @Override 1257 public void onNotificationRemoved(IStatusBarNotificationHolder sbnHolder, 1258 NotificationRankingUpdate update, NotificationStats stats, int reason) { 1259 StatusBarNotification sbn; 1260 try { 1261 sbn = sbnHolder.get(); 1262 } catch (RemoteException e) { 1263 Log.w(TAG, "onNotificationRemoved: Error receiving StatusBarNotification", e); 1264 return; 1265 } 1266 // protect subclass from concurrent modifications of (@link mNotificationKeys}. 1267 synchronized (mLock) { 1268 applyUpdateLocked(update); 1269 SomeArgs args = SomeArgs.obtain(); 1270 args.arg1 = sbn; 1271 args.arg2 = mRankingMap; 1272 args.arg3 = reason; 1273 args.arg4 = stats; 1274 mHandler.obtainMessage(MyHandler.MSG_ON_NOTIFICATION_REMOVED, 1275 args).sendToTarget(); 1276 } 1277 1278 } 1279 1280 @Override 1281 public void onListenerConnected(NotificationRankingUpdate update) { 1282 // protect subclass from concurrent modifications of (@link mNotificationKeys}. 1283 synchronized (mLock) { 1284 applyUpdateLocked(update); 1285 } 1286 isConnected = true; 1287 mHandler.obtainMessage(MyHandler.MSG_ON_LISTENER_CONNECTED).sendToTarget(); 1288 } 1289 1290 @Override 1291 public void onNotificationRankingUpdate(NotificationRankingUpdate update) 1292 throws RemoteException { 1293 // protect subclass from concurrent modifications of (@link mNotificationKeys}. 1294 synchronized (mLock) { 1295 applyUpdateLocked(update); 1296 mHandler.obtainMessage(MyHandler.MSG_ON_NOTIFICATION_RANKING_UPDATE, 1297 mRankingMap).sendToTarget(); 1298 } 1299 1300 } 1301 1302 @Override 1303 public void onListenerHintsChanged(int hints) throws RemoteException { 1304 mHandler.obtainMessage(MyHandler.MSG_ON_LISTENER_HINTS_CHANGED, 1305 hints, 0).sendToTarget(); 1306 } 1307 1308 @Override 1309 public void onInterruptionFilterChanged(int interruptionFilter) throws RemoteException { 1310 mHandler.obtainMessage(MyHandler.MSG_ON_INTERRUPTION_FILTER_CHANGED, 1311 interruptionFilter, 0).sendToTarget(); 1312 } 1313 1314 @Override 1315 public void onNotificationEnqueued(IStatusBarNotificationHolder notificationHolder) 1316 throws RemoteException { 1317 // no-op in the listener 1318 } 1319 1320 @Override 1321 public void onNotificationSnoozedUntilContext( 1322 IStatusBarNotificationHolder notificationHolder, String snoozeCriterionId) 1323 throws RemoteException { 1324 // no-op in the listener 1325 } 1326 1327 @Override 1328 public void onNotificationChannelModification(String pkgName, UserHandle user, 1329 NotificationChannel channel, 1330 @ChannelOrGroupModificationTypes int modificationType) { 1331 SomeArgs args = SomeArgs.obtain(); 1332 args.arg1 = pkgName; 1333 args.arg2 = user; 1334 args.arg3 = channel; 1335 args.arg4 = modificationType; 1336 mHandler.obtainMessage( 1337 MyHandler.MSG_ON_NOTIFICATION_CHANNEL_MODIFIED, args).sendToTarget(); 1338 } 1339 1340 @Override 1341 public void onNotificationChannelGroupModification(String pkgName, UserHandle user, 1342 NotificationChannelGroup group, 1343 @ChannelOrGroupModificationTypes int modificationType) { 1344 SomeArgs args = SomeArgs.obtain(); 1345 args.arg1 = pkgName; 1346 args.arg2 = user; 1347 args.arg3 = group; 1348 args.arg4 = modificationType; 1349 mHandler.obtainMessage( 1350 MyHandler.MSG_ON_NOTIFICATION_CHANNEL_GROUP_MODIFIED, args).sendToTarget(); 1351 } 1352 } 1353 1354 /** 1355 * @hide 1356 */ 1357 @GuardedBy("mLock") 1358 public final void applyUpdateLocked(NotificationRankingUpdate update) { 1359 mRankingMap = new RankingMap(update); 1360 } 1361 1362 /** @hide */ 1363 protected Context getContext() { 1364 if (mSystemContext != null) { 1365 return mSystemContext; 1366 } 1367 return this; 1368 } 1369 1370 /** 1371 * Stores ranking related information on a currently active notification. 1372 * 1373 * <p> 1374 * Ranking objects aren't automatically updated as notification events 1375 * occur. Instead, ranking information has to be retrieved again via the 1376 * current {@link RankingMap}. 1377 */ 1378 public static class Ranking { 1379 1380 /** Value signifying that the user has not expressed a per-app visibility override value. 1381 * @hide */ 1382 public static final int VISIBILITY_NO_OVERRIDE = NotificationManager.VISIBILITY_NO_OVERRIDE; 1383 1384 /** 1385 * The user is likely to have a negative reaction to this notification. 1386 */ 1387 public static final int USER_SENTIMENT_NEGATIVE = -1; 1388 /** 1389 * It is not known how the user will react to this notification. 1390 */ 1391 public static final int USER_SENTIMENT_NEUTRAL = 0; 1392 /** 1393 * The user is likely to have a positive reaction to this notification. 1394 */ 1395 public static final int USER_SENTIMENT_POSITIVE = 1; 1396 1397 /** @hide */ 1398 @IntDef(prefix = { "USER_SENTIMENT_" }, value = { 1399 USER_SENTIMENT_NEGATIVE, USER_SENTIMENT_NEUTRAL, USER_SENTIMENT_POSITIVE 1400 }) 1401 @Retention(RetentionPolicy.SOURCE) 1402 public @interface UserSentiment {} 1403 1404 private String mKey; 1405 private int mRank = -1; 1406 private boolean mIsAmbient; 1407 private boolean mMatchesInterruptionFilter; 1408 private int mVisibilityOverride; 1409 private int mSuppressedVisualEffects; 1410 private @NotificationManager.Importance int mImportance; 1411 private CharSequence mImportanceExplanation; 1412 // System specified group key. 1413 private String mOverrideGroupKey; 1414 // Notification assistant channel override. 1415 private NotificationChannel mChannel; 1416 // Notification assistant people override. 1417 private ArrayList<String> mOverridePeople; 1418 // Notification assistant snooze criteria. 1419 private ArrayList<SnoozeCriterion> mSnoozeCriteria; 1420 private boolean mShowBadge; 1421 private @UserSentiment int mUserSentiment = USER_SENTIMENT_NEUTRAL; 1422 private boolean mHidden; 1423 1424 public Ranking() {} 1425 1426 /** 1427 * Returns the key of the notification this Ranking applies to. 1428 */ 1429 public String getKey() { 1430 return mKey; 1431 } 1432 1433 /** 1434 * Returns the rank of the notification. 1435 * 1436 * @return the rank of the notification, that is the 0-based index in 1437 * the list of active notifications. 1438 */ 1439 public int getRank() { 1440 return mRank; 1441 } 1442 1443 /** 1444 * Returns whether the notification is an ambient notification, that is 1445 * a notification that doesn't require the user's immediate attention. 1446 */ 1447 public boolean isAmbient() { 1448 return mIsAmbient; 1449 } 1450 1451 /** 1452 * Returns the user specified visibility for the package that posted 1453 * this notification, or 1454 * {@link NotificationListenerService.Ranking#VISIBILITY_NO_OVERRIDE} if 1455 * no such preference has been expressed. 1456 * @hide 1457 */ 1458 public int getVisibilityOverride() { 1459 return mVisibilityOverride; 1460 } 1461 1462 /** 1463 * Returns the type(s) of visual effects that should be suppressed for this notification. 1464 * See {@link NotificationManager.Policy}, e.g. 1465 * {@link NotificationManager.Policy#SUPPRESSED_EFFECT_LIGHTS}. 1466 */ 1467 public int getSuppressedVisualEffects() { 1468 return mSuppressedVisualEffects; 1469 } 1470 1471 /** 1472 * Returns whether the notification matches the user's interruption 1473 * filter. 1474 * 1475 * @return {@code true} if the notification is allowed by the filter, or 1476 * {@code false} if it is blocked. 1477 */ 1478 public boolean matchesInterruptionFilter() { 1479 return mMatchesInterruptionFilter; 1480 } 1481 1482 /** 1483 * Returns the importance of the notification, which dictates its 1484 * modes of presentation, see: {@link NotificationManager#IMPORTANCE_DEFAULT}, etc. 1485 * 1486 * @return the importance of the notification 1487 */ 1488 public @NotificationManager.Importance int getImportance() { 1489 return mImportance; 1490 } 1491 1492 /** 1493 * If the importance has been overridden by user preference, then this will be non-null, 1494 * and should be displayed to the user. 1495 * 1496 * @return the explanation for the importance, or null if it is the natural importance 1497 */ 1498 public CharSequence getImportanceExplanation() { 1499 return mImportanceExplanation; 1500 } 1501 1502 /** 1503 * If the system has overridden the group key, then this will be non-null, and this 1504 * key should be used to bundle notifications. 1505 */ 1506 public String getOverrideGroupKey() { 1507 return mOverrideGroupKey; 1508 } 1509 1510 /** 1511 * Returns the notification channel this notification was posted to, which dictates 1512 * notification behavior and presentation. 1513 */ 1514 public NotificationChannel getChannel() { 1515 return mChannel; 1516 } 1517 1518 /** 1519 * Returns how the system thinks the user feels about notifications from the 1520 * channel provided by {@link #getChannel()}. You can use this information to expose 1521 * controls to help the user block this channel's notifications, if the sentiment is 1522 * {@link #USER_SENTIMENT_NEGATIVE}, or emphasize this notification if the sentiment is 1523 * {@link #USER_SENTIMENT_POSITIVE}. 1524 */ 1525 public int getUserSentiment() { 1526 return mUserSentiment; 1527 } 1528 1529 /** 1530 * If the {@link NotificationAssistantService} has added people to this notification, then 1531 * this will be non-null. 1532 * @hide 1533 * @removed 1534 */ 1535 @SystemApi 1536 public List<String> getAdditionalPeople() { 1537 return mOverridePeople; 1538 } 1539 1540 /** 1541 * Returns snooze criteria provided by the {@link NotificationAssistantService}. If your 1542 * user interface displays options for snoozing notifications these criteria should be 1543 * displayed as well. 1544 * @hide 1545 * @removed 1546 */ 1547 @SystemApi 1548 public List<SnoozeCriterion> getSnoozeCriteria() { 1549 return mSnoozeCriteria; 1550 } 1551 1552 /** 1553 * Returns whether this notification can be displayed as a badge. 1554 * 1555 * @return true if the notification can be displayed as a badge, false otherwise. 1556 */ 1557 public boolean canShowBadge() { 1558 return mShowBadge; 1559 } 1560 1561 /** 1562 * Returns whether the app that posted this notification is suspended, so this notification 1563 * should be hidden. 1564 * 1565 * @return true if the notification should be hidden, false otherwise. 1566 */ 1567 public boolean isSuspended() { 1568 return mHidden; 1569 } 1570 1571 /** 1572 * @hide 1573 */ 1574 @VisibleForTesting 1575 public void populate(String key, int rank, boolean matchesInterruptionFilter, 1576 int visibilityOverride, int suppressedVisualEffects, int importance, 1577 CharSequence explanation, String overrideGroupKey, 1578 NotificationChannel channel, ArrayList<String> overridePeople, 1579 ArrayList<SnoozeCriterion> snoozeCriteria, boolean showBadge, 1580 int userSentiment, boolean hidden) { 1581 mKey = key; 1582 mRank = rank; 1583 mIsAmbient = importance < NotificationManager.IMPORTANCE_LOW; 1584 mMatchesInterruptionFilter = matchesInterruptionFilter; 1585 mVisibilityOverride = visibilityOverride; 1586 mSuppressedVisualEffects = suppressedVisualEffects; 1587 mImportance = importance; 1588 mImportanceExplanation = explanation; 1589 mOverrideGroupKey = overrideGroupKey; 1590 mChannel = channel; 1591 mOverridePeople = overridePeople; 1592 mSnoozeCriteria = snoozeCriteria; 1593 mShowBadge = showBadge; 1594 mUserSentiment = userSentiment; 1595 mHidden = hidden; 1596 } 1597 1598 /** 1599 * {@hide} 1600 */ 1601 public static String importanceToString(int importance) { 1602 switch (importance) { 1603 case NotificationManager.IMPORTANCE_UNSPECIFIED: 1604 return "UNSPECIFIED"; 1605 case NotificationManager.IMPORTANCE_NONE: 1606 return "NONE"; 1607 case NotificationManager.IMPORTANCE_MIN: 1608 return "MIN"; 1609 case NotificationManager.IMPORTANCE_LOW: 1610 return "LOW"; 1611 case NotificationManager.IMPORTANCE_DEFAULT: 1612 return "DEFAULT"; 1613 case NotificationManager.IMPORTANCE_HIGH: 1614 case NotificationManager.IMPORTANCE_MAX: 1615 return "HIGH"; 1616 default: 1617 return "UNKNOWN(" + String.valueOf(importance) + ")"; 1618 } 1619 } 1620 } 1621 1622 /** 1623 * Provides access to ranking information on currently active 1624 * notifications. 1625 * 1626 * <p> 1627 * Note that this object represents a ranking snapshot that only applies to 1628 * notifications active at the time of retrieval. 1629 */ 1630 public static class RankingMap implements Parcelable { 1631 private final NotificationRankingUpdate mRankingUpdate; 1632 private ArrayMap<String,Integer> mRanks; 1633 private ArraySet<Object> mIntercepted; 1634 private ArrayMap<String, Integer> mVisibilityOverrides; 1635 private ArrayMap<String, Integer> mSuppressedVisualEffects; 1636 private ArrayMap<String, Integer> mImportance; 1637 private ArrayMap<String, String> mImportanceExplanation; 1638 private ArrayMap<String, String> mOverrideGroupKeys; 1639 private ArrayMap<String, NotificationChannel> mChannels; 1640 private ArrayMap<String, ArrayList<String>> mOverridePeople; 1641 private ArrayMap<String, ArrayList<SnoozeCriterion>> mSnoozeCriteria; 1642 private ArrayMap<String, Boolean> mShowBadge; 1643 private ArrayMap<String, Integer> mUserSentiment; 1644 private ArrayMap<String, Boolean> mHidden; 1645 1646 private RankingMap(NotificationRankingUpdate rankingUpdate) { 1647 mRankingUpdate = rankingUpdate; 1648 } 1649 1650 /** 1651 * Request the list of notification keys in their current ranking 1652 * order. 1653 * 1654 * @return An array of active notification keys, in their ranking order. 1655 */ 1656 public String[] getOrderedKeys() { 1657 return mRankingUpdate.getOrderedKeys(); 1658 } 1659 1660 /** 1661 * Populates outRanking with ranking information for the notification 1662 * with the given key. 1663 * 1664 * @return true if a valid key has been passed and outRanking has 1665 * been populated; false otherwise 1666 */ 1667 public boolean getRanking(String key, Ranking outRanking) { 1668 int rank = getRank(key); 1669 outRanking.populate(key, rank, !isIntercepted(key), 1670 getVisibilityOverride(key), getSuppressedVisualEffects(key), 1671 getImportance(key), getImportanceExplanation(key), getOverrideGroupKey(key), 1672 getChannel(key), getOverridePeople(key), getSnoozeCriteria(key), 1673 getShowBadge(key), getUserSentiment(key), getHidden(key)); 1674 return rank >= 0; 1675 } 1676 1677 private int getRank(String key) { 1678 synchronized (this) { 1679 if (mRanks == null) { 1680 buildRanksLocked(); 1681 } 1682 } 1683 Integer rank = mRanks.get(key); 1684 return rank != null ? rank : -1; 1685 } 1686 1687 private boolean isIntercepted(String key) { 1688 synchronized (this) { 1689 if (mIntercepted == null) { 1690 buildInterceptedSetLocked(); 1691 } 1692 } 1693 return mIntercepted.contains(key); 1694 } 1695 1696 private int getVisibilityOverride(String key) { 1697 synchronized (this) { 1698 if (mVisibilityOverrides == null) { 1699 buildVisibilityOverridesLocked(); 1700 } 1701 } 1702 Integer override = mVisibilityOverrides.get(key); 1703 if (override == null) { 1704 return Ranking.VISIBILITY_NO_OVERRIDE; 1705 } 1706 return override.intValue(); 1707 } 1708 1709 private int getSuppressedVisualEffects(String key) { 1710 synchronized (this) { 1711 if (mSuppressedVisualEffects == null) { 1712 buildSuppressedVisualEffectsLocked(); 1713 } 1714 } 1715 Integer suppressed = mSuppressedVisualEffects.get(key); 1716 if (suppressed == null) { 1717 return 0; 1718 } 1719 return suppressed.intValue(); 1720 } 1721 1722 private int getImportance(String key) { 1723 synchronized (this) { 1724 if (mImportance == null) { 1725 buildImportanceLocked(); 1726 } 1727 } 1728 Integer importance = mImportance.get(key); 1729 if (importance == null) { 1730 return NotificationManager.IMPORTANCE_DEFAULT; 1731 } 1732 return importance.intValue(); 1733 } 1734 1735 private String getImportanceExplanation(String key) { 1736 synchronized (this) { 1737 if (mImportanceExplanation == null) { 1738 buildImportanceExplanationLocked(); 1739 } 1740 } 1741 return mImportanceExplanation.get(key); 1742 } 1743 1744 private String getOverrideGroupKey(String key) { 1745 synchronized (this) { 1746 if (mOverrideGroupKeys == null) { 1747 buildOverrideGroupKeys(); 1748 } 1749 } 1750 return mOverrideGroupKeys.get(key); 1751 } 1752 1753 private NotificationChannel getChannel(String key) { 1754 synchronized (this) { 1755 if (mChannels == null) { 1756 buildChannelsLocked(); 1757 } 1758 } 1759 return mChannels.get(key); 1760 } 1761 1762 private ArrayList<String> getOverridePeople(String key) { 1763 synchronized (this) { 1764 if (mOverridePeople == null) { 1765 buildOverridePeopleLocked(); 1766 } 1767 } 1768 return mOverridePeople.get(key); 1769 } 1770 1771 private ArrayList<SnoozeCriterion> getSnoozeCriteria(String key) { 1772 synchronized (this) { 1773 if (mSnoozeCriteria == null) { 1774 buildSnoozeCriteriaLocked(); 1775 } 1776 } 1777 return mSnoozeCriteria.get(key); 1778 } 1779 1780 private boolean getShowBadge(String key) { 1781 synchronized (this) { 1782 if (mShowBadge == null) { 1783 buildShowBadgeLocked(); 1784 } 1785 } 1786 Boolean showBadge = mShowBadge.get(key); 1787 return showBadge == null ? false : showBadge.booleanValue(); 1788 } 1789 1790 private int getUserSentiment(String key) { 1791 synchronized (this) { 1792 if (mUserSentiment == null) { 1793 buildUserSentimentLocked(); 1794 } 1795 } 1796 Integer userSentiment = mUserSentiment.get(key); 1797 return userSentiment == null 1798 ? Ranking.USER_SENTIMENT_NEUTRAL : userSentiment.intValue(); 1799 } 1800 1801 private boolean getHidden(String key) { 1802 synchronized (this) { 1803 if (mHidden == null) { 1804 buildHiddenLocked(); 1805 } 1806 } 1807 Boolean hidden = mHidden.get(key); 1808 return hidden == null ? false : hidden.booleanValue(); 1809 } 1810 1811 // Locked by 'this' 1812 private void buildRanksLocked() { 1813 String[] orderedKeys = mRankingUpdate.getOrderedKeys(); 1814 mRanks = new ArrayMap<>(orderedKeys.length); 1815 for (int i = 0; i < orderedKeys.length; i++) { 1816 String key = orderedKeys[i]; 1817 mRanks.put(key, i); 1818 } 1819 } 1820 1821 // Locked by 'this' 1822 private void buildInterceptedSetLocked() { 1823 String[] dndInterceptedKeys = mRankingUpdate.getInterceptedKeys(); 1824 mIntercepted = new ArraySet<>(dndInterceptedKeys.length); 1825 Collections.addAll(mIntercepted, dndInterceptedKeys); 1826 } 1827 1828 // Locked by 'this' 1829 private void buildVisibilityOverridesLocked() { 1830 Bundle visibilityBundle = mRankingUpdate.getVisibilityOverrides(); 1831 mVisibilityOverrides = new ArrayMap<>(visibilityBundle.size()); 1832 for (String key: visibilityBundle.keySet()) { 1833 mVisibilityOverrides.put(key, visibilityBundle.getInt(key)); 1834 } 1835 } 1836 1837 // Locked by 'this' 1838 private void buildSuppressedVisualEffectsLocked() { 1839 Bundle suppressedBundle = mRankingUpdate.getSuppressedVisualEffects(); 1840 mSuppressedVisualEffects = new ArrayMap<>(suppressedBundle.size()); 1841 for (String key: suppressedBundle.keySet()) { 1842 mSuppressedVisualEffects.put(key, suppressedBundle.getInt(key)); 1843 } 1844 } 1845 // Locked by 'this' 1846 private void buildImportanceLocked() { 1847 String[] orderedKeys = mRankingUpdate.getOrderedKeys(); 1848 int[] importance = mRankingUpdate.getImportance(); 1849 mImportance = new ArrayMap<>(orderedKeys.length); 1850 for (int i = 0; i < orderedKeys.length; i++) { 1851 String key = orderedKeys[i]; 1852 mImportance.put(key, importance[i]); 1853 } 1854 } 1855 1856 // Locked by 'this' 1857 private void buildImportanceExplanationLocked() { 1858 Bundle explanationBundle = mRankingUpdate.getImportanceExplanation(); 1859 mImportanceExplanation = new ArrayMap<>(explanationBundle.size()); 1860 for (String key: explanationBundle.keySet()) { 1861 mImportanceExplanation.put(key, explanationBundle.getString(key)); 1862 } 1863 } 1864 1865 // Locked by 'this' 1866 private void buildOverrideGroupKeys() { 1867 Bundle overrideGroupKeys = mRankingUpdate.getOverrideGroupKeys(); 1868 mOverrideGroupKeys = new ArrayMap<>(overrideGroupKeys.size()); 1869 for (String key: overrideGroupKeys.keySet()) { 1870 mOverrideGroupKeys.put(key, overrideGroupKeys.getString(key)); 1871 } 1872 } 1873 1874 // Locked by 'this' 1875 private void buildChannelsLocked() { 1876 Bundle channels = mRankingUpdate.getChannels(); 1877 mChannels = new ArrayMap<>(channels.size()); 1878 for (String key : channels.keySet()) { 1879 mChannels.put(key, channels.getParcelable(key)); 1880 } 1881 } 1882 1883 // Locked by 'this' 1884 private void buildOverridePeopleLocked() { 1885 Bundle overridePeople = mRankingUpdate.getOverridePeople(); 1886 mOverridePeople = new ArrayMap<>(overridePeople.size()); 1887 for (String key : overridePeople.keySet()) { 1888 mOverridePeople.put(key, overridePeople.getStringArrayList(key)); 1889 } 1890 } 1891 1892 // Locked by 'this' 1893 private void buildSnoozeCriteriaLocked() { 1894 Bundle snoozeCriteria = mRankingUpdate.getSnoozeCriteria(); 1895 mSnoozeCriteria = new ArrayMap<>(snoozeCriteria.size()); 1896 for (String key : snoozeCriteria.keySet()) { 1897 mSnoozeCriteria.put(key, snoozeCriteria.getParcelableArrayList(key)); 1898 } 1899 } 1900 1901 // Locked by 'this' 1902 private void buildShowBadgeLocked() { 1903 Bundle showBadge = mRankingUpdate.getShowBadge(); 1904 mShowBadge = new ArrayMap<>(showBadge.size()); 1905 for (String key : showBadge.keySet()) { 1906 mShowBadge.put(key, showBadge.getBoolean(key)); 1907 } 1908 } 1909 1910 // Locked by 'this' 1911 private void buildUserSentimentLocked() { 1912 Bundle userSentiment = mRankingUpdate.getUserSentiment(); 1913 mUserSentiment = new ArrayMap<>(userSentiment.size()); 1914 for (String key : userSentiment.keySet()) { 1915 mUserSentiment.put(key, userSentiment.getInt(key)); 1916 } 1917 } 1918 1919 // Locked by 'this' 1920 private void buildHiddenLocked() { 1921 Bundle hidden = mRankingUpdate.getHidden(); 1922 mHidden = new ArrayMap<>(hidden.size()); 1923 for (String key : hidden.keySet()) { 1924 mHidden.put(key, hidden.getBoolean(key)); 1925 } 1926 } 1927 1928 // ----------- Parcelable 1929 1930 @Override 1931 public int describeContents() { 1932 return 0; 1933 } 1934 1935 @Override 1936 public void writeToParcel(Parcel dest, int flags) { 1937 dest.writeParcelable(mRankingUpdate, flags); 1938 } 1939 1940 public static final Creator<RankingMap> CREATOR = new Creator<RankingMap>() { 1941 @Override 1942 public RankingMap createFromParcel(Parcel source) { 1943 NotificationRankingUpdate rankingUpdate = source.readParcelable(null); 1944 return new RankingMap(rankingUpdate); 1945 } 1946 1947 @Override 1948 public RankingMap[] newArray(int size) { 1949 return new RankingMap[size]; 1950 } 1951 }; 1952 } 1953 1954 private final class MyHandler extends Handler { 1955 public static final int MSG_ON_NOTIFICATION_POSTED = 1; 1956 public static final int MSG_ON_NOTIFICATION_REMOVED = 2; 1957 public static final int MSG_ON_LISTENER_CONNECTED = 3; 1958 public static final int MSG_ON_NOTIFICATION_RANKING_UPDATE = 4; 1959 public static final int MSG_ON_LISTENER_HINTS_CHANGED = 5; 1960 public static final int MSG_ON_INTERRUPTION_FILTER_CHANGED = 6; 1961 public static final int MSG_ON_NOTIFICATION_CHANNEL_MODIFIED = 7; 1962 public static final int MSG_ON_NOTIFICATION_CHANNEL_GROUP_MODIFIED = 8; 1963 1964 public MyHandler(Looper looper) { 1965 super(looper, null, false); 1966 } 1967 1968 @Override 1969 public void handleMessage(Message msg) { 1970 if (!isConnected) { 1971 return; 1972 } 1973 switch (msg.what) { 1974 case MSG_ON_NOTIFICATION_POSTED: { 1975 SomeArgs args = (SomeArgs) msg.obj; 1976 StatusBarNotification sbn = (StatusBarNotification) args.arg1; 1977 RankingMap rankingMap = (RankingMap) args.arg2; 1978 args.recycle(); 1979 onNotificationPosted(sbn, rankingMap); 1980 } break; 1981 1982 case MSG_ON_NOTIFICATION_REMOVED: { 1983 SomeArgs args = (SomeArgs) msg.obj; 1984 StatusBarNotification sbn = (StatusBarNotification) args.arg1; 1985 RankingMap rankingMap = (RankingMap) args.arg2; 1986 int reason = (int) args.arg3; 1987 NotificationStats stats = (NotificationStats) args.arg4; 1988 args.recycle(); 1989 onNotificationRemoved(sbn, rankingMap, stats, reason); 1990 } break; 1991 1992 case MSG_ON_LISTENER_CONNECTED: { 1993 onListenerConnected(); 1994 } break; 1995 1996 case MSG_ON_NOTIFICATION_RANKING_UPDATE: { 1997 RankingMap rankingMap = (RankingMap) msg.obj; 1998 onNotificationRankingUpdate(rankingMap); 1999 } break; 2000 2001 case MSG_ON_LISTENER_HINTS_CHANGED: { 2002 final int hints = msg.arg1; 2003 onListenerHintsChanged(hints); 2004 } break; 2005 2006 case MSG_ON_INTERRUPTION_FILTER_CHANGED: { 2007 final int interruptionFilter = msg.arg1; 2008 onInterruptionFilterChanged(interruptionFilter); 2009 } break; 2010 2011 case MSG_ON_NOTIFICATION_CHANNEL_MODIFIED: { 2012 SomeArgs args = (SomeArgs) msg.obj; 2013 String pkgName = (String) args.arg1; 2014 UserHandle user= (UserHandle) args.arg2; 2015 NotificationChannel channel = (NotificationChannel) args.arg3; 2016 int modificationType = (int) args.arg4; 2017 onNotificationChannelModified(pkgName, user, channel, modificationType); 2018 } break; 2019 2020 case MSG_ON_NOTIFICATION_CHANNEL_GROUP_MODIFIED: { 2021 SomeArgs args = (SomeArgs) msg.obj; 2022 String pkgName = (String) args.arg1; 2023 UserHandle user = (UserHandle) args.arg2; 2024 NotificationChannelGroup group = (NotificationChannelGroup) args.arg3; 2025 int modificationType = (int) args.arg4; 2026 onNotificationChannelGroupModified(pkgName, user, group, modificationType); 2027 } break; 2028 } 2029 } 2030 } 2031} 2032