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