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