NotificationManagerService.java revision 7866be2b76e421ca28e5dcbd3e7d362baf279dd9
1/* 2 * Copyright (C) 2007 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 com.android.server; 18 19import com.android.internal.statusbar.StatusBarNotification; 20import com.android.server.StatusBarManagerService; 21 22import android.app.ActivityManagerNative; 23import android.app.IActivityManager; 24import android.app.INotificationManager; 25import android.app.ITransientNotification; 26import android.app.Notification; 27import android.app.NotificationManager; 28import android.app.PendingIntent; 29import android.app.StatusBarManager; 30import android.content.BroadcastReceiver; 31import android.content.ComponentName; 32import android.content.ContentResolver; 33import android.content.Context; 34import android.content.Intent; 35import android.content.IntentFilter; 36import android.content.pm.ApplicationInfo; 37import android.content.pm.PackageManager; 38import android.content.pm.PackageManager.NameNotFoundException; 39import android.content.res.Resources; 40import android.database.ContentObserver; 41import android.hardware.usb.UsbManager; 42import android.media.AudioManager; 43import android.net.Uri; 44import android.os.BatteryManager; 45import android.os.Bundle; 46import android.os.Binder; 47import android.os.Handler; 48import android.os.IBinder; 49import android.os.Message; 50import android.os.Power; 51import android.os.Process; 52import android.os.RemoteException; 53import android.os.SystemProperties; 54import android.os.Vibrator; 55import android.provider.Settings; 56import android.telephony.TelephonyManager; 57import android.text.TextUtils; 58import android.util.EventLog; 59import android.util.Slog; 60import android.util.Log; 61import android.view.accessibility.AccessibilityEvent; 62import android.view.accessibility.AccessibilityManager; 63import android.widget.Toast; 64 65import java.io.FileDescriptor; 66import java.io.PrintWriter; 67import java.util.ArrayList; 68import java.util.Arrays; 69 70/** {@hide} */ 71public class NotificationManagerService extends INotificationManager.Stub 72{ 73 private static final String TAG = "NotificationService"; 74 private static final boolean DBG = false; 75 76 private static final int MAX_PACKAGE_NOTIFICATIONS = 50; 77 78 // message codes 79 private static final int MESSAGE_TIMEOUT = 2; 80 81 private static final int LONG_DELAY = 3500; // 3.5 seconds 82 private static final int SHORT_DELAY = 2000; // 2 seconds 83 84 private static final long[] DEFAULT_VIBRATE_PATTERN = {0, 250, 250, 250}; 85 86 private static final int DEFAULT_STREAM_TYPE = AudioManager.STREAM_NOTIFICATION; 87 88 final Context mContext; 89 final IActivityManager mAm; 90 final IBinder mForegroundToken = new Binder(); 91 92 private WorkerHandler mHandler; 93 private StatusBarManagerService mStatusBar; 94 private LightsService mLightsService; 95 private LightsService.Light mBatteryLight; 96 private LightsService.Light mNotificationLight; 97 private LightsService.Light mAttentionLight; 98 99 private int mDefaultNotificationColor; 100 private int mDefaultNotificationLedOn; 101 private int mDefaultNotificationLedOff; 102 103 private NotificationRecord mSoundNotification; 104 private NotificationPlayer mSound; 105 private boolean mSystemReady; 106 private int mDisabledNotifications; 107 108 private NotificationRecord mVibrateNotification; 109 private Vibrator mVibrator = new Vibrator(); 110 111 // for enabling and disabling notification pulse behavior 112 private boolean mScreenOn = true; 113 private boolean mInCall = false; 114 private boolean mNotificationPulseEnabled; 115 // This is true if we have received a new notification while the screen is off 116 // (that is, if mLedNotification was set while the screen was off) 117 // This is reset to false when the screen is turned on. 118 private boolean mPendingPulseNotification; 119 120 // for adb connected notifications 121 private boolean mAdbNotificationShown = false; 122 private Notification mAdbNotification; 123 124 private final ArrayList<NotificationRecord> mNotificationList = 125 new ArrayList<NotificationRecord>(); 126 127 private ArrayList<ToastRecord> mToastQueue; 128 129 private ArrayList<NotificationRecord> mLights = new ArrayList<NotificationRecord>(); 130 131 private boolean mBatteryCharging; 132 private boolean mBatteryLow; 133 private boolean mBatteryFull; 134 private NotificationRecord mLedNotification; 135 136 private static int mBatteryLowARGB; 137 private static int mBatteryMediumARGB; 138 private static int mBatteryFullARGB; 139 private static int mBatteryLedOn; 140 private static int mBatteryLedOff; 141 142 private static String idDebugString(Context baseContext, String packageName, int id) { 143 Context c = null; 144 145 if (packageName != null) { 146 try { 147 c = baseContext.createPackageContext(packageName, 0); 148 } catch (NameNotFoundException e) { 149 c = baseContext; 150 } 151 } else { 152 c = baseContext; 153 } 154 155 String pkg; 156 String type; 157 String name; 158 159 Resources r = c.getResources(); 160 try { 161 return r.getResourceName(id); 162 } catch (Resources.NotFoundException e) { 163 return "<name unknown>"; 164 } 165 } 166 167 private static final class NotificationRecord 168 { 169 final String pkg; 170 final String tag; 171 final int id; 172 final int uid; 173 final int initialPid; 174 ITransientNotification callback; 175 int duration; 176 final Notification notification; 177 IBinder statusBarKey; 178 179 NotificationRecord(String pkg, String tag, int id, int uid, int initialPid, 180 Notification notification) 181 { 182 this.pkg = pkg; 183 this.tag = tag; 184 this.id = id; 185 this.uid = uid; 186 this.initialPid = initialPid; 187 this.notification = notification; 188 } 189 190 void dump(PrintWriter pw, String prefix, Context baseContext) { 191 pw.println(prefix + this); 192 pw.println(prefix + " icon=0x" + Integer.toHexString(notification.icon) 193 + " / " + idDebugString(baseContext, this.pkg, notification.icon)); 194 pw.println(prefix + " contentIntent=" + notification.contentIntent); 195 pw.println(prefix + " deleteIntent=" + notification.deleteIntent); 196 pw.println(prefix + " tickerText=" + notification.tickerText); 197 pw.println(prefix + " contentView=" + notification.contentView); 198 pw.println(prefix + " defaults=0x" + Integer.toHexString(notification.defaults)); 199 pw.println(prefix + " flags=0x" + Integer.toHexString(notification.flags)); 200 pw.println(prefix + " sound=" + notification.sound); 201 pw.println(prefix + " vibrate=" + Arrays.toString(notification.vibrate)); 202 pw.println(prefix + " ledARGB=0x" + Integer.toHexString(notification.ledARGB) 203 + " ledOnMS=" + notification.ledOnMS 204 + " ledOffMS=" + notification.ledOffMS); 205 } 206 207 @Override 208 public final String toString() 209 { 210 return "NotificationRecord{" 211 + Integer.toHexString(System.identityHashCode(this)) 212 + " pkg=" + pkg 213 + " id=" + Integer.toHexString(id) 214 + " tag=" + tag + "}"; 215 } 216 } 217 218 private static final class ToastRecord 219 { 220 final int pid; 221 final String pkg; 222 final ITransientNotification callback; 223 int duration; 224 225 ToastRecord(int pid, String pkg, ITransientNotification callback, int duration) 226 { 227 this.pid = pid; 228 this.pkg = pkg; 229 this.callback = callback; 230 this.duration = duration; 231 } 232 233 void update(int duration) { 234 this.duration = duration; 235 } 236 237 void dump(PrintWriter pw, String prefix) { 238 pw.println(prefix + this); 239 } 240 241 @Override 242 public final String toString() 243 { 244 return "ToastRecord{" 245 + Integer.toHexString(System.identityHashCode(this)) 246 + " pkg=" + pkg 247 + " callback=" + callback 248 + " duration=" + duration; 249 } 250 } 251 252 private StatusBarManagerService.NotificationCallbacks mNotificationCallbacks 253 = new StatusBarManagerService.NotificationCallbacks() { 254 255 public void onSetDisabled(int status) { 256 synchronized (mNotificationList) { 257 mDisabledNotifications = status; 258 if ((mDisabledNotifications & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) { 259 // cancel whatever's going on 260 long identity = Binder.clearCallingIdentity(); 261 try { 262 mSound.stop(); 263 } 264 finally { 265 Binder.restoreCallingIdentity(identity); 266 } 267 268 identity = Binder.clearCallingIdentity(); 269 try { 270 mVibrator.cancel(); 271 } 272 finally { 273 Binder.restoreCallingIdentity(identity); 274 } 275 } 276 } 277 } 278 279 public void onClearAll() { 280 cancelAll(); 281 } 282 283 public void onNotificationClick(String pkg, String tag, int id) { 284 cancelNotification(pkg, tag, id, Notification.FLAG_AUTO_CANCEL, 285 Notification.FLAG_FOREGROUND_SERVICE); 286 } 287 288 public void onPanelRevealed() { 289 synchronized (mNotificationList) { 290 // sound 291 mSoundNotification = null; 292 long identity = Binder.clearCallingIdentity(); 293 try { 294 mSound.stop(); 295 } 296 finally { 297 Binder.restoreCallingIdentity(identity); 298 } 299 300 // vibrate 301 mVibrateNotification = null; 302 identity = Binder.clearCallingIdentity(); 303 try { 304 mVibrator.cancel(); 305 } 306 finally { 307 Binder.restoreCallingIdentity(identity); 308 } 309 310 // light 311 mLights.clear(); 312 mLedNotification = null; 313 updateLightsLocked(); 314 } 315 } 316 317 public void onNotificationError(String pkg, String tag, int id, 318 int uid, int initialPid, String message) { 319 Slog.d(TAG, "onNotification error pkg=" + pkg + " tag=" + tag + " id=" + id 320 + "; will crashApplication(uid=" + uid + ", pid=" + initialPid + ")"); 321 cancelNotification(pkg, tag, id, 0, 0); 322 long ident = Binder.clearCallingIdentity(); 323 try { 324 ActivityManagerNative.getDefault().crashApplication(uid, initialPid, pkg, 325 "Bad notification posted from package " + pkg 326 + ": " + message); 327 } catch (RemoteException e) { 328 } 329 Binder.restoreCallingIdentity(ident); 330 } 331 }; 332 333 private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() { 334 @Override 335 public void onReceive(Context context, Intent intent) { 336 String action = intent.getAction(); 337 338 boolean queryRestart = false; 339 340 if (action.equals(Intent.ACTION_BATTERY_CHANGED)) { 341 boolean batteryCharging = (intent.getIntExtra("plugged", 0) != 0); 342 int level = intent.getIntExtra("level", -1); 343 boolean batteryLow = (level >= 0 && level <= Power.LOW_BATTERY_THRESHOLD); 344 int status = intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN); 345 boolean batteryFull = (status == BatteryManager.BATTERY_STATUS_FULL || level >= 90); 346 347 if (batteryCharging != mBatteryCharging || 348 batteryLow != mBatteryLow || 349 batteryFull != mBatteryFull) { 350 mBatteryCharging = batteryCharging; 351 mBatteryLow = batteryLow; 352 mBatteryFull = batteryFull; 353 updateLights(); 354 } 355 } else if (action.equals(UsbManager.ACTION_USB_STATE)) { 356 Bundle extras = intent.getExtras(); 357 boolean usbConnected = extras.getBoolean(UsbManager.USB_CONNECTED); 358 boolean adbEnabled = (UsbManager.USB_FUNCTION_ENABLED.equals( 359 extras.getString(UsbManager.USB_FUNCTION_ADB))); 360 updateAdbNotification(usbConnected && adbEnabled); 361 } else if (action.equals(Intent.ACTION_PACKAGE_REMOVED) 362 || action.equals(Intent.ACTION_PACKAGE_RESTARTED) 363 || (queryRestart=action.equals(Intent.ACTION_QUERY_PACKAGE_RESTART)) 364 || action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)) { 365 String pkgList[] = null; 366 if (action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)) { 367 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); 368 } else if (queryRestart) { 369 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES); 370 } else { 371 Uri uri = intent.getData(); 372 if (uri == null) { 373 return; 374 } 375 String pkgName = uri.getSchemeSpecificPart(); 376 if (pkgName == null) { 377 return; 378 } 379 pkgList = new String[]{pkgName}; 380 } 381 if (pkgList != null && (pkgList.length > 0)) { 382 for (String pkgName : pkgList) { 383 cancelAllNotificationsInt(pkgName, 0, 0, !queryRestart); 384 } 385 } 386 } else if (action.equals(Intent.ACTION_SCREEN_ON)) { 387 mScreenOn = true; 388 updateNotificationPulse(); 389 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) { 390 mScreenOn = false; 391 updateNotificationPulse(); 392 } else if (action.equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) { 393 mInCall = (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK)); 394 updateNotificationPulse(); 395 } 396 } 397 }; 398 399 class SettingsObserver extends ContentObserver { 400 SettingsObserver(Handler handler) { 401 super(handler); 402 } 403 404 void observe() { 405 ContentResolver resolver = mContext.getContentResolver(); 406 resolver.registerContentObserver(Settings.System.getUriFor( 407 Settings.System.NOTIFICATION_LIGHT_PULSE), false, this); 408 update(); 409 } 410 411 @Override public void onChange(boolean selfChange) { 412 update(); 413 } 414 415 public void update() { 416 ContentResolver resolver = mContext.getContentResolver(); 417 boolean pulseEnabled = Settings.System.getInt(resolver, 418 Settings.System.NOTIFICATION_LIGHT_PULSE, 0) != 0; 419 if (mNotificationPulseEnabled != pulseEnabled) { 420 mNotificationPulseEnabled = pulseEnabled; 421 updateNotificationPulse(); 422 } 423 } 424 } 425 426 NotificationManagerService(Context context, StatusBarManagerService statusBar, 427 LightsService lights) 428 { 429 super(); 430 mContext = context; 431 mLightsService = lights; 432 mAm = ActivityManagerNative.getDefault(); 433 mSound = new NotificationPlayer(TAG); 434 mSound.setUsesWakeLock(context); 435 mToastQueue = new ArrayList<ToastRecord>(); 436 mHandler = new WorkerHandler(); 437 438 mStatusBar = statusBar; 439 statusBar.setNotificationCallbacks(mNotificationCallbacks); 440 441 mBatteryLight = lights.getLight(LightsService.LIGHT_ID_BATTERY); 442 mNotificationLight = lights.getLight(LightsService.LIGHT_ID_NOTIFICATIONS); 443 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION); 444 445 Resources resources = mContext.getResources(); 446 mDefaultNotificationColor = resources.getColor( 447 com.android.internal.R.color.config_defaultNotificationColor); 448 mDefaultNotificationLedOn = resources.getInteger( 449 com.android.internal.R.integer.config_defaultNotificationLedOn); 450 mDefaultNotificationLedOff = resources.getInteger( 451 com.android.internal.R.integer.config_defaultNotificationLedOff); 452 453 mBatteryLowARGB = mContext.getResources().getInteger( 454 com.android.internal.R.integer.config_notificationsBatteryLowARGB); 455 mBatteryMediumARGB = mContext.getResources().getInteger( 456 com.android.internal.R.integer.config_notificationsBatteryMediumARGB); 457 mBatteryFullARGB = mContext.getResources().getInteger( 458 com.android.internal.R.integer.config_notificationsBatteryFullARGB); 459 mBatteryLedOn = mContext.getResources().getInteger( 460 com.android.internal.R.integer.config_notificationsBatteryLedOn); 461 mBatteryLedOff = mContext.getResources().getInteger( 462 com.android.internal.R.integer.config_notificationsBatteryLedOff); 463 464 // Don't start allowing notifications until the setup wizard has run once. 465 // After that, including subsequent boots, init with notifications turned on. 466 // This works on the first boot because the setup wizard will toggle this 467 // flag at least once and we'll go back to 0 after that. 468 if (0 == Settings.Secure.getInt(mContext.getContentResolver(), 469 Settings.Secure.DEVICE_PROVISIONED, 0)) { 470 mDisabledNotifications = StatusBarManager.DISABLE_NOTIFICATION_ALERTS; 471 } 472 473 // register for battery changed notifications 474 IntentFilter filter = new IntentFilter(); 475 filter.addAction(Intent.ACTION_BATTERY_CHANGED); 476 filter.addAction(UsbManager.ACTION_USB_STATE); 477 filter.addAction(Intent.ACTION_SCREEN_ON); 478 filter.addAction(Intent.ACTION_SCREEN_OFF); 479 filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED); 480 mContext.registerReceiver(mIntentReceiver, filter); 481 IntentFilter pkgFilter = new IntentFilter(); 482 pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); 483 pkgFilter.addAction(Intent.ACTION_PACKAGE_RESTARTED); 484 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART); 485 pkgFilter.addDataScheme("package"); 486 mContext.registerReceiver(mIntentReceiver, pkgFilter); 487 IntentFilter sdFilter = new IntentFilter(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE); 488 mContext.registerReceiver(mIntentReceiver, sdFilter); 489 490 SettingsObserver observer = new SettingsObserver(mHandler); 491 observer.observe(); 492 } 493 494 void systemReady() { 495 // no beeping until we're basically done booting 496 mSystemReady = true; 497 } 498 499 // Toasts 500 // ============================================================================ 501 public void enqueueToast(String pkg, ITransientNotification callback, int duration) 502 { 503 if (DBG) Slog.i(TAG, "enqueueToast pkg=" + pkg + " callback=" + callback + " duration=" + duration); 504 505 if (pkg == null || callback == null) { 506 Slog.e(TAG, "Not doing toast. pkg=" + pkg + " callback=" + callback); 507 return ; 508 } 509 510 synchronized (mToastQueue) { 511 int callingPid = Binder.getCallingPid(); 512 long callingId = Binder.clearCallingIdentity(); 513 try { 514 ToastRecord record; 515 int index = indexOfToastLocked(pkg, callback); 516 // If it's already in the queue, we update it in place, we don't 517 // move it to the end of the queue. 518 if (index >= 0) { 519 record = mToastQueue.get(index); 520 record.update(duration); 521 } else { 522 record = new ToastRecord(callingPid, pkg, callback, duration); 523 mToastQueue.add(record); 524 index = mToastQueue.size() - 1; 525 keepProcessAliveLocked(callingPid); 526 } 527 // If it's at index 0, it's the current toast. It doesn't matter if it's 528 // new or just been updated. Call back and tell it to show itself. 529 // If the callback fails, this will remove it from the list, so don't 530 // assume that it's valid after this. 531 if (index == 0) { 532 showNextToastLocked(); 533 } 534 } finally { 535 Binder.restoreCallingIdentity(callingId); 536 } 537 } 538 } 539 540 public void cancelToast(String pkg, ITransientNotification callback) { 541 Slog.i(TAG, "cancelToast pkg=" + pkg + " callback=" + callback); 542 543 if (pkg == null || callback == null) { 544 Slog.e(TAG, "Not cancelling notification. pkg=" + pkg + " callback=" + callback); 545 return ; 546 } 547 548 synchronized (mToastQueue) { 549 long callingId = Binder.clearCallingIdentity(); 550 try { 551 int index = indexOfToastLocked(pkg, callback); 552 if (index >= 0) { 553 cancelToastLocked(index); 554 } else { 555 Slog.w(TAG, "Toast already cancelled. pkg=" + pkg + " callback=" + callback); 556 } 557 } finally { 558 Binder.restoreCallingIdentity(callingId); 559 } 560 } 561 } 562 563 private void showNextToastLocked() { 564 ToastRecord record = mToastQueue.get(0); 565 while (record != null) { 566 if (DBG) Slog.d(TAG, "Show pkg=" + record.pkg + " callback=" + record.callback); 567 try { 568 record.callback.show(); 569 scheduleTimeoutLocked(record, false); 570 return; 571 } catch (RemoteException e) { 572 Slog.w(TAG, "Object died trying to show notification " + record.callback 573 + " in package " + record.pkg); 574 // remove it from the list and let the process die 575 int index = mToastQueue.indexOf(record); 576 if (index >= 0) { 577 mToastQueue.remove(index); 578 } 579 keepProcessAliveLocked(record.pid); 580 if (mToastQueue.size() > 0) { 581 record = mToastQueue.get(0); 582 } else { 583 record = null; 584 } 585 } 586 } 587 } 588 589 private void cancelToastLocked(int index) { 590 ToastRecord record = mToastQueue.get(index); 591 try { 592 record.callback.hide(); 593 } catch (RemoteException e) { 594 Slog.w(TAG, "Object died trying to hide notification " + record.callback 595 + " in package " + record.pkg); 596 // don't worry about this, we're about to remove it from 597 // the list anyway 598 } 599 mToastQueue.remove(index); 600 keepProcessAliveLocked(record.pid); 601 if (mToastQueue.size() > 0) { 602 // Show the next one. If the callback fails, this will remove 603 // it from the list, so don't assume that the list hasn't changed 604 // after this point. 605 showNextToastLocked(); 606 } 607 } 608 609 private void scheduleTimeoutLocked(ToastRecord r, boolean immediate) 610 { 611 Message m = Message.obtain(mHandler, MESSAGE_TIMEOUT, r); 612 long delay = immediate ? 0 : (r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY); 613 mHandler.removeCallbacksAndMessages(r); 614 mHandler.sendMessageDelayed(m, delay); 615 } 616 617 private void handleTimeout(ToastRecord record) 618 { 619 if (DBG) Slog.d(TAG, "Timeout pkg=" + record.pkg + " callback=" + record.callback); 620 synchronized (mToastQueue) { 621 int index = indexOfToastLocked(record.pkg, record.callback); 622 if (index >= 0) { 623 cancelToastLocked(index); 624 } 625 } 626 } 627 628 // lock on mToastQueue 629 private int indexOfToastLocked(String pkg, ITransientNotification callback) 630 { 631 IBinder cbak = callback.asBinder(); 632 ArrayList<ToastRecord> list = mToastQueue; 633 int len = list.size(); 634 for (int i=0; i<len; i++) { 635 ToastRecord r = list.get(i); 636 if (r.pkg.equals(pkg) && r.callback.asBinder() == cbak) { 637 return i; 638 } 639 } 640 return -1; 641 } 642 643 // lock on mToastQueue 644 private void keepProcessAliveLocked(int pid) 645 { 646 int toastCount = 0; // toasts from this pid 647 ArrayList<ToastRecord> list = mToastQueue; 648 int N = list.size(); 649 for (int i=0; i<N; i++) { 650 ToastRecord r = list.get(i); 651 if (r.pid == pid) { 652 toastCount++; 653 } 654 } 655 try { 656 mAm.setProcessForeground(mForegroundToken, pid, toastCount > 0); 657 } catch (RemoteException e) { 658 // Shouldn't happen. 659 } 660 } 661 662 private final class WorkerHandler extends Handler 663 { 664 @Override 665 public void handleMessage(Message msg) 666 { 667 switch (msg.what) 668 { 669 case MESSAGE_TIMEOUT: 670 handleTimeout((ToastRecord)msg.obj); 671 break; 672 } 673 } 674 } 675 676 677 // Notifications 678 // ============================================================================ 679 public void enqueueNotification(String pkg, int id, Notification notification, int[] idOut) 680 { 681 enqueueNotificationWithTag(pkg, null /* tag */, id, notification, idOut); 682 } 683 684 public void enqueueNotificationWithTag(String pkg, String tag, int id, Notification notification, 685 int[] idOut) 686 { 687 enqueueNotificationInternal(pkg, Binder.getCallingUid(), Binder.getCallingPid(), 688 tag, id, notification, idOut); 689 } 690 691 // Not exposed via Binder; for system use only (otherwise malicious apps could spoof the 692 // uid/pid of another application) 693 public void enqueueNotificationInternal(String pkg, int callingUid, int callingPid, 694 String tag, int id, Notification notification, int[] idOut) 695 { 696 checkIncomingCall(pkg); 697 698 // Limit the number of notifications that any given package except the android 699 // package can enqueue. Prevents DOS attacks and deals with leaks. 700 if (!"android".equals(pkg)) { 701 synchronized (mNotificationList) { 702 int count = 0; 703 final int N = mNotificationList.size(); 704 for (int i=0; i<N; i++) { 705 final NotificationRecord r = mNotificationList.get(i); 706 if (r.pkg.equals(pkg)) { 707 count++; 708 if (count >= MAX_PACKAGE_NOTIFICATIONS) { 709 Slog.e(TAG, "Package has already posted " + count 710 + " notifications. Not showing more. package=" + pkg); 711 return; 712 } 713 } 714 } 715 } 716 } 717 718 // This conditional is a dirty hack to limit the logging done on 719 // behalf of the download manager without affecting other apps. 720 if (!pkg.equals("com.android.providers.downloads") 721 || Log.isLoggable("DownloadManager", Log.VERBOSE)) { 722 EventLog.writeEvent(EventLogTags.NOTIFICATION_ENQUEUE, pkg, id, notification.toString()); 723 } 724 725 if (pkg == null || notification == null) { 726 throw new IllegalArgumentException("null not allowed: pkg=" + pkg 727 + " id=" + id + " notification=" + notification); 728 } 729 if (notification.icon != 0) { 730 if (notification.contentView == null) { 731 throw new IllegalArgumentException("contentView required: pkg=" + pkg 732 + " id=" + id + " notification=" + notification); 733 } 734 if (notification.contentIntent == null) { 735 throw new IllegalArgumentException("contentIntent required: pkg=" + pkg 736 + " id=" + id + " notification=" + notification); 737 } 738 } 739 740 synchronized (mNotificationList) { 741 NotificationRecord r = new NotificationRecord(pkg, tag, id, 742 callingUid, callingPid, notification); 743 NotificationRecord old = null; 744 745 int index = indexOfNotificationLocked(pkg, tag, id); 746 if (index < 0) { 747 mNotificationList.add(r); 748 } else { 749 old = mNotificationList.remove(index); 750 mNotificationList.add(index, r); 751 // Make sure we don't lose the foreground service state. 752 if (old != null) { 753 notification.flags |= 754 old.notification.flags&Notification.FLAG_FOREGROUND_SERVICE; 755 } 756 } 757 758 // Ensure if this is a foreground service that the proper additional 759 // flags are set. 760 if ((notification.flags&Notification.FLAG_FOREGROUND_SERVICE) != 0) { 761 notification.flags |= Notification.FLAG_ONGOING_EVENT 762 | Notification.FLAG_NO_CLEAR; 763 } 764 765 if (notification.icon != 0) { 766 StatusBarNotification n = new StatusBarNotification(pkg, id, tag, 767 r.uid, r.initialPid, notification); 768 if (old != null && old.statusBarKey != null) { 769 r.statusBarKey = old.statusBarKey; 770 long identity = Binder.clearCallingIdentity(); 771 try { 772 mStatusBar.updateNotification(r.statusBarKey, n); 773 } 774 finally { 775 Binder.restoreCallingIdentity(identity); 776 } 777 } else { 778 long identity = Binder.clearCallingIdentity(); 779 try { 780 r.statusBarKey = mStatusBar.addNotification(n); 781 mAttentionLight.pulse(); 782 } 783 finally { 784 Binder.restoreCallingIdentity(identity); 785 } 786 } 787 sendAccessibilityEvent(notification, pkg); 788 } else { 789 if (old != null && old.statusBarKey != null) { 790 long identity = Binder.clearCallingIdentity(); 791 try { 792 mStatusBar.removeNotification(old.statusBarKey); 793 } 794 finally { 795 Binder.restoreCallingIdentity(identity); 796 } 797 } 798 } 799 800 // If we're not supposed to beep, vibrate, etc. then don't. 801 if (((mDisabledNotifications & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) == 0) 802 && (!(old != null 803 && (notification.flags & Notification.FLAG_ONLY_ALERT_ONCE) != 0 )) 804 && mSystemReady) { 805 806 final AudioManager audioManager = (AudioManager) mContext 807 .getSystemService(Context.AUDIO_SERVICE); 808 // sound 809 final boolean useDefaultSound = 810 (notification.defaults & Notification.DEFAULT_SOUND) != 0; 811 if (useDefaultSound || notification.sound != null) { 812 Uri uri; 813 if (useDefaultSound) { 814 uri = Settings.System.DEFAULT_NOTIFICATION_URI; 815 } else { 816 uri = notification.sound; 817 } 818 boolean looping = (notification.flags & Notification.FLAG_INSISTENT) != 0; 819 int audioStreamType; 820 if (notification.audioStreamType >= 0) { 821 audioStreamType = notification.audioStreamType; 822 } else { 823 audioStreamType = DEFAULT_STREAM_TYPE; 824 } 825 mSoundNotification = r; 826 // do not play notifications if stream volume is 0 827 // (typically because ringer mode is silent). 828 if (audioManager.getStreamVolume(audioStreamType) != 0) { 829 long identity = Binder.clearCallingIdentity(); 830 try { 831 mSound.play(mContext, uri, looping, audioStreamType); 832 } 833 finally { 834 Binder.restoreCallingIdentity(identity); 835 } 836 } 837 } 838 839 // vibrate 840 final boolean useDefaultVibrate = 841 (notification.defaults & Notification.DEFAULT_VIBRATE) != 0; 842 if ((useDefaultVibrate || notification.vibrate != null) 843 && audioManager.shouldVibrate(AudioManager.VIBRATE_TYPE_NOTIFICATION)) { 844 mVibrateNotification = r; 845 846 mVibrator.vibrate(useDefaultVibrate ? DEFAULT_VIBRATE_PATTERN 847 : notification.vibrate, 848 ((notification.flags & Notification.FLAG_INSISTENT) != 0) ? 0: -1); 849 } 850 } 851 852 // this option doesn't shut off the lights 853 854 // light 855 // the most recent thing gets the light 856 mLights.remove(old); 857 if (mLedNotification == old) { 858 mLedNotification = null; 859 } 860 //Slog.i(TAG, "notification.lights=" 861 // + ((old.notification.lights.flags & Notification.FLAG_SHOW_LIGHTS) != 0)); 862 if ((notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0) { 863 mLights.add(r); 864 updateLightsLocked(); 865 } else { 866 if (old != null 867 && ((old.notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0)) { 868 updateLightsLocked(); 869 } 870 } 871 } 872 873 idOut[0] = id; 874 } 875 876 private void sendAccessibilityEvent(Notification notification, CharSequence packageName) { 877 AccessibilityManager manager = AccessibilityManager.getInstance(mContext); 878 if (!manager.isEnabled()) { 879 return; 880 } 881 882 AccessibilityEvent event = 883 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED); 884 event.setPackageName(packageName); 885 event.setClassName(Notification.class.getName()); 886 event.setParcelableData(notification); 887 CharSequence tickerText = notification.tickerText; 888 if (!TextUtils.isEmpty(tickerText)) { 889 event.getText().add(tickerText); 890 } 891 892 manager.sendAccessibilityEvent(event); 893 } 894 895 private void cancelNotificationLocked(NotificationRecord r) { 896 // status bar 897 if (r.notification.icon != 0) { 898 long identity = Binder.clearCallingIdentity(); 899 try { 900 mStatusBar.removeNotification(r.statusBarKey); 901 } 902 finally { 903 Binder.restoreCallingIdentity(identity); 904 } 905 r.statusBarKey = null; 906 } 907 908 // sound 909 if (mSoundNotification == r) { 910 mSoundNotification = null; 911 long identity = Binder.clearCallingIdentity(); 912 try { 913 mSound.stop(); 914 } 915 finally { 916 Binder.restoreCallingIdentity(identity); 917 } 918 } 919 920 // vibrate 921 if (mVibrateNotification == r) { 922 mVibrateNotification = null; 923 long identity = Binder.clearCallingIdentity(); 924 try { 925 mVibrator.cancel(); 926 } 927 finally { 928 Binder.restoreCallingIdentity(identity); 929 } 930 } 931 932 // light 933 mLights.remove(r); 934 if (mLedNotification == r) { 935 mLedNotification = null; 936 } 937 } 938 939 /** 940 * Cancels a notification ONLY if it has all of the {@code mustHaveFlags} 941 * and none of the {@code mustNotHaveFlags}. 942 */ 943 private void cancelNotification(String pkg, String tag, int id, int mustHaveFlags, 944 int mustNotHaveFlags) { 945 EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL, pkg, id, mustHaveFlags); 946 947 synchronized (mNotificationList) { 948 int index = indexOfNotificationLocked(pkg, tag, id); 949 if (index >= 0) { 950 NotificationRecord r = mNotificationList.get(index); 951 952 if ((r.notification.flags & mustHaveFlags) != mustHaveFlags) { 953 return; 954 } 955 if ((r.notification.flags & mustNotHaveFlags) != 0) { 956 return; 957 } 958 959 mNotificationList.remove(index); 960 961 cancelNotificationLocked(r); 962 updateLightsLocked(); 963 } 964 } 965 } 966 967 /** 968 * Cancels all notifications from a given package that have all of the 969 * {@code mustHaveFlags}. 970 */ 971 boolean cancelAllNotificationsInt(String pkg, int mustHaveFlags, 972 int mustNotHaveFlags, boolean doit) { 973 EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL_ALL, pkg, mustHaveFlags); 974 975 synchronized (mNotificationList) { 976 final int N = mNotificationList.size(); 977 boolean canceledSomething = false; 978 for (int i = N-1; i >= 0; --i) { 979 NotificationRecord r = mNotificationList.get(i); 980 if ((r.notification.flags & mustHaveFlags) != mustHaveFlags) { 981 continue; 982 } 983 if ((r.notification.flags & mustNotHaveFlags) != 0) { 984 continue; 985 } 986 if (!r.pkg.equals(pkg)) { 987 continue; 988 } 989 canceledSomething = true; 990 if (!doit) { 991 return true; 992 } 993 mNotificationList.remove(i); 994 cancelNotificationLocked(r); 995 } 996 if (canceledSomething) { 997 updateLightsLocked(); 998 } 999 return canceledSomething; 1000 } 1001 } 1002 1003 1004 public void cancelNotification(String pkg, int id) { 1005 cancelNotificationWithTag(pkg, null /* tag */, id); 1006 } 1007 1008 public void cancelNotificationWithTag(String pkg, String tag, int id) { 1009 checkIncomingCall(pkg); 1010 // Don't allow client applications to cancel foreground service notis. 1011 cancelNotification(pkg, tag, id, 0, 1012 Binder.getCallingUid() == Process.SYSTEM_UID 1013 ? 0 : Notification.FLAG_FOREGROUND_SERVICE); 1014 } 1015 1016 public void cancelAllNotifications(String pkg) { 1017 checkIncomingCall(pkg); 1018 1019 // Calling from user space, don't allow the canceling of actively 1020 // running foreground services. 1021 cancelAllNotificationsInt(pkg, 0, Notification.FLAG_FOREGROUND_SERVICE, true); 1022 } 1023 1024 void checkIncomingCall(String pkg) { 1025 int uid = Binder.getCallingUid(); 1026 if (uid == Process.SYSTEM_UID || uid == 0) { 1027 return; 1028 } 1029 try { 1030 ApplicationInfo ai = mContext.getPackageManager().getApplicationInfo( 1031 pkg, 0); 1032 if (ai.uid != uid) { 1033 throw new SecurityException("Calling uid " + uid + " gave package" 1034 + pkg + " which is owned by uid " + ai.uid); 1035 } 1036 } catch (PackageManager.NameNotFoundException e) { 1037 throw new SecurityException("Unknown package " + pkg); 1038 } 1039 } 1040 1041 void cancelAll() { 1042 synchronized (mNotificationList) { 1043 final int N = mNotificationList.size(); 1044 for (int i=N-1; i>=0; i--) { 1045 NotificationRecord r = mNotificationList.get(i); 1046 1047 if ((r.notification.flags & (Notification.FLAG_ONGOING_EVENT 1048 | Notification.FLAG_NO_CLEAR)) == 0) { 1049 if (r.notification.deleteIntent != null) { 1050 try { 1051 r.notification.deleteIntent.send(); 1052 } catch (PendingIntent.CanceledException ex) { 1053 // do nothing - there's no relevant way to recover, and 1054 // no reason to let this propagate 1055 Slog.w(TAG, "canceled PendingIntent for " + r.pkg, ex); 1056 } 1057 } 1058 mNotificationList.remove(i); 1059 cancelNotificationLocked(r); 1060 } 1061 } 1062 1063 updateLightsLocked(); 1064 } 1065 } 1066 1067 private void updateLights() { 1068 synchronized (mNotificationList) { 1069 updateLightsLocked(); 1070 } 1071 } 1072 1073 // lock on mNotificationList 1074 private void updateLightsLocked() 1075 { 1076 // Battery low always shows, other states only show if charging. 1077 if (mBatteryLow) { 1078 if (mBatteryCharging) { 1079 mBatteryLight.setColor(mBatteryLowARGB); 1080 } else { 1081 // Flash when battery is low and not charging 1082 mBatteryLight.setFlashing(mBatteryLowARGB, LightsService.LIGHT_FLASH_TIMED, 1083 mBatteryLedOn, mBatteryLedOff); 1084 } 1085 } else if (mBatteryCharging) { 1086 if (mBatteryFull) { 1087 mBatteryLight.setColor(mBatteryFullARGB); 1088 } else { 1089 mBatteryLight.setColor(mBatteryMediumARGB); 1090 } 1091 } else { 1092 mBatteryLight.turnOff(); 1093 } 1094 1095 // clear pending pulse notification if screen is on 1096 if (mScreenOn || mLedNotification == null) { 1097 mPendingPulseNotification = false; 1098 } 1099 1100 // handle notification lights 1101 if (mLedNotification == null) { 1102 // get next notification, if any 1103 int n = mLights.size(); 1104 if (n > 0) { 1105 mLedNotification = mLights.get(n-1); 1106 } 1107 if (mLedNotification != null && !mScreenOn) { 1108 mPendingPulseNotification = true; 1109 } 1110 } 1111 1112 // we only flash if screen is off and persistent pulsing is enabled 1113 // and we are not currently in a call 1114 if (!mPendingPulseNotification || mScreenOn || mInCall) { 1115 mNotificationLight.turnOff(); 1116 } else { 1117 int ledARGB = mLedNotification.notification.ledARGB; 1118 int ledOnMS = mLedNotification.notification.ledOnMS; 1119 int ledOffMS = mLedNotification.notification.ledOffMS; 1120 if ((mLedNotification.notification.defaults & Notification.DEFAULT_LIGHTS) != 0) { 1121 ledARGB = mDefaultNotificationColor; 1122 ledOnMS = mDefaultNotificationLedOn; 1123 ledOffMS = mDefaultNotificationLedOff; 1124 } 1125 if (mNotificationPulseEnabled) { 1126 // pulse repeatedly 1127 mNotificationLight.setFlashing(ledARGB, LightsService.LIGHT_FLASH_TIMED, 1128 ledOnMS, ledOffMS); 1129 } else { 1130 // pulse only once 1131 mNotificationLight.pulse(ledARGB, ledOnMS); 1132 } 1133 } 1134 } 1135 1136 // lock on mNotificationList 1137 private int indexOfNotificationLocked(String pkg, String tag, int id) 1138 { 1139 ArrayList<NotificationRecord> list = mNotificationList; 1140 final int len = list.size(); 1141 for (int i=0; i<len; i++) { 1142 NotificationRecord r = list.get(i); 1143 if (tag == null) { 1144 if (r.tag != null) { 1145 continue; 1146 } 1147 } else { 1148 if (!tag.equals(r.tag)) { 1149 continue; 1150 } 1151 } 1152 if (r.id == id && r.pkg.equals(pkg)) { 1153 return i; 1154 } 1155 } 1156 return -1; 1157 } 1158 1159 // This is here instead of StatusBarPolicy because it is an important 1160 // security feature that we don't want people customizing the platform 1161 // to accidentally lose. 1162 private void updateAdbNotification(boolean adbEnabled) { 1163 if (adbEnabled) { 1164 if ("0".equals(SystemProperties.get("persist.adb.notify"))) { 1165 return; 1166 } 1167 if (!mAdbNotificationShown) { 1168 NotificationManager notificationManager = (NotificationManager) mContext 1169 .getSystemService(Context.NOTIFICATION_SERVICE); 1170 if (notificationManager != null) { 1171 Resources r = mContext.getResources(); 1172 CharSequence title = r.getText( 1173 com.android.internal.R.string.adb_active_notification_title); 1174 CharSequence message = r.getText( 1175 com.android.internal.R.string.adb_active_notification_message); 1176 1177 if (mAdbNotification == null) { 1178 mAdbNotification = new Notification(); 1179 mAdbNotification.icon = com.android.internal.R.drawable.stat_sys_adb; 1180 mAdbNotification.when = 0; 1181 mAdbNotification.flags = Notification.FLAG_ONGOING_EVENT; 1182 mAdbNotification.tickerText = title; 1183 mAdbNotification.defaults = 0; // please be quiet 1184 mAdbNotification.sound = null; 1185 mAdbNotification.vibrate = null; 1186 } 1187 1188 Intent intent = new Intent( 1189 Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS); 1190 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | 1191 Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); 1192 // Note: we are hard-coding the component because this is 1193 // an important security UI that we don't want anyone 1194 // intercepting. 1195 intent.setComponent(new ComponentName("com.android.settings", 1196 "com.android.settings.DevelopmentSettings")); 1197 PendingIntent pi = PendingIntent.getActivity(mContext, 0, 1198 intent, 0); 1199 1200 mAdbNotification.setLatestEventInfo(mContext, title, message, pi); 1201 1202 mAdbNotificationShown = true; 1203 notificationManager.notify( 1204 com.android.internal.R.string.adb_active_notification_title, 1205 mAdbNotification); 1206 } 1207 } 1208 1209 } else if (mAdbNotificationShown) { 1210 NotificationManager notificationManager = (NotificationManager) mContext 1211 .getSystemService(Context.NOTIFICATION_SERVICE); 1212 if (notificationManager != null) { 1213 mAdbNotificationShown = false; 1214 notificationManager.cancel( 1215 com.android.internal.R.string.adb_active_notification_title); 1216 } 1217 } 1218 } 1219 1220 private void updateNotificationPulse() { 1221 synchronized (mNotificationList) { 1222 updateLightsLocked(); 1223 } 1224 } 1225 1226 // ====================================================================== 1227 @Override 1228 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1229 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 1230 != PackageManager.PERMISSION_GRANTED) { 1231 pw.println("Permission Denial: can't dump NotificationManager from from pid=" 1232 + Binder.getCallingPid() 1233 + ", uid=" + Binder.getCallingUid()); 1234 return; 1235 } 1236 1237 pw.println("Current Notification Manager state:"); 1238 1239 int N; 1240 1241 synchronized (mToastQueue) { 1242 N = mToastQueue.size(); 1243 if (N > 0) { 1244 pw.println(" Toast Queue:"); 1245 for (int i=0; i<N; i++) { 1246 mToastQueue.get(i).dump(pw, " "); 1247 } 1248 pw.println(" "); 1249 } 1250 1251 } 1252 1253 synchronized (mNotificationList) { 1254 N = mNotificationList.size(); 1255 if (N > 0) { 1256 pw.println(" Notification List:"); 1257 for (int i=0; i<N; i++) { 1258 mNotificationList.get(i).dump(pw, " ", mContext); 1259 } 1260 pw.println(" "); 1261 } 1262 1263 N = mLights.size(); 1264 if (N > 0) { 1265 pw.println(" Lights List:"); 1266 for (int i=0; i<N; i++) { 1267 mLights.get(i).dump(pw, " ", mContext); 1268 } 1269 pw.println(" "); 1270 } 1271 1272 pw.println(" mSoundNotification=" + mSoundNotification); 1273 pw.println(" mSound=" + mSound); 1274 pw.println(" mVibrateNotification=" + mVibrateNotification); 1275 pw.println(" mDisabledNotifications=0x" + Integer.toHexString(mDisabledNotifications)); 1276 pw.println(" mSystemReady=" + mSystemReady); 1277 } 1278 } 1279} 1280