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