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