NotificationListenerService.java revision c441856bb6c5712efab9d5ef422c95210884a1d8
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 /** 696 * Request that the listener be rebound, after a previous call to (@link requestUnbind). 697 * 698 * <P>This method will fail for listeners that have 699 * not been granted the permission by the user. 700 * 701 * <P>The service should wait for the {@link #onListenerConnected()} event 702 * before performing any operations. 703 */ 704 public static final void requestRebind(ComponentName componentName) 705 throws RemoteException { 706 INotificationManager noMan = INotificationManager.Stub.asInterface( 707 ServiceManager.getService(Context.NOTIFICATION_SERVICE)); 708 noMan.requestBindListener(componentName); 709 } 710 711 /** 712 * Request that the service be unbound. 713 * 714 * <P>This will no longer receive updates until 715 * {@link #requestRebind(ComponentName)} is called. 716 * The service will likely be kiled by the system after this call. 717 */ 718 public final void requestUnbind() throws RemoteException { 719 if (mWrapper != null) { 720 INotificationManager noMan = getNotificationInterface(); 721 noMan.requestUnbindListener(mWrapper); 722 } 723 } 724 725 /** Convert new-style Icons to legacy representations for pre-M clients. */ 726 private void createLegacyIconExtras(Notification n) { 727 Icon smallIcon = n.getSmallIcon(); 728 Icon largeIcon = n.getLargeIcon(); 729 if (smallIcon != null && smallIcon.getType() == Icon.TYPE_RESOURCE) { 730 n.extras.putInt(Notification.EXTRA_SMALL_ICON, smallIcon.getResId()); 731 n.icon = smallIcon.getResId(); 732 } 733 if (largeIcon != null) { 734 Drawable d = largeIcon.loadDrawable(getContext()); 735 if (d != null && d instanceof BitmapDrawable) { 736 final Bitmap largeIconBits = ((BitmapDrawable) d).getBitmap(); 737 n.extras.putParcelable(Notification.EXTRA_LARGE_ICON, largeIconBits); 738 n.largeIcon = largeIconBits; 739 } 740 } 741 } 742 743 /** 744 * Populates remote views for pre-N targeting apps. 745 */ 746 private void maybePopulateRemoteViews(Notification notification) { 747 if (getContext().getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.N) { 748 Builder builder = Builder.recoverBuilder(getContext(), notification); 749 notification.contentView = builder.makeContentView(); 750 notification.bigContentView = builder.makeBigContentView(); 751 notification.headsUpContentView = builder.makeHeadsUpContentView(); 752 } 753 } 754 755 /** @hide */ 756 protected class NotificationListenerWrapper extends INotificationListener.Stub { 757 @Override 758 public void onNotificationPosted(IStatusBarNotificationHolder sbnHolder, 759 NotificationRankingUpdate update) { 760 StatusBarNotification sbn; 761 try { 762 sbn = sbnHolder.get(); 763 } catch (RemoteException e) { 764 Log.w(TAG, "onNotificationPosted: Error receiving StatusBarNotification", e); 765 return; 766 } 767 768 try { 769 Notification notification = sbn.getNotification(); 770 // convert icon metadata to legacy format for older clients 771 createLegacyIconExtras(sbn.getNotification()); 772 maybePopulateRemoteViews(sbn.getNotification()); 773 } catch (IllegalArgumentException e) { 774 // warn and drop corrupt notification 775 Log.w(TAG, "onNotificationPosted: can't rebuild notification from " + 776 sbn.getPackageName()); 777 sbn = null; 778 } 779 780 // protect subclass from concurrent modifications of (@link mNotificationKeys}. 781 synchronized (mWrapper) { 782 applyUpdate(update); 783 try { 784 if (sbn != null) { 785 NotificationListenerService.this.onNotificationPosted(sbn, mRankingMap); 786 } else { 787 // still pass along the ranking map, it may contain other information 788 NotificationListenerService.this.onNotificationRankingUpdate(mRankingMap); 789 } 790 } catch (Throwable t) { 791 Log.w(TAG, "Error running onNotificationPosted", t); 792 } 793 } 794 } 795 @Override 796 public void onNotificationRemoved(IStatusBarNotificationHolder sbnHolder, 797 NotificationRankingUpdate update) { 798 StatusBarNotification sbn; 799 try { 800 sbn = sbnHolder.get(); 801 } catch (RemoteException e) { 802 Log.w(TAG, "onNotificationRemoved: Error receiving StatusBarNotification", e); 803 return; 804 } 805 // protect subclass from concurrent modifications of (@link mNotificationKeys}. 806 synchronized (mWrapper) { 807 applyUpdate(update); 808 try { 809 NotificationListenerService.this.onNotificationRemoved(sbn, mRankingMap); 810 } catch (Throwable t) { 811 Log.w(TAG, "Error running onNotificationRemoved", t); 812 } 813 } 814 } 815 @Override 816 public void onListenerConnected(NotificationRankingUpdate update) { 817 // protect subclass from concurrent modifications of (@link mNotificationKeys}. 818 synchronized (mWrapper) { 819 applyUpdate(update); 820 try { 821 NotificationListenerService.this.onListenerConnected(); 822 } catch (Throwable t) { 823 Log.w(TAG, "Error running onListenerConnected", t); 824 } 825 } 826 } 827 @Override 828 public void onNotificationRankingUpdate(NotificationRankingUpdate update) 829 throws RemoteException { 830 // protect subclass from concurrent modifications of (@link mNotificationKeys}. 831 synchronized (mWrapper) { 832 applyUpdate(update); 833 try { 834 NotificationListenerService.this.onNotificationRankingUpdate(mRankingMap); 835 } catch (Throwable t) { 836 Log.w(TAG, "Error running onNotificationRankingUpdate", t); 837 } 838 } 839 } 840 @Override 841 public void onListenerHintsChanged(int hints) throws RemoteException { 842 try { 843 NotificationListenerService.this.onListenerHintsChanged(hints); 844 } catch (Throwable t) { 845 Log.w(TAG, "Error running onListenerHintsChanged", t); 846 } 847 } 848 849 @Override 850 public void onInterruptionFilterChanged(int interruptionFilter) throws RemoteException { 851 try { 852 NotificationListenerService.this.onInterruptionFilterChanged(interruptionFilter); 853 } catch (Throwable t) { 854 Log.w(TAG, "Error running onInterruptionFilterChanged", t); 855 } 856 } 857 858 @Override 859 public void onNotificationEnqueued(IStatusBarNotificationHolder notificationHolder, 860 int importance, boolean user) throws RemoteException { 861 // no-op in the listener 862 } 863 864 @Override 865 public void onNotificationVisibilityChanged(String key, long time, boolean visible) 866 throws RemoteException { 867 // no-op in the listener 868 } 869 870 @Override 871 public void onNotificationClick(String key, long time) throws RemoteException { 872 // no-op in the listener 873 } 874 875 @Override 876 public void onNotificationActionClick(String key, long time, int actionIndex) 877 throws RemoteException { 878 // no-op in the listener 879 } 880 881 @Override 882 public void onNotificationRemovedReason(String key, long time, int reason) 883 throws RemoteException { 884 // no-op in the listener 885 } 886 } 887 888 private void applyUpdate(NotificationRankingUpdate update) { 889 mRankingMap = new RankingMap(update); 890 } 891 892 private Context getContext() { 893 if (mSystemContext != null) { 894 return mSystemContext; 895 } 896 return this; 897 } 898 899 /** 900 * Stores ranking related information on a currently active notification. 901 * 902 * <p> 903 * Ranking objects aren't automatically updated as notification events 904 * occur. Instead, ranking information has to be retrieved again via the 905 * current {@link RankingMap}. 906 */ 907 public static class Ranking { 908 /** Value signifying that the user has not expressed a per-app visibility override value. 909 * @hide */ 910 public static final int VISIBILITY_NO_OVERRIDE = -1000; 911 912 /** 913 * Value signifying that the user has not expressed an importance. 914 * 915 * This value is for persisting preferences, and should never be associated with 916 * an actual notification. 917 */ 918 public static final int IMPORTANCE_UNSPECIFIED = -1000; 919 920 /** 921 * A notification with no importance: shows nowhere, is blocked. 922 */ 923 public static final int IMPORTANCE_NONE = 0; 924 925 /** 926 * Low notification importance: only shows in the shade, below the fold. 927 */ 928 public static final int IMPORTANCE_LOW = 1; 929 930 /** 931 * Default notification importance: shows everywhere, but is not intrusive. 932 */ 933 public static final int IMPORTANCE_DEFAULT = 2; 934 935 /** 936 * Higher notification importance: shows everywhere, makes noise, 937 * but does not visually intrude. 938 */ 939 public static final int IMPORTANCE_HIGH = 3; 940 941 /** 942 * Highest notification importance: shows everywhere, makes noise, 943 * and also visually intrudes. 944 */ 945 public static final int IMPORTANCE_MAX = 4; 946 947 private String mKey; 948 private int mRank = -1; 949 private boolean mIsAmbient; 950 private boolean mMatchesInterruptionFilter; 951 private int mVisibilityOverride; 952 private int mSuppressedVisualEffects; 953 private int mImportance; 954 private CharSequence mImportanceExplanation; 955 956 public Ranking() {} 957 958 /** 959 * Returns the key of the notification this Ranking applies to. 960 */ 961 public String getKey() { 962 return mKey; 963 } 964 965 /** 966 * Returns the rank of the notification. 967 * 968 * @return the rank of the notification, that is the 0-based index in 969 * the list of active notifications. 970 */ 971 public int getRank() { 972 return mRank; 973 } 974 975 /** 976 * Returns whether the notification is an ambient notification, that is 977 * a notification that doesn't require the user's immediate attention. 978 */ 979 public boolean isAmbient() { 980 return mIsAmbient; 981 } 982 983 /** 984 * Returns the user specificed visibility for the package that posted 985 * this notification, or 986 * {@link NotificationListenerService.Ranking#VISIBILITY_NO_OVERRIDE} if 987 * no such preference has been expressed. 988 * @hide 989 */ 990 public int getVisibilityOverride() { 991 return mVisibilityOverride; 992 } 993 994 /** 995 * Returns the type(s) of visual effects that should be suppressed for this notification. 996 * See {@link #SUPPRESSED_EFFECT_LIGHTS}, {@link #SUPPRESSED_EFFECT_PEEK}, 997 * {@link #SUPPRESSED_EFFECT_SCREEN_ON}. 998 */ 999 public int getSuppressedVisualEffects() { 1000 return mSuppressedVisualEffects; 1001 } 1002 1003 /** 1004 * Returns whether the notification matches the user's interruption 1005 * filter. 1006 * 1007 * @return {@code true} if the notification is allowed by the filter, or 1008 * {@code false} if it is blocked. 1009 */ 1010 public boolean matchesInterruptionFilter() { 1011 return mMatchesInterruptionFilter; 1012 } 1013 1014 /** 1015 * Returns the importance of the notification, which dictates its 1016 * modes of presentation, see: {@link #IMPORTANCE_DEFAULT}, etc. 1017 * 1018 * @return the rank of the notification 1019 */ 1020 public int getImportance() { 1021 return mImportance; 1022 } 1023 1024 /** 1025 * If the importance has been overriden by user preference, then this will be non-null, 1026 * and should be displayed to the user. 1027 * 1028 * @return the explanation for the importance, or null if it is the natural importance 1029 */ 1030 public CharSequence getImportanceExplanation() { 1031 return mImportanceExplanation; 1032 } 1033 1034 private void populate(String key, int rank, boolean matchesInterruptionFilter, 1035 int visibilityOverride, int suppressedVisualEffects, int importance, 1036 CharSequence explanation) { 1037 mKey = key; 1038 mRank = rank; 1039 mIsAmbient = importance < IMPORTANCE_DEFAULT; 1040 mMatchesInterruptionFilter = matchesInterruptionFilter; 1041 mVisibilityOverride = visibilityOverride; 1042 mSuppressedVisualEffects = suppressedVisualEffects; 1043 mImportance = importance; 1044 mImportanceExplanation = explanation; 1045 } 1046 1047 /** 1048 * {@hide} 1049 */ 1050 public static String importanceToString(int importance) { 1051 switch (importance) { 1052 case IMPORTANCE_UNSPECIFIED: 1053 return "UNSPECIFIED"; 1054 case IMPORTANCE_NONE: 1055 return "NONE"; 1056 case IMPORTANCE_LOW: 1057 return "LOW"; 1058 case IMPORTANCE_DEFAULT: 1059 return "DEFAULT"; 1060 case IMPORTANCE_HIGH: 1061 return "HIGH"; 1062 case IMPORTANCE_MAX: 1063 return "MAX"; 1064 default: 1065 return "UNKNOWN(" + String.valueOf(importance) + ")"; 1066 } 1067 } 1068 } 1069 1070 /** 1071 * Provides access to ranking information on currently active 1072 * notifications. 1073 * 1074 * <p> 1075 * Note that this object represents a ranking snapshot that only applies to 1076 * notifications active at the time of retrieval. 1077 */ 1078 public static class RankingMap implements Parcelable { 1079 private final NotificationRankingUpdate mRankingUpdate; 1080 private ArrayMap<String,Integer> mRanks; 1081 private ArraySet<Object> mIntercepted; 1082 private ArrayMap<String, Integer> mVisibilityOverrides; 1083 private ArrayMap<String, Integer> mSuppressedVisualEffects; 1084 private ArrayMap<String, Integer> mImportance; 1085 private ArrayMap<String, String> mImportanceExplanation; 1086 1087 private RankingMap(NotificationRankingUpdate rankingUpdate) { 1088 mRankingUpdate = rankingUpdate; 1089 } 1090 1091 /** 1092 * Request the list of notification keys in their current ranking 1093 * order. 1094 * 1095 * @return An array of active notification keys, in their ranking order. 1096 */ 1097 public String[] getOrderedKeys() { 1098 return mRankingUpdate.getOrderedKeys(); 1099 } 1100 1101 /** 1102 * Populates outRanking with ranking information for the notification 1103 * with the given key. 1104 * 1105 * @return true if a valid key has been passed and outRanking has 1106 * been populated; false otherwise 1107 */ 1108 public boolean getRanking(String key, Ranking outRanking) { 1109 int rank = getRank(key); 1110 outRanking.populate(key, rank, !isIntercepted(key), 1111 getVisibilityOverride(key), getSuppressedVisualEffects(key), 1112 getImportance(key), getImportanceExplanation(key)); 1113 return rank >= 0; 1114 } 1115 1116 private int getRank(String key) { 1117 synchronized (this) { 1118 if (mRanks == null) { 1119 buildRanksLocked(); 1120 } 1121 } 1122 Integer rank = mRanks.get(key); 1123 return rank != null ? rank : -1; 1124 } 1125 1126 private boolean isIntercepted(String key) { 1127 synchronized (this) { 1128 if (mIntercepted == null) { 1129 buildInterceptedSetLocked(); 1130 } 1131 } 1132 return mIntercepted.contains(key); 1133 } 1134 1135 private int getVisibilityOverride(String key) { 1136 synchronized (this) { 1137 if (mVisibilityOverrides == null) { 1138 buildVisibilityOverridesLocked(); 1139 } 1140 } 1141 Integer override = mVisibilityOverrides.get(key); 1142 if (override == null) { 1143 return Ranking.VISIBILITY_NO_OVERRIDE; 1144 } 1145 return override.intValue(); 1146 } 1147 1148 private int getSuppressedVisualEffects(String key) { 1149 synchronized (this) { 1150 if (mSuppressedVisualEffects == null) { 1151 buildSuppressedVisualEffectsLocked(); 1152 } 1153 } 1154 Integer suppressed = mSuppressedVisualEffects.get(key); 1155 if (suppressed == null) { 1156 return 0; 1157 } 1158 return suppressed.intValue(); 1159 } 1160 1161 private int getImportance(String key) { 1162 synchronized (this) { 1163 if (mImportance == null) { 1164 buildImportanceLocked(); 1165 } 1166 } 1167 Integer importance = mImportance.get(key); 1168 if (importance == null) { 1169 return Ranking.IMPORTANCE_DEFAULT; 1170 } 1171 return importance.intValue(); 1172 } 1173 1174 private String getImportanceExplanation(String key) { 1175 synchronized (this) { 1176 if (mImportanceExplanation == null) { 1177 buildImportanceExplanationLocked(); 1178 } 1179 } 1180 return mImportanceExplanation.get(key); 1181 } 1182 1183 // Locked by 'this' 1184 private void buildRanksLocked() { 1185 String[] orderedKeys = mRankingUpdate.getOrderedKeys(); 1186 mRanks = new ArrayMap<>(orderedKeys.length); 1187 for (int i = 0; i < orderedKeys.length; i++) { 1188 String key = orderedKeys[i]; 1189 mRanks.put(key, i); 1190 } 1191 } 1192 1193 // Locked by 'this' 1194 private void buildInterceptedSetLocked() { 1195 String[] dndInterceptedKeys = mRankingUpdate.getInterceptedKeys(); 1196 mIntercepted = new ArraySet<>(dndInterceptedKeys.length); 1197 Collections.addAll(mIntercepted, dndInterceptedKeys); 1198 } 1199 1200 // Locked by 'this' 1201 private void buildVisibilityOverridesLocked() { 1202 Bundle visibilityBundle = mRankingUpdate.getVisibilityOverrides(); 1203 mVisibilityOverrides = new ArrayMap<>(visibilityBundle.size()); 1204 for (String key: visibilityBundle.keySet()) { 1205 mVisibilityOverrides.put(key, visibilityBundle.getInt(key)); 1206 } 1207 } 1208 1209 // Locked by 'this' 1210 private void buildSuppressedVisualEffectsLocked() { 1211 Bundle suppressedBundle = mRankingUpdate.getSuppressedVisualEffects(); 1212 mSuppressedVisualEffects = new ArrayMap<>(suppressedBundle.size()); 1213 for (String key: suppressedBundle.keySet()) { 1214 mSuppressedVisualEffects.put(key, suppressedBundle.getInt(key)); 1215 } 1216 } 1217 // Locked by 'this' 1218 private void buildImportanceLocked() { 1219 String[] orderedKeys = mRankingUpdate.getOrderedKeys(); 1220 int[] importance = mRankingUpdate.getImportance(); 1221 mImportance = new ArrayMap<>(orderedKeys.length); 1222 for (int i = 0; i < orderedKeys.length; i++) { 1223 String key = orderedKeys[i]; 1224 mImportance.put(key, importance[i]); 1225 } 1226 } 1227 1228 // Locked by 'this' 1229 private void buildImportanceExplanationLocked() { 1230 Bundle explanationBundle = mRankingUpdate.getImportanceExplanation(); 1231 mImportanceExplanation = new ArrayMap<>(explanationBundle.size()); 1232 for (String key: explanationBundle.keySet()) { 1233 mImportanceExplanation.put(key, explanationBundle.getString(key)); 1234 } 1235 } 1236 1237 // ----------- Parcelable 1238 1239 @Override 1240 public int describeContents() { 1241 return 0; 1242 } 1243 1244 @Override 1245 public void writeToParcel(Parcel dest, int flags) { 1246 dest.writeParcelable(mRankingUpdate, flags); 1247 } 1248 1249 public static final Creator<RankingMap> CREATOR = new Creator<RankingMap>() { 1250 @Override 1251 public RankingMap createFromParcel(Parcel source) { 1252 NotificationRankingUpdate rankingUpdate = source.readParcelable(null); 1253 return new RankingMap(rankingUpdate); 1254 } 1255 1256 @Override 1257 public RankingMap[] newArray(int size) { 1258 return new RankingMap[size]; 1259 } 1260 }; 1261 } 1262} 1263