NotificationListenerService.java revision 617215874db9c208a74dc97f4133e6b6fc96271c
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; 18import android.service.notification.IStatusBarNotificationHolder; 19 20import android.annotation.SystemApi; 21import android.annotation.SdkConstant; 22import android.app.INotificationManager; 23import android.app.Notification; 24import android.app.Notification.Builder; 25import android.app.NotificationManager; 26import android.app.Service; 27import android.content.ComponentName; 28import android.content.Context; 29import android.content.Intent; 30import android.content.pm.ParceledListSlice; 31import android.graphics.drawable.BitmapDrawable; 32import android.graphics.drawable.Drawable; 33import android.graphics.drawable.Icon; 34import android.graphics.Bitmap; 35import android.os.Build; 36import android.os.Bundle; 37import android.os.IBinder; 38import android.os.Parcel; 39import android.os.Parcelable; 40import android.os.RemoteException; 41import android.os.ServiceManager; 42import android.util.ArrayMap; 43import android.util.ArraySet; 44import android.util.Log; 45 46import java.util.ArrayList; 47import java.util.Collections; 48import java.util.List; 49 50/** 51 * A service that receives calls from the system when new notifications are 52 * posted or removed, or their ranking changed. 53 * <p>To extend this class, you must declare the service in your manifest file with 54 * the {@link android.Manifest.permission#BIND_NOTIFICATION_LISTENER_SERVICE} permission 55 * and include an intent filter with the {@link #SERVICE_INTERFACE} action. For example:</p> 56 * <pre> 57 * <service android:name=".NotificationListener" 58 * android:label="@string/service_name" 59 * android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"> 60 * <intent-filter> 61 * <action android:name="android.service.notification.NotificationListenerService" /> 62 * </intent-filter> 63 * </service></pre> 64 * <p> Typically, while enabled in user settings, this service will be bound on boot or when a 65 * settings change occurs that could affect whether this service should run. However, for some 66 * system usage modes, the you may instead specify that this service is instead bound and unbound 67 * in response to mode changes by including a category in the intent filter. Currently 68 * supported categories are: 69 * <ul> 70 * <li>{@link #CATEGORY_VR_NOTIFICATIONS} - this service is bound when an Activity has enabled 71 * VR mode. {@see android.app.Activity#setVrMode(boolean)}.</li> 72 * </ul> 73 * </p> 74 */ 75public abstract class NotificationListenerService extends Service { 76 // TAG = "NotificationListenerService[MySubclass]" 77 private final String TAG = NotificationListenerService.class.getSimpleName() 78 + "[" + getClass().getSimpleName() + "]"; 79 80 /** 81 * {@link #getCurrentInterruptionFilter() Interruption filter} constant - 82 * Normal interruption filter. 83 */ 84 public static final int INTERRUPTION_FILTER_ALL 85 = NotificationManager.INTERRUPTION_FILTER_ALL; 86 87 /** 88 * {@link #getCurrentInterruptionFilter() Interruption filter} constant - 89 * Priority interruption filter. 90 */ 91 public static final int INTERRUPTION_FILTER_PRIORITY 92 = NotificationManager.INTERRUPTION_FILTER_PRIORITY; 93 94 /** 95 * {@link #getCurrentInterruptionFilter() Interruption filter} constant - 96 * No interruptions filter. 97 */ 98 public static final int INTERRUPTION_FILTER_NONE 99 = NotificationManager.INTERRUPTION_FILTER_NONE; 100 101 /** 102 * {@link #getCurrentInterruptionFilter() Interruption filter} constant - 103 * Alarms only interruption filter. 104 */ 105 public static final int INTERRUPTION_FILTER_ALARMS 106 = NotificationManager.INTERRUPTION_FILTER_ALARMS; 107 108 /** {@link #getCurrentInterruptionFilter() Interruption filter} constant - returned when 109 * the value is unavailable for any reason. For example, before the notification listener 110 * is connected. 111 * 112 * {@see #onListenerConnected()} 113 */ 114 public static final int INTERRUPTION_FILTER_UNKNOWN 115 = NotificationManager.INTERRUPTION_FILTER_UNKNOWN; 116 117 /** {@link #getCurrentListenerHints() Listener hints} constant - the primary device UI 118 * should disable notification sound, vibrating and other visual or aural effects. 119 * This does not change the interruption filter, only the effects. **/ 120 public static final int HINT_HOST_DISABLE_EFFECTS = 1; 121 122 public static final int SUPPRESSED_EFFECT_LIGHTS = 123 NotificationManager.Policy.SUPPRESSED_EFFECT_LIGHTS; 124 public static final int SUPPRESSED_EFFECT_PEEK = 125 NotificationManager.Policy.SUPPRESSED_EFFECT_PEEK; 126 public static final int SUPPRESSED_EFFECT_SCREEN_ON = 127 NotificationManager.Policy.SUPPRESSED_EFFECT_SCREEN_ON; 128 129 /** 130 * The full trim of the StatusBarNotification including all its features. 131 * 132 * @hide 133 */ 134 @SystemApi 135 public static final int TRIM_FULL = 0; 136 137 /** 138 * A light trim of the StatusBarNotification excluding the following features: 139 * 140 * <ol> 141 * <li>{@link Notification#tickerView tickerView}</li> 142 * <li>{@link Notification#contentView contentView}</li> 143 * <li>{@link Notification#largeIcon largeIcon}</li> 144 * <li>{@link Notification#bigContentView bigContentView}</li> 145 * <li>{@link Notification#headsUpContentView headsUpContentView}</li> 146 * <li>{@link Notification#EXTRA_LARGE_ICON extras[EXTRA_LARGE_ICON]}</li> 147 * <li>{@link Notification#EXTRA_LARGE_ICON_BIG extras[EXTRA_LARGE_ICON_BIG]}</li> 148 * <li>{@link Notification#EXTRA_PICTURE extras[EXTRA_PICTURE]}</li> 149 * <li>{@link Notification#EXTRA_BIG_TEXT extras[EXTRA_BIG_TEXT]}</li> 150 * </ol> 151 * 152 * @hide 153 */ 154 @SystemApi 155 public static final int TRIM_LIGHT = 1; 156 157 /** @hide */ 158 protected NotificationListenerWrapper mWrapper = null; 159 private RankingMap mRankingMap; 160 161 private INotificationManager mNoMan; 162 163 /** Only valid after a successful call to (@link registerAsService}. */ 164 private int mCurrentUser; 165 166 167 // This context is required for system services since NotificationListenerService isn't 168 // started as a real Service and hence no context is available. 169 private Context mSystemContext; 170 171 /** 172 * The {@link Intent} that must be declared as handled by the service. 173 */ 174 @SdkConstant(SdkConstant.SdkConstantType.SERVICE_ACTION) 175 public static final String SERVICE_INTERFACE 176 = "android.service.notification.NotificationListenerService"; 177 178 /** 179 * If this category is declared in the application manifest for a service of this type, this 180 * service will be bound when VR mode is enabled, and unbound when VR mode is disabled rather 181 * than the normal lifecycle for a notification service. 182 * 183 * {@see android.app.Activity#setVrMode(boolean)} 184 */ 185 @SdkConstant(SdkConstant.SdkConstantType.INTENT_CATEGORY) 186 public static final String CATEGORY_VR_NOTIFICATIONS = 187 "android.intent.category.vr.notifications"; 188 189 /** 190 * Implement this method to learn about new notifications as they are posted by apps. 191 * 192 * @param sbn A data structure encapsulating the original {@link android.app.Notification} 193 * object as well as its identifying information (tag and id) and source 194 * (package name). 195 */ 196 public void onNotificationPosted(StatusBarNotification sbn) { 197 // optional 198 } 199 200 /** 201 * Implement this method to learn about new notifications as they are posted by apps. 202 * 203 * @param sbn A data structure encapsulating the original {@link android.app.Notification} 204 * object as well as its identifying information (tag and id) and source 205 * (package name). 206 * @param rankingMap The current ranking map that can be used to retrieve ranking information 207 * for active notifications, including the newly posted one. 208 */ 209 public void onNotificationPosted(StatusBarNotification sbn, RankingMap rankingMap) { 210 onNotificationPosted(sbn); 211 } 212 213 /** 214 * Implement this method to learn when notifications are removed. 215 * <P> 216 * This might occur because the user has dismissed the notification using system UI (or another 217 * notification listener) or because the app has withdrawn the notification. 218 * <P> 219 * NOTE: The {@link StatusBarNotification} object you receive will be "light"; that is, the 220 * result from {@link StatusBarNotification#getNotification} may be missing some heavyweight 221 * fields such as {@link android.app.Notification#contentView} and 222 * {@link android.app.Notification#largeIcon}. However, all other fields on 223 * {@link StatusBarNotification}, sufficient to match this call with a prior call to 224 * {@link #onNotificationPosted(StatusBarNotification)}, will be intact. 225 * 226 * @param sbn A data structure encapsulating at least the original information (tag and id) 227 * and source (package name) used to post the {@link android.app.Notification} that 228 * was just removed. 229 */ 230 public void onNotificationRemoved(StatusBarNotification sbn) { 231 // optional 232 } 233 234 /** 235 * Implement this method to learn when notifications are removed. 236 * <P> 237 * This might occur because the user has dismissed the notification using system UI (or another 238 * notification listener) or because the app has withdrawn the notification. 239 * <P> 240 * NOTE: The {@link StatusBarNotification} object you receive will be "light"; that is, the 241 * result from {@link StatusBarNotification#getNotification} may be missing some heavyweight 242 * fields such as {@link android.app.Notification#contentView} and 243 * {@link android.app.Notification#largeIcon}. However, all other fields on 244 * {@link StatusBarNotification}, sufficient to match this call with a prior call to 245 * {@link #onNotificationPosted(StatusBarNotification)}, will be intact. 246 * 247 * @param sbn A data structure encapsulating at least the original information (tag and id) 248 * and source (package name) used to post the {@link android.app.Notification} that 249 * was just removed. 250 * @param rankingMap The current ranking map that can be used to retrieve ranking information 251 * for active notifications. 252 * 253 */ 254 public void onNotificationRemoved(StatusBarNotification sbn, RankingMap rankingMap) { 255 onNotificationRemoved(sbn); 256 } 257 258 /** 259 * Implement this method to learn about when the listener is enabled and connected to 260 * the notification manager. You are safe to call {@link #getActiveNotifications()} 261 * at this time. 262 */ 263 public void onListenerConnected() { 264 // optional 265 } 266 267 /** 268 * Implement this method to be notified when the notification ranking changes. 269 * 270 * @param rankingMap The current ranking map that can be used to retrieve ranking information 271 * for active notifications. 272 */ 273 public void onNotificationRankingUpdate(RankingMap rankingMap) { 274 // optional 275 } 276 277 /** 278 * Implement this method to be notified when the 279 * {@link #getCurrentListenerHints() Listener hints} change. 280 * 281 * @param hints The current {@link #getCurrentListenerHints() listener hints}. 282 */ 283 public void onListenerHintsChanged(int hints) { 284 // optional 285 } 286 287 /** 288 * Implement this method to be notified when the 289 * {@link #getCurrentInterruptionFilter() interruption filter} changed. 290 * 291 * @param interruptionFilter The current 292 * {@link #getCurrentInterruptionFilter() interruption filter}. 293 */ 294 public void onInterruptionFilterChanged(int interruptionFilter) { 295 // optional 296 } 297 298 /** @hide */ 299 protected final INotificationManager getNotificationInterface() { 300 if (mNoMan == null) { 301 mNoMan = INotificationManager.Stub.asInterface( 302 ServiceManager.getService(Context.NOTIFICATION_SERVICE)); 303 } 304 return mNoMan; 305 } 306 307 /** 308 * Inform the notification manager about dismissal of a single notification. 309 * <p> 310 * Use this if your listener has a user interface that allows the user to dismiss individual 311 * notifications, similar to the behavior of Android's status bar and notification panel. 312 * It should be called after the user dismisses a single notification using your UI; 313 * upon being informed, the notification manager will actually remove the notification 314 * and you will get an {@link #onNotificationRemoved(StatusBarNotification)} callback. 315 * <P> 316 * <b>Note:</b> If your listener allows the user to fire a notification's 317 * {@link android.app.Notification#contentIntent} by tapping/clicking/etc., you should call 318 * this method at that time <i>if</i> the Notification in question has the 319 * {@link android.app.Notification#FLAG_AUTO_CANCEL} flag set. 320 * 321 * @param pkg Package of the notifying app. 322 * @param tag Tag of the notification as specified by the notifying app in 323 * {@link android.app.NotificationManager#notify(String, int, android.app.Notification)}. 324 * @param id ID of the notification as specified by the notifying app in 325 * {@link android.app.NotificationManager#notify(String, int, android.app.Notification)}. 326 * <p> 327 * @deprecated Use {@link #cancelNotification(String key)} 328 * instead. Beginning with {@link android.os.Build.VERSION_CODES#LOLLIPOP} this method will no longer 329 * cancel the notification. It will continue to cancel the notification for applications 330 * whose {@code targetSdkVersion} is earlier than {@link android.os.Build.VERSION_CODES#LOLLIPOP}. 331 */ 332 public final void cancelNotification(String pkg, String tag, int id) { 333 if (!isBound()) return; 334 try { 335 getNotificationInterface().cancelNotificationFromListener( 336 mWrapper, pkg, tag, id); 337 } catch (android.os.RemoteException ex) { 338 Log.v(TAG, "Unable to contact notification manager", ex); 339 } 340 } 341 342 /** 343 * Inform the notification manager about dismissal of a single notification. 344 * <p> 345 * Use this if your listener has a user interface that allows the user to dismiss individual 346 * notifications, similar to the behavior of Android's status bar and notification panel. 347 * It should be called after the user dismisses a single notification using your UI; 348 * upon being informed, the notification manager will actually remove the notification 349 * and you will get an {@link #onNotificationRemoved(StatusBarNotification)} callback. 350 * <P> 351 * <b>Note:</b> If your listener allows the user to fire a notification's 352 * {@link android.app.Notification#contentIntent} by tapping/clicking/etc., you should call 353 * this method at that time <i>if</i> the Notification in question has the 354 * {@link android.app.Notification#FLAG_AUTO_CANCEL} flag set. 355 * <p> 356 * @param key Notification to dismiss from {@link StatusBarNotification#getKey()}. 357 */ 358 public final void cancelNotification(String key) { 359 if (!isBound()) return; 360 try { 361 getNotificationInterface().cancelNotificationsFromListener(mWrapper, 362 new String[] { key }); 363 } catch (android.os.RemoteException ex) { 364 Log.v(TAG, "Unable to contact notification manager", ex); 365 } 366 } 367 368 /** 369 * Inform the notification manager about dismissal of all notifications. 370 * <p> 371 * Use this if your listener has a user interface that allows the user to dismiss all 372 * notifications, similar to the behavior of Android's status bar and notification panel. 373 * It should be called after the user invokes the "dismiss all" function of your UI; 374 * upon being informed, the notification manager will actually remove all active notifications 375 * and you will get multiple {@link #onNotificationRemoved(StatusBarNotification)} callbacks. 376 * 377 * {@see #cancelNotification(String, String, int)} 378 */ 379 public final void cancelAllNotifications() { 380 cancelNotifications(null /*all*/); 381 } 382 383 /** 384 * Inform the notification manager about dismissal of specific notifications. 385 * <p> 386 * Use this if your listener has a user interface that allows the user to dismiss 387 * multiple notifications at once. 388 * 389 * @param keys Notifications to dismiss, or {@code null} to dismiss all. 390 * 391 * {@see #cancelNotification(String, String, int)} 392 */ 393 public final void cancelNotifications(String[] keys) { 394 if (!isBound()) return; 395 try { 396 getNotificationInterface().cancelNotificationsFromListener(mWrapper, keys); 397 } catch (android.os.RemoteException ex) { 398 Log.v(TAG, "Unable to contact notification manager", ex); 399 } 400 } 401 402 /** 403 * Inform the notification manager that these notifications have been viewed by the 404 * user. This should only be called when there is sufficient confidence that the user is 405 * looking at the notifications, such as when the notifications appear on the screen due to 406 * an explicit user interaction. 407 * @param keys Notifications to mark as seen. 408 */ 409 public final void setNotificationsShown(String[] keys) { 410 if (!isBound()) return; 411 try { 412 getNotificationInterface().setNotificationsShownFromListener(mWrapper, keys); 413 } catch (android.os.RemoteException ex) { 414 Log.v(TAG, "Unable to contact notification manager", ex); 415 } 416 } 417 418 /** 419 * Sets the notification trim that will be received via {@link #onNotificationPosted}. 420 * 421 * <p> 422 * Setting a trim other than {@link #TRIM_FULL} enables listeners that don't need access to the 423 * full notification features right away to reduce their memory footprint. Full notifications 424 * can be requested on-demand via {@link #getActiveNotifications(int)}. 425 * 426 * <p> 427 * Set to {@link #TRIM_FULL} initially. 428 * 429 * @hide 430 * 431 * @param trim trim of the notifications to be passed via {@link #onNotificationPosted}. 432 * See <code>TRIM_*</code> constants. 433 */ 434 @SystemApi 435 public final void setOnNotificationPostedTrim(int trim) { 436 if (!isBound()) return; 437 try { 438 getNotificationInterface().setOnNotificationPostedTrimFromListener(mWrapper, trim); 439 } catch (RemoteException ex) { 440 Log.v(TAG, "Unable to contact notification manager", ex); 441 } 442 } 443 444 /** 445 * Request the list of outstanding notifications (that is, those that are visible to the 446 * current user). Useful when you don't know what's already been posted. 447 * 448 * @return An array of active notifications, sorted in natural order. 449 */ 450 public StatusBarNotification[] getActiveNotifications() { 451 return getActiveNotifications(null, TRIM_FULL); 452 } 453 454 /** 455 * Request the list of outstanding notifications (that is, those that are visible to the 456 * current user). Useful when you don't know what's already been posted. 457 * 458 * @hide 459 * 460 * @param trim trim of the notifications to be returned. See <code>TRIM_*</code> constants. 461 * @return An array of active notifications, sorted in natural order. 462 */ 463 @SystemApi 464 public StatusBarNotification[] getActiveNotifications(int trim) { 465 return getActiveNotifications(null, trim); 466 } 467 468 /** 469 * Request one or more notifications by key. Useful if you have been keeping track of 470 * notifications but didn't want to retain the bits, and now need to go back and extract 471 * more data out of those notifications. 472 * 473 * @param keys the keys of the notifications to request 474 * @return An array of notifications corresponding to the requested keys, in the 475 * same order as the key list. 476 */ 477 public StatusBarNotification[] getActiveNotifications(String[] keys) { 478 return getActiveNotifications(keys, TRIM_FULL); 479 } 480 481 /** 482 * Request one or more notifications by key. Useful if you have been keeping track of 483 * notifications but didn't want to retain the bits, and now need to go back and extract 484 * more data out of those notifications. 485 * 486 * @hide 487 * 488 * @param keys the keys of the notifications to request 489 * @param trim trim of the notifications to be returned. See <code>TRIM_*</code> constants. 490 * @return An array of notifications corresponding to the requested keys, in the 491 * same order as the key list. 492 */ 493 @SystemApi 494 public StatusBarNotification[] getActiveNotifications(String[] keys, int trim) { 495 if (!isBound()) 496 return null; 497 try { 498 ParceledListSlice<StatusBarNotification> parceledList = getNotificationInterface() 499 .getActiveNotificationsFromListener(mWrapper, keys, trim); 500 List<StatusBarNotification> list = parceledList.getList(); 501 ArrayList<StatusBarNotification> corruptNotifications = null; 502 int N = list.size(); 503 for (int i = 0; i < N; i++) { 504 StatusBarNotification sbn = list.get(i); 505 Notification notification = sbn.getNotification(); 506 try { 507 // convert icon metadata to legacy format for older clients 508 createLegacyIconExtras(notification); 509 // populate remote views for older clients. 510 maybePopulateRemoteViews(notification); 511 } catch (IllegalArgumentException e) { 512 if (corruptNotifications == null) { 513 corruptNotifications = new ArrayList<>(N); 514 } 515 corruptNotifications.add(sbn); 516 Log.w(TAG, "onNotificationPosted: can't rebuild notification from " + 517 sbn.getPackageName()); 518 } 519 } 520 if (corruptNotifications != null) { 521 list.removeAll(corruptNotifications); 522 } 523 return list.toArray(new StatusBarNotification[list.size()]); 524 } catch (android.os.RemoteException ex) { 525 Log.v(TAG, "Unable to contact notification manager", ex); 526 } 527 return null; 528 } 529 530 /** 531 * Gets the set of hints representing current state. 532 * 533 * <p> 534 * The current state may differ from the requested state if the hint represents state 535 * shared across all listeners or a feature the notification host does not support or refuses 536 * to grant. 537 * 538 * @return Zero or more of the HINT_ constants. 539 */ 540 public final int getCurrentListenerHints() { 541 if (!isBound()) return 0; 542 try { 543 return getNotificationInterface().getHintsFromListener(mWrapper); 544 } catch (android.os.RemoteException ex) { 545 Log.v(TAG, "Unable to contact notification manager", ex); 546 return 0; 547 } 548 } 549 550 /** 551 * Gets the current notification interruption filter active on the host. 552 * 553 * <p> 554 * The interruption filter defines which notifications are allowed to interrupt the user 555 * (e.g. via sound & vibration) and is applied globally. Listeners can find out whether 556 * a specific notification matched the interruption filter via 557 * {@link Ranking#matchesInterruptionFilter()}. 558 * <p> 559 * The current filter may differ from the previously requested filter if the notification host 560 * does not support or refuses to apply the requested filter, or if another component changed 561 * the filter in the meantime. 562 * <p> 563 * Listen for updates using {@link #onInterruptionFilterChanged(int)}. 564 * 565 * @return One of the INTERRUPTION_FILTER_ constants, or INTERRUPTION_FILTER_UNKNOWN when 566 * unavailable. 567 */ 568 public final int getCurrentInterruptionFilter() { 569 if (!isBound()) return INTERRUPTION_FILTER_UNKNOWN; 570 try { 571 return getNotificationInterface().getInterruptionFilterFromListener(mWrapper); 572 } catch (android.os.RemoteException ex) { 573 Log.v(TAG, "Unable to contact notification manager", ex); 574 return INTERRUPTION_FILTER_UNKNOWN; 575 } 576 } 577 578 /** 579 * Sets the desired {@link #getCurrentListenerHints() listener hints}. 580 * 581 * <p> 582 * This is merely a request, the host may or may not choose to take action depending 583 * on other listener requests or other global state. 584 * <p> 585 * Listen for updates using {@link #onListenerHintsChanged(int)}. 586 * 587 * @param hints One or more of the HINT_ constants. 588 */ 589 public final void requestListenerHints(int hints) { 590 if (!isBound()) return; 591 try { 592 getNotificationInterface().requestHintsFromListener(mWrapper, hints); 593 } catch (android.os.RemoteException ex) { 594 Log.v(TAG, "Unable to contact notification manager", ex); 595 } 596 } 597 598 /** 599 * Sets the desired {@link #getCurrentInterruptionFilter() interruption filter}. 600 * 601 * <p> 602 * This is merely a request, the host may or may not choose to apply the requested 603 * interruption filter depending on other listener requests or other global state. 604 * <p> 605 * Listen for updates using {@link #onInterruptionFilterChanged(int)}. 606 * 607 * @param interruptionFilter One of the INTERRUPTION_FILTER_ constants. 608 */ 609 public final void requestInterruptionFilter(int interruptionFilter) { 610 if (!isBound()) return; 611 try { 612 getNotificationInterface() 613 .requestInterruptionFilterFromListener(mWrapper, interruptionFilter); 614 } catch (android.os.RemoteException ex) { 615 Log.v(TAG, "Unable to contact notification manager", ex); 616 } 617 } 618 619 /** 620 * Returns current ranking information. 621 * 622 * <p> 623 * The returned object represents the current ranking snapshot and only 624 * applies for currently active notifications. 625 * <p> 626 * Generally you should use the RankingMap that is passed with events such 627 * as {@link #onNotificationPosted(StatusBarNotification, RankingMap)}, 628 * {@link #onNotificationRemoved(StatusBarNotification, RankingMap)}, and 629 * so on. This method should only be used when needing access outside of 630 * such events, for example to retrieve the RankingMap right after 631 * initialization. 632 * 633 * @return A {@link RankingMap} object providing access to ranking information 634 */ 635 public RankingMap getCurrentRanking() { 636 return mRankingMap; 637 } 638 639 @Override 640 public IBinder onBind(Intent intent) { 641 if (mWrapper == null) { 642 mWrapper = new NotificationListenerWrapper(); 643 } 644 return mWrapper; 645 } 646 647 /** @hide */ 648 protected boolean isBound() { 649 if (mWrapper == null) { 650 Log.w(TAG, "Notification listener service not yet bound."); 651 return false; 652 } 653 return true; 654 } 655 656 /** 657 * Directly register this service with the Notification Manager. 658 * 659 * <p>Only system services may use this call. It will fail for non-system callers. 660 * Apps should ask the user to add their listener in Settings. 661 * 662 * @param context Context required for accessing resources. Since this service isn't 663 * launched as a real Service when using this method, a context has to be passed in. 664 * @param componentName the component that will consume the notification information 665 * @param currentUser the user to use as the stream filter 666 * @hide 667 */ 668 @SystemApi 669 public void registerAsSystemService(Context context, ComponentName componentName, 670 int currentUser) throws RemoteException { 671 mSystemContext = context; 672 if (mWrapper == null) { 673 mWrapper = new NotificationListenerWrapper(); 674 } 675 INotificationManager noMan = getNotificationInterface(); 676 noMan.registerListener(mWrapper, componentName, currentUser); 677 mCurrentUser = currentUser; 678 } 679 680 /** 681 * Directly unregister this service from the Notification Manager. 682 * 683 * <P>This method will fail for listeners that were not registered 684 * with (@link registerAsService). 685 * @hide 686 */ 687 @SystemApi 688 public void unregisterAsSystemService() throws RemoteException { 689 if (mWrapper != null) { 690 INotificationManager noMan = getNotificationInterface(); 691 noMan.unregisterListener(mWrapper, mCurrentUser); 692 } 693 } 694 695 /** Convert new-style Icons to legacy representations for pre-M clients. */ 696 private void createLegacyIconExtras(Notification n) { 697 Icon smallIcon = n.getSmallIcon(); 698 Icon largeIcon = n.getLargeIcon(); 699 if (smallIcon != null && smallIcon.getType() == Icon.TYPE_RESOURCE) { 700 n.extras.putInt(Notification.EXTRA_SMALL_ICON, smallIcon.getResId()); 701 n.icon = smallIcon.getResId(); 702 } 703 if (largeIcon != null) { 704 Drawable d = largeIcon.loadDrawable(getContext()); 705 if (d != null && d instanceof BitmapDrawable) { 706 final Bitmap largeIconBits = ((BitmapDrawable) d).getBitmap(); 707 n.extras.putParcelable(Notification.EXTRA_LARGE_ICON, largeIconBits); 708 n.largeIcon = largeIconBits; 709 } 710 } 711 } 712 713 /** 714 * Populates remote views for pre-N targeting apps. 715 */ 716 private void maybePopulateRemoteViews(Notification notification) { 717 if (getContext().getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N) { 718 Builder builder = Builder.recoverBuilder(getContext(), notification); 719 notification.contentView = builder.makeContentView(); 720 notification.bigContentView = builder.makeBigContentView(); 721 notification.headsUpContentView = builder.makeHeadsUpContentView(); 722 } 723 } 724 725 /** @hide */ 726 protected class NotificationListenerWrapper extends INotificationListener.Stub { 727 @Override 728 public void onNotificationPosted(IStatusBarNotificationHolder sbnHolder, 729 NotificationRankingUpdate update) { 730 StatusBarNotification sbn; 731 try { 732 sbn = sbnHolder.get(); 733 } catch (RemoteException e) { 734 Log.w(TAG, "onNotificationPosted: Error receiving StatusBarNotification", e); 735 return; 736 } 737 738 try { 739 Notification notification = sbn.getNotification(); 740 // convert icon metadata to legacy format for older clients 741 createLegacyIconExtras(sbn.getNotification()); 742 maybePopulateRemoteViews(sbn.getNotification()); 743 } catch (IllegalArgumentException e) { 744 // warn and drop corrupt notification 745 Log.w(TAG, "onNotificationPosted: can't rebuild notification from " + 746 sbn.getPackageName()); 747 sbn = null; 748 } 749 750 // protect subclass from concurrent modifications of (@link mNotificationKeys}. 751 synchronized (mWrapper) { 752 applyUpdate(update); 753 try { 754 if (sbn != null) { 755 NotificationListenerService.this.onNotificationPosted(sbn, mRankingMap); 756 } else { 757 // still pass along the ranking map, it may contain other information 758 NotificationListenerService.this.onNotificationRankingUpdate(mRankingMap); 759 } 760 } catch (Throwable t) { 761 Log.w(TAG, "Error running onNotificationPosted", t); 762 } 763 } 764 } 765 @Override 766 public void onNotificationRemoved(IStatusBarNotificationHolder sbnHolder, 767 NotificationRankingUpdate update) { 768 StatusBarNotification sbn; 769 try { 770 sbn = sbnHolder.get(); 771 } catch (RemoteException e) { 772 Log.w(TAG, "onNotificationRemoved: Error receiving StatusBarNotification", e); 773 return; 774 } 775 // protect subclass from concurrent modifications of (@link mNotificationKeys}. 776 synchronized (mWrapper) { 777 applyUpdate(update); 778 try { 779 NotificationListenerService.this.onNotificationRemoved(sbn, mRankingMap); 780 } catch (Throwable t) { 781 Log.w(TAG, "Error running onNotificationRemoved", t); 782 } 783 } 784 } 785 @Override 786 public void onListenerConnected(NotificationRankingUpdate update) { 787 // protect subclass from concurrent modifications of (@link mNotificationKeys}. 788 synchronized (mWrapper) { 789 applyUpdate(update); 790 try { 791 NotificationListenerService.this.onListenerConnected(); 792 } catch (Throwable t) { 793 Log.w(TAG, "Error running onListenerConnected", t); 794 } 795 } 796 } 797 @Override 798 public void onNotificationRankingUpdate(NotificationRankingUpdate update) 799 throws RemoteException { 800 // protect subclass from concurrent modifications of (@link mNotificationKeys}. 801 synchronized (mWrapper) { 802 applyUpdate(update); 803 try { 804 NotificationListenerService.this.onNotificationRankingUpdate(mRankingMap); 805 } catch (Throwable t) { 806 Log.w(TAG, "Error running onNotificationRankingUpdate", t); 807 } 808 } 809 } 810 @Override 811 public void onListenerHintsChanged(int hints) throws RemoteException { 812 try { 813 NotificationListenerService.this.onListenerHintsChanged(hints); 814 } catch (Throwable t) { 815 Log.w(TAG, "Error running onListenerHintsChanged", t); 816 } 817 } 818 819 @Override 820 public void onInterruptionFilterChanged(int interruptionFilter) throws RemoteException { 821 try { 822 NotificationListenerService.this.onInterruptionFilterChanged(interruptionFilter); 823 } catch (Throwable t) { 824 Log.w(TAG, "Error running onInterruptionFilterChanged", t); 825 } 826 } 827 828 @Override 829 public void onNotificationEnqueued(IStatusBarNotificationHolder notificationHolder, 830 int importance, boolean user) throws RemoteException { 831 // no-op in the listener 832 } 833 834 @Override 835 public void onNotificationVisibilityChanged(String key, long time, boolean visible) 836 throws RemoteException { 837 // no-op in the listener 838 } 839 840 @Override 841 public void onNotificationClick(String key, long time) throws RemoteException { 842 // no-op in the listener 843 } 844 845 @Override 846 public void onNotificationActionClick(String key, long time, int actionIndex) 847 throws RemoteException { 848 // no-op in the listener 849 } 850 851 @Override 852 public void onNotificationRemovedReason(String key, long time, int reason) 853 throws RemoteException { 854 // no-op in the listener 855 } 856 } 857 858 private void applyUpdate(NotificationRankingUpdate update) { 859 mRankingMap = new RankingMap(update); 860 } 861 862 private Context getContext() { 863 if (mSystemContext != null) { 864 return mSystemContext; 865 } 866 return this; 867 } 868 869 /** 870 * Stores ranking related information on a currently active notification. 871 * 872 * <p> 873 * Ranking objects aren't automatically updated as notification events 874 * occur. Instead, ranking information has to be retrieved again via the 875 * current {@link RankingMap}. 876 */ 877 public static class Ranking { 878 /** Value signifying that the user has not expressed a per-app visibility override value. 879 * @hide */ 880 public static final int VISIBILITY_NO_OVERRIDE = -1000; 881 882 /** 883 * Value signifying that the user has not expressed an importance. 884 * 885 * This value is for persisting preferences, and should never be associated with 886 * an actual notification. 887 */ 888 public static final int IMPORTANCE_UNSPECIFIED = -1000; 889 890 /** 891 * A notification with no importance: shows nowhere, is blocked. 892 */ 893 public static final int IMPORTANCE_NONE = 0; 894 895 /** 896 * Low notification importance: only shows in the shade, below the fold. 897 */ 898 public static final int IMPORTANCE_LOW = 1; 899 900 /** 901 * Default notification importance: shows everywhere, but is not intrusive. 902 */ 903 public static final int IMPORTANCE_DEFAULT = 2; 904 905 /** 906 * Higher notification importance: shows everywhere, makes noise, 907 * but does not visually intrude. 908 */ 909 public static final int IMPORTANCE_HIGH = 3; 910 911 /** 912 * Highest notification importance: shows everywhere, makes noise, 913 * and also visually intrudes. 914 */ 915 public static final int IMPORTANCE_MAX = 4; 916 917 private String mKey; 918 private int mRank = -1; 919 private boolean mIsAmbient; 920 private boolean mMatchesInterruptionFilter; 921 private int mVisibilityOverride; 922 private int mSuppressedVisualEffects; 923 private int mImportance; 924 private CharSequence mImportanceExplanation; 925 926 public Ranking() {} 927 928 /** 929 * Returns the key of the notification this Ranking applies to. 930 */ 931 public String getKey() { 932 return mKey; 933 } 934 935 /** 936 * Returns the rank of the notification. 937 * 938 * @return the rank of the notification, that is the 0-based index in 939 * the list of active notifications. 940 */ 941 public int getRank() { 942 return mRank; 943 } 944 945 /** 946 * Returns whether the notification is an ambient notification, that is 947 * a notification that doesn't require the user's immediate attention. 948 */ 949 public boolean isAmbient() { 950 return mIsAmbient; 951 } 952 953 /** 954 * Returns the user specificed visibility for the package that posted 955 * this notification, or 956 * {@link NotificationListenerService.Ranking#VISIBILITY_NO_OVERRIDE} if 957 * no such preference has been expressed. 958 * @hide 959 */ 960 public int getVisibilityOverride() { 961 return mVisibilityOverride; 962 } 963 964 /** 965 * Returns the type(s) of visual effects that should be suppressed for this notification. 966 * See {@link #SUPPRESSED_EFFECT_LIGHTS}, {@link #SUPPRESSED_EFFECT_PEEK}, 967 * {@link #SUPPRESSED_EFFECT_SCREEN_ON}. 968 */ 969 public int getSuppressedVisualEffects() { 970 return mSuppressedVisualEffects; 971 } 972 973 /** 974 * Returns whether the notification matches the user's interruption 975 * filter. 976 * 977 * @return {@code true} if the notification is allowed by the filter, or 978 * {@code false} if it is blocked. 979 */ 980 public boolean matchesInterruptionFilter() { 981 return mMatchesInterruptionFilter; 982 } 983 984 /** 985 * Returns the importance of the notification, which dictates its 986 * modes of presentation, see: {@link #IMPORTANCE_DEFAULT}, etc. 987 * 988 * @return the rank of the notification 989 */ 990 public int getImportance() { 991 return mImportance; 992 } 993 994 /** 995 * If the importance has been overriden by user preference, or by a 996 * {@link NotificationAssistantService}, then this will be non-null, 997 * and should be displayed to the user. 998 * 999 * @return the explanation for the importance, or null if it is the natural importance 1000 */ 1001 public CharSequence getImportanceExplanation() { 1002 return mImportanceExplanation; 1003 } 1004 1005 private void populate(String key, int rank, boolean isAmbient, 1006 boolean matchesInterruptionFilter, int visibilityOverride, 1007 int suppressedVisualEffects, int importance, 1008 CharSequence explanation) { 1009 mKey = key; 1010 mRank = rank; 1011 mIsAmbient = isAmbient; 1012 mMatchesInterruptionFilter = matchesInterruptionFilter; 1013 mVisibilityOverride = visibilityOverride; 1014 mSuppressedVisualEffects = suppressedVisualEffects; 1015 mImportance = importance; 1016 mImportanceExplanation = explanation; 1017 } 1018 1019 /** 1020 * {@hide} 1021 */ 1022 public static String importanceToString(int importance) { 1023 switch (importance) { 1024 case IMPORTANCE_UNSPECIFIED: 1025 return "UNSPECIFIED"; 1026 case IMPORTANCE_NONE: 1027 return "NONE"; 1028 case IMPORTANCE_LOW: 1029 return "LOW"; 1030 case IMPORTANCE_DEFAULT: 1031 return "DEFAULT"; 1032 case IMPORTANCE_HIGH: 1033 return "HIGH"; 1034 case IMPORTANCE_MAX: 1035 return "MAX"; 1036 default: 1037 return "UNKNOWN(" + String.valueOf(importance) + ")"; 1038 } 1039 } 1040 } 1041 1042 /** 1043 * Provides access to ranking information on currently active 1044 * notifications. 1045 * 1046 * <p> 1047 * Note that this object represents a ranking snapshot that only applies to 1048 * notifications active at the time of retrieval. 1049 */ 1050 public static class RankingMap implements Parcelable { 1051 private final NotificationRankingUpdate mRankingUpdate; 1052 private ArrayMap<String,Integer> mRanks; 1053 private ArraySet<Object> mIntercepted; 1054 private ArrayMap<String, Integer> mVisibilityOverrides; 1055 private ArrayMap<String, Integer> mSuppressedVisualEffects; 1056 private ArrayMap<String, Integer> mImportance; 1057 private ArrayMap<String, String> mImportanceExplanation; 1058 1059 private RankingMap(NotificationRankingUpdate rankingUpdate) { 1060 mRankingUpdate = rankingUpdate; 1061 } 1062 1063 /** 1064 * Request the list of notification keys in their current ranking 1065 * order. 1066 * 1067 * @return An array of active notification keys, in their ranking order. 1068 */ 1069 public String[] getOrderedKeys() { 1070 return mRankingUpdate.getOrderedKeys(); 1071 } 1072 1073 /** 1074 * Populates outRanking with ranking information for the notification 1075 * with the given key. 1076 * 1077 * @return true if a valid key has been passed and outRanking has 1078 * been populated; false otherwise 1079 */ 1080 public boolean getRanking(String key, Ranking outRanking) { 1081 int rank = getRank(key); 1082 outRanking.populate(key, rank, isAmbient(key), !isIntercepted(key), 1083 getVisibilityOverride(key), getSuppressedVisualEffects(key), 1084 getImportance(key), getImportanceExplanation(key)); 1085 return rank >= 0; 1086 } 1087 1088 private int getRank(String key) { 1089 synchronized (this) { 1090 if (mRanks == null) { 1091 buildRanksLocked(); 1092 } 1093 } 1094 Integer rank = mRanks.get(key); 1095 return rank != null ? rank : -1; 1096 } 1097 1098 private boolean isAmbient(String key) { 1099 int firstAmbientIndex = mRankingUpdate.getFirstAmbientIndex(); 1100 if (firstAmbientIndex < 0) { 1101 return false; 1102 } 1103 int rank = getRank(key); 1104 return rank >= 0 && rank >= firstAmbientIndex; 1105 } 1106 1107 private boolean isIntercepted(String key) { 1108 synchronized (this) { 1109 if (mIntercepted == null) { 1110 buildInterceptedSetLocked(); 1111 } 1112 } 1113 return mIntercepted.contains(key); 1114 } 1115 1116 private int getVisibilityOverride(String key) { 1117 synchronized (this) { 1118 if (mVisibilityOverrides == null) { 1119 buildVisibilityOverridesLocked(); 1120 } 1121 } 1122 Integer override = mVisibilityOverrides.get(key); 1123 if (override == null) { 1124 return Ranking.VISIBILITY_NO_OVERRIDE; 1125 } 1126 return override.intValue(); 1127 } 1128 1129 private int getSuppressedVisualEffects(String key) { 1130 synchronized (this) { 1131 if (mSuppressedVisualEffects == null) { 1132 buildSuppressedVisualEffectsLocked(); 1133 } 1134 } 1135 Integer suppressed = mSuppressedVisualEffects.get(key); 1136 if (suppressed == null) { 1137 return 0; 1138 } 1139 return suppressed.intValue(); 1140 } 1141 1142 private int getImportance(String key) { 1143 synchronized (this) { 1144 if (mImportance == null) { 1145 buildImportanceLocked(); 1146 } 1147 } 1148 Integer importance = mImportance.get(key); 1149 if (importance == null) { 1150 return Ranking.IMPORTANCE_DEFAULT; 1151 } 1152 return importance.intValue(); 1153 } 1154 1155 private String getImportanceExplanation(String key) { 1156 synchronized (this) { 1157 if (mImportanceExplanation == null) { 1158 buildImportanceExplanationLocked(); 1159 } 1160 } 1161 return mImportanceExplanation.get(key); 1162 } 1163 1164 // Locked by 'this' 1165 private void buildRanksLocked() { 1166 String[] orderedKeys = mRankingUpdate.getOrderedKeys(); 1167 mRanks = new ArrayMap<>(orderedKeys.length); 1168 for (int i = 0; i < orderedKeys.length; i++) { 1169 String key = orderedKeys[i]; 1170 mRanks.put(key, i); 1171 } 1172 } 1173 1174 // Locked by 'this' 1175 private void buildInterceptedSetLocked() { 1176 String[] dndInterceptedKeys = mRankingUpdate.getInterceptedKeys(); 1177 mIntercepted = new ArraySet<>(dndInterceptedKeys.length); 1178 Collections.addAll(mIntercepted, dndInterceptedKeys); 1179 } 1180 1181 // Locked by 'this' 1182 private void buildVisibilityOverridesLocked() { 1183 Bundle visibilityBundle = mRankingUpdate.getVisibilityOverrides(); 1184 mVisibilityOverrides = new ArrayMap<>(visibilityBundle.size()); 1185 for (String key: visibilityBundle.keySet()) { 1186 mVisibilityOverrides.put(key, visibilityBundle.getInt(key)); 1187 } 1188 } 1189 1190 // Locked by 'this' 1191 private void buildSuppressedVisualEffectsLocked() { 1192 Bundle suppressedBundle = mRankingUpdate.getSuppressedVisualEffects(); 1193 mSuppressedVisualEffects = new ArrayMap<>(suppressedBundle.size()); 1194 for (String key: suppressedBundle.keySet()) { 1195 mSuppressedVisualEffects.put(key, suppressedBundle.getInt(key)); 1196 } 1197 } 1198 // Locked by 'this' 1199 private void buildImportanceLocked() { 1200 String[] orderedKeys = mRankingUpdate.getOrderedKeys(); 1201 int[] importance = mRankingUpdate.getImportance(); 1202 mImportance = new ArrayMap<>(orderedKeys.length); 1203 for (int i = 0; i < orderedKeys.length; i++) { 1204 String key = orderedKeys[i]; 1205 mImportance.put(key, importance[i]); 1206 } 1207 } 1208 1209 // Locked by 'this' 1210 private void buildImportanceExplanationLocked() { 1211 Bundle explanationBundle = mRankingUpdate.getImportanceExplanation(); 1212 mImportanceExplanation = new ArrayMap<>(explanationBundle.size()); 1213 for (String key: explanationBundle.keySet()) { 1214 mImportanceExplanation.put(key, explanationBundle.getString(key)); 1215 } 1216 } 1217 1218 // ----------- Parcelable 1219 1220 @Override 1221 public int describeContents() { 1222 return 0; 1223 } 1224 1225 @Override 1226 public void writeToParcel(Parcel dest, int flags) { 1227 dest.writeParcelable(mRankingUpdate, flags); 1228 } 1229 1230 public static final Creator<RankingMap> CREATOR = new Creator<RankingMap>() { 1231 @Override 1232 public RankingMap createFromParcel(Parcel source) { 1233 NotificationRankingUpdate rankingUpdate = source.readParcelable(null); 1234 return new RankingMap(rankingUpdate); 1235 } 1236 1237 @Override 1238 public RankingMap[] newArray(int size) { 1239 return new RankingMap[size]; 1240 } 1241 }; 1242 } 1243} 1244