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