NotificationListenerService.java revision 1fc476d51203c0b76ebd0f2062adf3059437b0dc
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.SystemApi; 20import android.annotation.SdkConstant; 21import android.app.INotificationManager; 22import android.app.Notification; 23import android.app.Notification.Builder; 24import android.app.NotificationManager.Policy; 25import android.app.Service; 26import android.content.ComponentName; 27import android.content.Context; 28import android.content.Intent; 29import android.content.pm.ParceledListSlice; 30import android.os.Bundle; 31import android.os.IBinder; 32import android.os.Parcel; 33import android.os.Parcelable; 34import android.os.RemoteException; 35import android.os.ServiceManager; 36import android.util.ArrayMap; 37import android.util.ArraySet; 38import android.util.Log; 39 40import java.util.Collections; 41import java.util.List; 42 43/** 44 * A service that receives calls from the system when new notifications are 45 * posted or removed, or their ranking changed. 46 * <p>To extend this class, you must declare the service in your manifest file with 47 * the {@link android.Manifest.permission#BIND_NOTIFICATION_LISTENER_SERVICE} permission 48 * and include an intent filter with the {@link #SERVICE_INTERFACE} action. For example:</p> 49 * <pre> 50 * <service android:name=".NotificationListener" 51 * android:label="@string/service_name" 52 * android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"> 53 * <intent-filter> 54 * <action android:name="android.service.notification.NotificationListenerService" /> 55 * </intent-filter> 56 * </service></pre> 57 */ 58public abstract class NotificationListenerService extends Service { 59 // TAG = "NotificationListenerService[MySubclass]" 60 private final String TAG = NotificationListenerService.class.getSimpleName() 61 + "[" + getClass().getSimpleName() + "]"; 62 63 /** 64 * {@link #getCurrentInterruptionFilter() Interruption filter} constant - 65 * Normal interruption filter. 66 */ 67 public static final int INTERRUPTION_FILTER_ALL = 1; 68 69 /** 70 * {@link #getCurrentInterruptionFilter() Interruption filter} constant - 71 * Priority interruption filter. 72 */ 73 public static final int INTERRUPTION_FILTER_PRIORITY = 2; 74 75 /** 76 * {@link #getCurrentInterruptionFilter() Interruption filter} constant - 77 * No interruptions filter. 78 */ 79 public static final int INTERRUPTION_FILTER_NONE = 3; 80 81 /** 82 * {@link #getCurrentInterruptionFilter() Interruption filter} constant - 83 * Alarms only interruption filter. 84 */ 85 public static final int INTERRUPTION_FILTER_ALARMS = 4; 86 87 /** {@link #getCurrentInterruptionFilter() Interruption filter} constant - returned when 88 * the value is unavailable for any reason. For example, before the notification listener 89 * is connected. 90 * 91 * {@see #onListenerConnected()} 92 */ 93 public static final int INTERRUPTION_FILTER_UNKNOWN = 0; 94 95 /** {@link #getCurrentListenerHints() Listener hints} constant - the primary device UI 96 * should disable notification sound, vibrating and other visual or aural effects. 97 * This does not change the interruption filter, only the effects. **/ 98 public static final int HINT_HOST_DISABLE_EFFECTS = 1; 99 100 /** 101 * The full trim of the StatusBarNotification including all its features. 102 * 103 * @hide 104 */ 105 @SystemApi 106 public static final int TRIM_FULL = 0; 107 108 /** 109 * A light trim of the StatusBarNotification excluding the following features: 110 * 111 * <ol> 112 * <li>{@link Notification#tickerView tickerView}</li> 113 * <li>{@link Notification#contentView contentView}</li> 114 * <li>{@link Notification#largeIcon largeIcon}</li> 115 * <li>{@link Notification#bigContentView bigContentView}</li> 116 * <li>{@link Notification#headsUpContentView headsUpContentView}</li> 117 * <li>{@link Notification#EXTRA_LARGE_ICON extras[EXTRA_LARGE_ICON]}</li> 118 * <li>{@link Notification#EXTRA_LARGE_ICON_BIG extras[EXTRA_LARGE_ICON_BIG]}</li> 119 * <li>{@link Notification#EXTRA_PICTURE extras[EXTRA_PICTURE]}</li> 120 * <li>{@link Notification#EXTRA_BIG_TEXT extras[EXTRA_BIG_TEXT]}</li> 121 * </ol> 122 * 123 * @hide 124 */ 125 @SystemApi 126 public static final int TRIM_LIGHT = 1; 127 128 private INotificationListenerWrapper mWrapper = null; 129 private RankingMap mRankingMap; 130 131 private INotificationManager mNoMan; 132 133 /** Only valid after a successful call to (@link registerAsService}. */ 134 private int mCurrentUser; 135 136 137 // This context is required for system services since NotificationListenerService isn't 138 // started as a real Service and hence no context is available. 139 private Context mSystemContext; 140 141 /** 142 * The {@link Intent} that must be declared as handled by the service. 143 */ 144 @SdkConstant(SdkConstant.SdkConstantType.SERVICE_ACTION) 145 public static final String SERVICE_INTERFACE 146 = "android.service.notification.NotificationListenerService"; 147 148 /** 149 * Implement this method to learn about new notifications as they are posted by apps. 150 * 151 * @param sbn A data structure encapsulating the original {@link android.app.Notification} 152 * object as well as its identifying information (tag and id) and source 153 * (package name). 154 */ 155 public void onNotificationPosted(StatusBarNotification sbn) { 156 // optional 157 } 158 159 /** 160 * Implement this method to learn about new notifications as they are posted by apps. 161 * 162 * @param sbn A data structure encapsulating the original {@link android.app.Notification} 163 * object as well as its identifying information (tag and id) and source 164 * (package name). 165 * @param rankingMap The current ranking map that can be used to retrieve ranking information 166 * for active notifications, including the newly posted one. 167 */ 168 public void onNotificationPosted(StatusBarNotification sbn, RankingMap rankingMap) { 169 onNotificationPosted(sbn); 170 } 171 172 /** 173 * Implement this method to learn when notifications are removed. 174 * <P> 175 * This might occur because the user has dismissed the notification using system UI (or another 176 * notification listener) or because the app has withdrawn the notification. 177 * <P> 178 * NOTE: The {@link StatusBarNotification} object you receive will be "light"; that is, the 179 * result from {@link StatusBarNotification#getNotification} may be missing some heavyweight 180 * fields such as {@link android.app.Notification#contentView} and 181 * {@link android.app.Notification#largeIcon}. However, all other fields on 182 * {@link StatusBarNotification}, sufficient to match this call with a prior call to 183 * {@link #onNotificationPosted(StatusBarNotification)}, will be intact. 184 * 185 * @param sbn A data structure encapsulating at least the original information (tag and id) 186 * and source (package name) used to post the {@link android.app.Notification} that 187 * was just removed. 188 */ 189 public void onNotificationRemoved(StatusBarNotification sbn) { 190 // optional 191 } 192 193 /** 194 * Implement this method to learn when notifications are removed. 195 * <P> 196 * This might occur because the user has dismissed the notification using system UI (or another 197 * notification listener) or because the app has withdrawn the notification. 198 * <P> 199 * NOTE: The {@link StatusBarNotification} object you receive will be "light"; that is, the 200 * result from {@link StatusBarNotification#getNotification} may be missing some heavyweight 201 * fields such as {@link android.app.Notification#contentView} and 202 * {@link android.app.Notification#largeIcon}. However, all other fields on 203 * {@link StatusBarNotification}, sufficient to match this call with a prior call to 204 * {@link #onNotificationPosted(StatusBarNotification)}, will be intact. 205 * 206 * @param sbn A data structure encapsulating at least the original information (tag and id) 207 * and source (package name) used to post the {@link android.app.Notification} that 208 * was just removed. 209 * @param rankingMap The current ranking map that can be used to retrieve ranking information 210 * for active notifications. 211 * 212 */ 213 public void onNotificationRemoved(StatusBarNotification sbn, RankingMap rankingMap) { 214 onNotificationRemoved(sbn); 215 } 216 217 /** 218 * Implement this method to learn about when the listener is enabled and connected to 219 * the notification manager. You are safe to call {@link #getActiveNotifications()} 220 * at this time. 221 */ 222 public void onListenerConnected() { 223 // optional 224 } 225 226 /** 227 * Implement this method to be notified when the notification ranking changes. 228 * 229 * @param rankingMap The current ranking map that can be used to retrieve ranking information 230 * for active notifications. 231 */ 232 public void onNotificationRankingUpdate(RankingMap rankingMap) { 233 // optional 234 } 235 236 /** 237 * Implement this method to be notified when the 238 * {@link #getCurrentListenerHints() Listener hints} change. 239 * 240 * @param hints The current {@link #getCurrentListenerHints() listener hints}. 241 */ 242 public void onListenerHintsChanged(int hints) { 243 // optional 244 } 245 246 /** 247 * Implement this method to be notified when the 248 * {@link #getCurrentInterruptionFilter() interruption filter} changed. 249 * 250 * @param interruptionFilter The current 251 * {@link #getCurrentInterruptionFilter() interruption filter}. 252 */ 253 public void onInterruptionFilterChanged(int interruptionFilter) { 254 // optional 255 } 256 257 private final INotificationManager getNotificationInterface() { 258 if (mNoMan == null) { 259 mNoMan = INotificationManager.Stub.asInterface( 260 ServiceManager.getService(Context.NOTIFICATION_SERVICE)); 261 } 262 return mNoMan; 263 } 264 265 /** 266 * Inform the notification manager about dismissal of a single notification. 267 * <p> 268 * Use this if your listener has a user interface that allows the user to dismiss individual 269 * notifications, similar to the behavior of Android's status bar and notification panel. 270 * It should be called after the user dismisses a single notification using your UI; 271 * upon being informed, the notification manager will actually remove the notification 272 * and you will get an {@link #onNotificationRemoved(StatusBarNotification)} callback. 273 * <P> 274 * <b>Note:</b> If your listener allows the user to fire a notification's 275 * {@link android.app.Notification#contentIntent} by tapping/clicking/etc., you should call 276 * this method at that time <i>if</i> the Notification in question has the 277 * {@link android.app.Notification#FLAG_AUTO_CANCEL} flag set. 278 * 279 * @param pkg Package of the notifying app. 280 * @param tag Tag of the notification as specified by the notifying app in 281 * {@link android.app.NotificationManager#notify(String, int, android.app.Notification)}. 282 * @param id ID of the notification as specified by the notifying app in 283 * {@link android.app.NotificationManager#notify(String, int, android.app.Notification)}. 284 * <p> 285 * @deprecated Use {@link #cancelNotification(String key)} 286 * instead. Beginning with {@link android.os.Build.VERSION_CODES#LOLLIPOP} this method will no longer 287 * cancel the notification. It will continue to cancel the notification for applications 288 * whose {@code targetSdkVersion} is earlier than {@link android.os.Build.VERSION_CODES#LOLLIPOP}. 289 */ 290 public final void cancelNotification(String pkg, String tag, int id) { 291 if (!isBound()) return; 292 try { 293 getNotificationInterface().cancelNotificationFromListener( 294 mWrapper, pkg, tag, id); 295 } catch (android.os.RemoteException ex) { 296 Log.v(TAG, "Unable to contact notification manager", ex); 297 } 298 } 299 300 /** 301 * Inform the notification manager about dismissal of a single notification. 302 * <p> 303 * Use this if your listener has a user interface that allows the user to dismiss individual 304 * notifications, similar to the behavior of Android's status bar and notification panel. 305 * It should be called after the user dismisses a single notification using your UI; 306 * upon being informed, the notification manager will actually remove the notification 307 * and you will get an {@link #onNotificationRemoved(StatusBarNotification)} callback. 308 * <P> 309 * <b>Note:</b> If your listener allows the user to fire a notification's 310 * {@link android.app.Notification#contentIntent} by tapping/clicking/etc., you should call 311 * this method at that time <i>if</i> the Notification in question has the 312 * {@link android.app.Notification#FLAG_AUTO_CANCEL} flag set. 313 * <p> 314 * @param key Notification to dismiss from {@link StatusBarNotification#getKey()}. 315 */ 316 public final void cancelNotification(String key) { 317 if (!isBound()) return; 318 try { 319 getNotificationInterface().cancelNotificationsFromListener(mWrapper, 320 new String[] {key}); 321 } catch (android.os.RemoteException ex) { 322 Log.v(TAG, "Unable to contact notification manager", ex); 323 } 324 } 325 326 /** 327 * Inform the notification manager about dismissal of all notifications. 328 * <p> 329 * Use this if your listener has a user interface that allows the user to dismiss all 330 * notifications, similar to the behavior of Android's status bar and notification panel. 331 * It should be called after the user invokes the "dismiss all" function of your UI; 332 * upon being informed, the notification manager will actually remove all active notifications 333 * and you will get multiple {@link #onNotificationRemoved(StatusBarNotification)} callbacks. 334 * 335 * {@see #cancelNotification(String, String, int)} 336 */ 337 public final void cancelAllNotifications() { 338 cancelNotifications(null /*all*/); 339 } 340 341 /** 342 * Inform the notification manager about dismissal of specific notifications. 343 * <p> 344 * Use this if your listener has a user interface that allows the user to dismiss 345 * multiple notifications at once. 346 * 347 * @param keys Notifications to dismiss, or {@code null} to dismiss all. 348 * 349 * {@see #cancelNotification(String, String, int)} 350 */ 351 public final void cancelNotifications(String[] keys) { 352 if (!isBound()) return; 353 try { 354 getNotificationInterface().cancelNotificationsFromListener(mWrapper, keys); 355 } catch (android.os.RemoteException ex) { 356 Log.v(TAG, "Unable to contact notification manager", ex); 357 } 358 } 359 360 /** 361 * Sets the notification trim that will be received via {@link #onNotificationPosted}. 362 * 363 * <p> 364 * Setting a trim other than {@link #TRIM_FULL} enables listeners that don't need access to the 365 * full notification features right away to reduce their memory footprint. Full notifications 366 * can be requested on-demand via {@link #getActiveNotifications(int)}. 367 * 368 * <p> 369 * Set to {@link #TRIM_FULL} initially. 370 * 371 * @hide 372 * 373 * @param trim trim of the notifications to be passed via {@link #onNotificationPosted}. 374 * See <code>TRIM_*</code> constants. 375 */ 376 @SystemApi 377 public final void setOnNotificationPostedTrim(int trim) { 378 if (!isBound()) return; 379 try { 380 getNotificationInterface().setOnNotificationPostedTrimFromListener(mWrapper, trim); 381 } catch (RemoteException ex) { 382 Log.v(TAG, "Unable to contact notification manager", ex); 383 } 384 } 385 386 /** 387 * Request the list of outstanding notifications (that is, those that are visible to the 388 * current user). Useful when you don't know what's already been posted. 389 * 390 * @return An array of active notifications, sorted in natural order. 391 */ 392 public StatusBarNotification[] getActiveNotifications() { 393 return getActiveNotifications(null, TRIM_FULL); 394 } 395 396 /** 397 * Request the list of outstanding notifications (that is, those that are visible to the 398 * current user). Useful when you don't know what's already been posted. 399 * 400 * @hide 401 * 402 * @param trim trim of the notifications to be returned. See <code>TRIM_*</code> constants. 403 * @return An array of active notifications, sorted in natural order. 404 */ 405 @SystemApi 406 public StatusBarNotification[] getActiveNotifications(int trim) { 407 return getActiveNotifications(null, trim); 408 } 409 410 /** 411 * Request one or more notifications by key. Useful if you have been keeping track of 412 * notifications but didn't want to retain the bits, and now need to go back and extract 413 * more data out of those notifications. 414 * 415 * @param keys the keys of the notifications to request 416 * @return An array of notifications corresponding to the requested keys, in the 417 * same order as the key list. 418 */ 419 public StatusBarNotification[] getActiveNotifications(String[] keys) { 420 return getActiveNotifications(keys, TRIM_FULL); 421 } 422 423 /** 424 * Request one or more notifications by key. Useful if you have been keeping track of 425 * notifications but didn't want to retain the bits, and now need to go back and extract 426 * more data out of those notifications. 427 * 428 * @hide 429 * 430 * @param keys the keys of the notifications to request 431 * @param trim trim of the notifications to be returned. See <code>TRIM_*</code> constants. 432 * @return An array of notifications corresponding to the requested keys, in the 433 * same order as the key list. 434 */ 435 @SystemApi 436 public StatusBarNotification[] getActiveNotifications(String[] keys, int trim) { 437 if (!isBound()) 438 return null; 439 try { 440 ParceledListSlice<StatusBarNotification> parceledList = getNotificationInterface() 441 .getActiveNotificationsFromListener(mWrapper, keys, trim); 442 List<StatusBarNotification> list = parceledList.getList(); 443 444 int N = list.size(); 445 for (int i = 0; i < N; i++) { 446 Notification notification = list.get(i).getNotification(); 447 Builder.rebuild(getContext(), notification); 448 } 449 return list.toArray(new StatusBarNotification[N]); 450 } catch (android.os.RemoteException ex) { 451 Log.v(TAG, "Unable to contact notification manager", ex); 452 } 453 return null; 454 } 455 456 /** 457 * Gets the set of hints representing current state. 458 * 459 * <p> 460 * The current state may differ from the requested state if the hint represents state 461 * shared across all listeners or a feature the notification host does not support or refuses 462 * to grant. 463 * 464 * @return Zero or more of the HINT_ constants. 465 */ 466 public final int getCurrentListenerHints() { 467 if (!isBound()) return 0; 468 try { 469 return getNotificationInterface().getHintsFromListener(mWrapper); 470 } catch (android.os.RemoteException ex) { 471 Log.v(TAG, "Unable to contact notification manager", ex); 472 return 0; 473 } 474 } 475 476 /** 477 * Gets the current notification interruption filter active on the host. 478 * 479 * <p> 480 * The interruption filter defines which notifications are allowed to interrupt the user 481 * (e.g. via sound & vibration) and is applied globally. Listeners can find out whether 482 * a specific notification matched the interruption filter via 483 * {@link Ranking#matchesInterruptionFilter()}. 484 * <p> 485 * The current filter may differ from the previously requested filter if the notification host 486 * does not support or refuses to apply the requested filter, or if another component changed 487 * the filter in the meantime. 488 * <p> 489 * Listen for updates using {@link #onInterruptionFilterChanged(int)}. 490 * 491 * @return One of the INTERRUPTION_FILTER_ constants, or INTERRUPTION_FILTER_UNKNOWN when 492 * unavailable. 493 */ 494 public final int getCurrentInterruptionFilter() { 495 if (!isBound()) return INTERRUPTION_FILTER_UNKNOWN; 496 try { 497 return getNotificationInterface().getInterruptionFilterFromListener(mWrapper); 498 } catch (android.os.RemoteException ex) { 499 Log.v(TAG, "Unable to contact notification manager", ex); 500 return INTERRUPTION_FILTER_UNKNOWN; 501 } 502 } 503 504 /** 505 * Gets the notification policy token associated with this listener. 506 * 507 * <p> 508 * Returns null if this listener is not currently active. 509 */ 510 public final Policy.Token getNotificationPolicyToken() { 511 if (!isBound()) return null; 512 try { 513 return getNotificationInterface().getPolicyTokenFromListener(mWrapper); 514 } catch (android.os.RemoteException ex) { 515 Log.v(TAG, "Unable to contact notification manager", ex); 516 return null; 517 } 518 } 519 520 /** 521 * Sets the desired {@link #getCurrentListenerHints() listener hints}. 522 * 523 * <p> 524 * This is merely a request, the host may or may not choose to take action depending 525 * on other listener requests or other global state. 526 * <p> 527 * Listen for updates using {@link #onListenerHintsChanged(int)}. 528 * 529 * @param hints One or more of the HINT_ constants. 530 */ 531 public final void requestListenerHints(int hints) { 532 if (!isBound()) return; 533 try { 534 getNotificationInterface().requestHintsFromListener(mWrapper, hints); 535 } catch (android.os.RemoteException ex) { 536 Log.v(TAG, "Unable to contact notification manager", ex); 537 } 538 } 539 540 /** 541 * Sets the desired {@link #getCurrentInterruptionFilter() interruption filter}. 542 * 543 * <p> 544 * This is merely a request, the host may or may not choose to apply the requested 545 * interruption filter depending on other listener requests or other global state. 546 * <p> 547 * Listen for updates using {@link #onInterruptionFilterChanged(int)}. 548 * 549 * @param interruptionFilter One of the INTERRUPTION_FILTER_ constants. 550 */ 551 public final void requestInterruptionFilter(int interruptionFilter) { 552 if (!isBound()) return; 553 try { 554 getNotificationInterface() 555 .requestInterruptionFilterFromListener(mWrapper, interruptionFilter); 556 } catch (android.os.RemoteException ex) { 557 Log.v(TAG, "Unable to contact notification manager", ex); 558 } 559 } 560 561 /** 562 * Returns current ranking information. 563 * 564 * <p> 565 * The returned object represents the current ranking snapshot and only 566 * applies for currently active notifications. 567 * <p> 568 * Generally you should use the RankingMap that is passed with events such 569 * as {@link #onNotificationPosted(StatusBarNotification, RankingMap)}, 570 * {@link #onNotificationRemoved(StatusBarNotification, RankingMap)}, and 571 * so on. This method should only be used when needing access outside of 572 * such events, for example to retrieve the RankingMap right after 573 * initialization. 574 * 575 * @return A {@link RankingMap} object providing access to ranking information 576 */ 577 public RankingMap getCurrentRanking() { 578 return mRankingMap; 579 } 580 581 @Override 582 public IBinder onBind(Intent intent) { 583 if (mWrapper == null) { 584 mWrapper = new INotificationListenerWrapper(); 585 } 586 return mWrapper; 587 } 588 589 private boolean isBound() { 590 if (mWrapper == null) { 591 Log.w(TAG, "Notification listener service not yet bound."); 592 return false; 593 } 594 return true; 595 } 596 597 /** 598 * Directly register this service with the Notification Manager. 599 * 600 * <p>Only system services may use this call. It will fail for non-system callers. 601 * Apps should ask the user to add their listener in Settings. 602 * 603 * @param context Context required for accessing resources. Since this service isn't 604 * launched as a real Service when using this method, a context has to be passed in. 605 * @param componentName the component that will consume the notification information 606 * @param currentUser the user to use as the stream filter 607 * @hide 608 */ 609 @SystemApi 610 public void registerAsSystemService(Context context, ComponentName componentName, 611 int currentUser) throws RemoteException { 612 mSystemContext = context; 613 if (mWrapper == null) { 614 mWrapper = new INotificationListenerWrapper(); 615 } 616 INotificationManager noMan = getNotificationInterface(); 617 noMan.registerListener(mWrapper, componentName, currentUser); 618 mCurrentUser = currentUser; 619 } 620 621 /** 622 * Directly unregister this service from the Notification Manager. 623 * 624 * <P>This method will fail for listeners that were not registered 625 * with (@link registerAsService). 626 * @hide 627 */ 628 @SystemApi 629 public void unregisterAsSystemService() throws RemoteException { 630 if (mWrapper != null) { 631 INotificationManager noMan = getNotificationInterface(); 632 noMan.unregisterListener(mWrapper, mCurrentUser); 633 } 634 } 635 636 private class INotificationListenerWrapper extends INotificationListener.Stub { 637 @Override 638 public void onNotificationPosted(IStatusBarNotificationHolder sbnHolder, 639 NotificationRankingUpdate update) { 640 StatusBarNotification sbn; 641 try { 642 sbn = sbnHolder.get(); 643 } catch (RemoteException e) { 644 Log.w(TAG, "onNotificationPosted: Error receiving StatusBarNotification", e); 645 return; 646 } 647 Notification.Builder.rebuild(getContext(), sbn.getNotification()); 648 649 // protect subclass from concurrent modifications of (@link mNotificationKeys}. 650 synchronized (mWrapper) { 651 applyUpdate(update); 652 try { 653 NotificationListenerService.this.onNotificationPosted(sbn, mRankingMap); 654 } catch (Throwable t) { 655 Log.w(TAG, "Error running onNotificationPosted", t); 656 } 657 } 658 } 659 @Override 660 public void onNotificationRemoved(IStatusBarNotificationHolder sbnHolder, 661 NotificationRankingUpdate update) { 662 StatusBarNotification sbn; 663 try { 664 sbn = sbnHolder.get(); 665 } catch (RemoteException e) { 666 Log.w(TAG, "onNotificationRemoved: Error receiving StatusBarNotification", e); 667 return; 668 } 669 // protect subclass from concurrent modifications of (@link mNotificationKeys}. 670 synchronized (mWrapper) { 671 applyUpdate(update); 672 try { 673 NotificationListenerService.this.onNotificationRemoved(sbn, mRankingMap); 674 } catch (Throwable t) { 675 Log.w(TAG, "Error running onNotificationRemoved", t); 676 } 677 } 678 } 679 @Override 680 public void onListenerConnected(NotificationRankingUpdate update) { 681 // protect subclass from concurrent modifications of (@link mNotificationKeys}. 682 synchronized (mWrapper) { 683 applyUpdate(update); 684 try { 685 NotificationListenerService.this.onListenerConnected(); 686 } catch (Throwable t) { 687 Log.w(TAG, "Error running onListenerConnected", t); 688 } 689 } 690 } 691 @Override 692 public void onNotificationRankingUpdate(NotificationRankingUpdate update) 693 throws RemoteException { 694 // protect subclass from concurrent modifications of (@link mNotificationKeys}. 695 synchronized (mWrapper) { 696 applyUpdate(update); 697 try { 698 NotificationListenerService.this.onNotificationRankingUpdate(mRankingMap); 699 } catch (Throwable t) { 700 Log.w(TAG, "Error running onNotificationRankingUpdate", t); 701 } 702 } 703 } 704 @Override 705 public void onListenerHintsChanged(int hints) throws RemoteException { 706 try { 707 NotificationListenerService.this.onListenerHintsChanged(hints); 708 } catch (Throwable t) { 709 Log.w(TAG, "Error running onListenerHintsChanged", t); 710 } 711 } 712 713 @Override 714 public void onInterruptionFilterChanged(int interruptionFilter) throws RemoteException { 715 try { 716 NotificationListenerService.this.onInterruptionFilterChanged(interruptionFilter); 717 } catch (Throwable t) { 718 Log.w(TAG, "Error running onInterruptionFilterChanged", t); 719 } 720 } 721 } 722 723 private void applyUpdate(NotificationRankingUpdate update) { 724 mRankingMap = new RankingMap(update); 725 } 726 727 private Context getContext() { 728 if (mSystemContext != null) { 729 return mSystemContext; 730 } 731 return this; 732 } 733 734 /** 735 * Stores ranking related information on a currently active notification. 736 * 737 * <p> 738 * Ranking objects aren't automatically updated as notification events 739 * occur. Instead, ranking information has to be retrieved again via the 740 * current {@link RankingMap}. 741 */ 742 public static class Ranking { 743 /** Value signifying that the user has not expressed a per-app visibility override value. 744 * @hide */ 745 public static final int VISIBILITY_NO_OVERRIDE = -1000; 746 747 private String mKey; 748 private int mRank = -1; 749 private boolean mIsAmbient; 750 private boolean mMatchesInterruptionFilter; 751 private int mVisibilityOverride; 752 753 public Ranking() {} 754 755 /** 756 * Returns the key of the notification this Ranking applies to. 757 */ 758 public String getKey() { 759 return mKey; 760 } 761 762 /** 763 * Returns the rank of the notification. 764 * 765 * @return the rank of the notification, that is the 0-based index in 766 * the list of active notifications. 767 */ 768 public int getRank() { 769 return mRank; 770 } 771 772 /** 773 * Returns whether the notification is an ambient notification, that is 774 * a notification that doesn't require the user's immediate attention. 775 */ 776 public boolean isAmbient() { 777 return mIsAmbient; 778 } 779 780 /** 781 * Returns the user specificed visibility for the package that posted 782 * this notification, or 783 * {@link NotificationListenerService.Ranking#VISIBILITY_NO_OVERRIDE} if 784 * no such preference has been expressed. 785 * @hide 786 */ 787 public int getVisibilityOverride() { 788 return mVisibilityOverride; 789 } 790 791 792 /** 793 * Returns whether the notification matches the user's interruption 794 * filter. 795 * 796 * @return {@code true} if the notification is allowed by the filter, or 797 * {@code false} if it is blocked. 798 */ 799 public boolean matchesInterruptionFilter() { 800 return mMatchesInterruptionFilter; 801 } 802 803 private void populate(String key, int rank, boolean isAmbient, 804 boolean matchesInterruptionFilter, int visibilityOverride) { 805 mKey = key; 806 mRank = rank; 807 mIsAmbient = isAmbient; 808 mMatchesInterruptionFilter = matchesInterruptionFilter; 809 mVisibilityOverride = visibilityOverride; 810 } 811 } 812 813 /** 814 * Provides access to ranking information on currently active 815 * notifications. 816 * 817 * <p> 818 * Note that this object represents a ranking snapshot that only applies to 819 * notifications active at the time of retrieval. 820 */ 821 public static class RankingMap implements Parcelable { 822 private final NotificationRankingUpdate mRankingUpdate; 823 private ArrayMap<String,Integer> mRanks; 824 private ArraySet<Object> mIntercepted; 825 private ArrayMap<String, Integer> mVisibilityOverrides; 826 827 private RankingMap(NotificationRankingUpdate rankingUpdate) { 828 mRankingUpdate = rankingUpdate; 829 } 830 831 /** 832 * Request the list of notification keys in their current ranking 833 * order. 834 * 835 * @return An array of active notification keys, in their ranking order. 836 */ 837 public String[] getOrderedKeys() { 838 return mRankingUpdate.getOrderedKeys(); 839 } 840 841 /** 842 * Populates outRanking with ranking information for the notification 843 * with the given key. 844 * 845 * @return true if a valid key has been passed and outRanking has 846 * been populated; false otherwise 847 */ 848 public boolean getRanking(String key, Ranking outRanking) { 849 int rank = getRank(key); 850 outRanking.populate(key, rank, isAmbient(key), !isIntercepted(key), 851 getVisibilityOverride(key)); 852 return rank >= 0; 853 } 854 855 private int getRank(String key) { 856 synchronized (this) { 857 if (mRanks == null) { 858 buildRanksLocked(); 859 } 860 } 861 Integer rank = mRanks.get(key); 862 return rank != null ? rank : -1; 863 } 864 865 private boolean isAmbient(String key) { 866 int firstAmbientIndex = mRankingUpdate.getFirstAmbientIndex(); 867 if (firstAmbientIndex < 0) { 868 return false; 869 } 870 int rank = getRank(key); 871 return rank >= 0 && rank >= firstAmbientIndex; 872 } 873 874 private boolean isIntercepted(String key) { 875 synchronized (this) { 876 if (mIntercepted == null) { 877 buildInterceptedSetLocked(); 878 } 879 } 880 return mIntercepted.contains(key); 881 } 882 883 private int getVisibilityOverride(String key) { 884 synchronized (this) { 885 if (mVisibilityOverrides == null) { 886 buildVisibilityOverridesLocked(); 887 } 888 } 889 Integer overide = mVisibilityOverrides.get(key); 890 if (overide == null) { 891 return Ranking.VISIBILITY_NO_OVERRIDE; 892 } 893 return overide.intValue(); 894 } 895 896 // Locked by 'this' 897 private void buildRanksLocked() { 898 String[] orderedKeys = mRankingUpdate.getOrderedKeys(); 899 mRanks = new ArrayMap<>(orderedKeys.length); 900 for (int i = 0; i < orderedKeys.length; i++) { 901 String key = orderedKeys[i]; 902 mRanks.put(key, i); 903 } 904 } 905 906 // Locked by 'this' 907 private void buildInterceptedSetLocked() { 908 String[] dndInterceptedKeys = mRankingUpdate.getInterceptedKeys(); 909 mIntercepted = new ArraySet<>(dndInterceptedKeys.length); 910 Collections.addAll(mIntercepted, dndInterceptedKeys); 911 } 912 913 // Locked by 'this' 914 private void buildVisibilityOverridesLocked() { 915 Bundle visibilityBundle = mRankingUpdate.getVisibilityOverrides(); 916 mVisibilityOverrides = new ArrayMap<>(visibilityBundle.size()); 917 for (String key: visibilityBundle.keySet()) { 918 mVisibilityOverrides.put(key, visibilityBundle.getInt(key)); 919 } 920 } 921 922 // ----------- Parcelable 923 924 @Override 925 public int describeContents() { 926 return 0; 927 } 928 929 @Override 930 public void writeToParcel(Parcel dest, int flags) { 931 dest.writeParcelable(mRankingUpdate, flags); 932 } 933 934 public static final Creator<RankingMap> CREATOR = new Creator<RankingMap>() { 935 @Override 936 public RankingMap createFromParcel(Parcel source) { 937 NotificationRankingUpdate rankingUpdate = source.readParcelable(null); 938 return new RankingMap(rankingUpdate); 939 } 940 941 @Override 942 public RankingMap[] newArray(int size) { 943 return new RankingMap[size]; 944 } 945 }; 946 } 947} 948