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