NotificationManagerService.java revision 40bbf9295d5245d3917629ce15f7b37670aef1ac
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 final int BATTERY_LOW_ARGB = 0xFFFF0000; // Charging Low - red solid on
137    private static final int BATTERY_MEDIUM_ARGB = 0xFFFFFF00;    // Charging - orange solid on
138    private static final int BATTERY_FULL_ARGB = 0xFF00FF00; // Charging Full - green solid on
139    private static final int BATTERY_BLINK_ON = 125;
140    private static final int BATTERY_BLINK_OFF = 2875;
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        // Don't start allowing notifications until the setup wizard has run once.
454        // After that, including subsequent boots, init with notifications turned on.
455        // This works on the first boot because the setup wizard will toggle this
456        // flag at least once and we'll go back to 0 after that.
457        if (0 == Settings.Secure.getInt(mContext.getContentResolver(),
458                    Settings.Secure.DEVICE_PROVISIONED, 0)) {
459            mDisabledNotifications = StatusBarManager.DISABLE_NOTIFICATION_ALERTS;
460        }
461
462        // register for battery changed notifications
463        IntentFilter filter = new IntentFilter();
464        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
465        filter.addAction(UsbManager.ACTION_USB_STATE);
466        filter.addAction(Intent.ACTION_SCREEN_ON);
467        filter.addAction(Intent.ACTION_SCREEN_OFF);
468        filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
469        mContext.registerReceiver(mIntentReceiver, filter);
470        IntentFilter pkgFilter = new IntentFilter();
471        pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
472        pkgFilter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
473        pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
474        pkgFilter.addDataScheme("package");
475        mContext.registerReceiver(mIntentReceiver, pkgFilter);
476        IntentFilter sdFilter = new IntentFilter(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
477        mContext.registerReceiver(mIntentReceiver, sdFilter);
478
479        SettingsObserver observer = new SettingsObserver(mHandler);
480        observer.observe();
481    }
482
483    void systemReady() {
484        // no beeping until we're basically done booting
485        mSystemReady = true;
486    }
487
488    // Toasts
489    // ============================================================================
490    public void enqueueToast(String pkg, ITransientNotification callback, int duration)
491    {
492        if (DBG) Slog.i(TAG, "enqueueToast pkg=" + pkg + " callback=" + callback + " duration=" + duration);
493
494        if (pkg == null || callback == null) {
495            Slog.e(TAG, "Not doing toast. pkg=" + pkg + " callback=" + callback);
496            return ;
497        }
498
499        synchronized (mToastQueue) {
500            int callingPid = Binder.getCallingPid();
501            long callingId = Binder.clearCallingIdentity();
502            try {
503                ToastRecord record;
504                int index = indexOfToastLocked(pkg, callback);
505                // If it's already in the queue, we update it in place, we don't
506                // move it to the end of the queue.
507                if (index >= 0) {
508                    record = mToastQueue.get(index);
509                    record.update(duration);
510                } else {
511                    record = new ToastRecord(callingPid, pkg, callback, duration);
512                    mToastQueue.add(record);
513                    index = mToastQueue.size() - 1;
514                    keepProcessAliveLocked(callingPid);
515                }
516                // If it's at index 0, it's the current toast.  It doesn't matter if it's
517                // new or just been updated.  Call back and tell it to show itself.
518                // If the callback fails, this will remove it from the list, so don't
519                // assume that it's valid after this.
520                if (index == 0) {
521                    showNextToastLocked();
522                }
523            } finally {
524                Binder.restoreCallingIdentity(callingId);
525            }
526        }
527    }
528
529    public void cancelToast(String pkg, ITransientNotification callback) {
530        Slog.i(TAG, "cancelToast pkg=" + pkg + " callback=" + callback);
531
532        if (pkg == null || callback == null) {
533            Slog.e(TAG, "Not cancelling notification. pkg=" + pkg + " callback=" + callback);
534            return ;
535        }
536
537        synchronized (mToastQueue) {
538            long callingId = Binder.clearCallingIdentity();
539            try {
540                int index = indexOfToastLocked(pkg, callback);
541                if (index >= 0) {
542                    cancelToastLocked(index);
543                } else {
544                    Slog.w(TAG, "Toast already cancelled. pkg=" + pkg + " callback=" + callback);
545                }
546            } finally {
547                Binder.restoreCallingIdentity(callingId);
548            }
549        }
550    }
551
552    private void showNextToastLocked() {
553        ToastRecord record = mToastQueue.get(0);
554        while (record != null) {
555            if (DBG) Slog.d(TAG, "Show pkg=" + record.pkg + " callback=" + record.callback);
556            try {
557                record.callback.show();
558                scheduleTimeoutLocked(record, false);
559                return;
560            } catch (RemoteException e) {
561                Slog.w(TAG, "Object died trying to show notification " + record.callback
562                        + " in package " + record.pkg);
563                // remove it from the list and let the process die
564                int index = mToastQueue.indexOf(record);
565                if (index >= 0) {
566                    mToastQueue.remove(index);
567                }
568                keepProcessAliveLocked(record.pid);
569                if (mToastQueue.size() > 0) {
570                    record = mToastQueue.get(0);
571                } else {
572                    record = null;
573                }
574            }
575        }
576    }
577
578    private void cancelToastLocked(int index) {
579        ToastRecord record = mToastQueue.get(index);
580        try {
581            record.callback.hide();
582        } catch (RemoteException e) {
583            Slog.w(TAG, "Object died trying to hide notification " + record.callback
584                    + " in package " + record.pkg);
585            // don't worry about this, we're about to remove it from
586            // the list anyway
587        }
588        mToastQueue.remove(index);
589        keepProcessAliveLocked(record.pid);
590        if (mToastQueue.size() > 0) {
591            // Show the next one. If the callback fails, this will remove
592            // it from the list, so don't assume that the list hasn't changed
593            // after this point.
594            showNextToastLocked();
595        }
596    }
597
598    private void scheduleTimeoutLocked(ToastRecord r, boolean immediate)
599    {
600        Message m = Message.obtain(mHandler, MESSAGE_TIMEOUT, r);
601        long delay = immediate ? 0 : (r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY);
602        mHandler.removeCallbacksAndMessages(r);
603        mHandler.sendMessageDelayed(m, delay);
604    }
605
606    private void handleTimeout(ToastRecord record)
607    {
608        if (DBG) Slog.d(TAG, "Timeout pkg=" + record.pkg + " callback=" + record.callback);
609        synchronized (mToastQueue) {
610            int index = indexOfToastLocked(record.pkg, record.callback);
611            if (index >= 0) {
612                cancelToastLocked(index);
613            }
614        }
615    }
616
617    // lock on mToastQueue
618    private int indexOfToastLocked(String pkg, ITransientNotification callback)
619    {
620        IBinder cbak = callback.asBinder();
621        ArrayList<ToastRecord> list = mToastQueue;
622        int len = list.size();
623        for (int i=0; i<len; i++) {
624            ToastRecord r = list.get(i);
625            if (r.pkg.equals(pkg) && r.callback.asBinder() == cbak) {
626                return i;
627            }
628        }
629        return -1;
630    }
631
632    // lock on mToastQueue
633    private void keepProcessAliveLocked(int pid)
634    {
635        int toastCount = 0; // toasts from this pid
636        ArrayList<ToastRecord> list = mToastQueue;
637        int N = list.size();
638        for (int i=0; i<N; i++) {
639            ToastRecord r = list.get(i);
640            if (r.pid == pid) {
641                toastCount++;
642            }
643        }
644        try {
645            mAm.setProcessForeground(mForegroundToken, pid, toastCount > 0);
646        } catch (RemoteException e) {
647            // Shouldn't happen.
648        }
649    }
650
651    private final class WorkerHandler extends Handler
652    {
653        @Override
654        public void handleMessage(Message msg)
655        {
656            switch (msg.what)
657            {
658                case MESSAGE_TIMEOUT:
659                    handleTimeout((ToastRecord)msg.obj);
660                    break;
661            }
662        }
663    }
664
665
666    // Notifications
667    // ============================================================================
668    public void enqueueNotification(String pkg, int id, Notification notification, int[] idOut)
669    {
670        enqueueNotificationWithTag(pkg, null /* tag */, id, notification, idOut);
671    }
672
673    public void enqueueNotificationWithTag(String pkg, String tag, int id, Notification notification,
674            int[] idOut)
675    {
676        enqueueNotificationInternal(pkg, Binder.getCallingUid(), Binder.getCallingPid(),
677                tag, id, notification, idOut);
678    }
679
680    // Not exposed via Binder; for system use only (otherwise malicious apps could spoof the
681    // uid/pid of another application)
682    public void enqueueNotificationInternal(String pkg, int callingUid, int callingPid,
683            String tag, int id, Notification notification, int[] idOut)
684    {
685        checkIncomingCall(pkg);
686
687        // Limit the number of notifications that any given package except the android
688        // package can enqueue.  Prevents DOS attacks and deals with leaks.
689        if (!"android".equals(pkg)) {
690            synchronized (mNotificationList) {
691                int count = 0;
692                final int N = mNotificationList.size();
693                for (int i=0; i<N; i++) {
694                    final NotificationRecord r = mNotificationList.get(i);
695                    if (r.pkg.equals(pkg)) {
696                        count++;
697                        if (count >= MAX_PACKAGE_NOTIFICATIONS) {
698                            Slog.e(TAG, "Package has already posted " + count
699                                    + " notifications.  Not showing more.  package=" + pkg);
700                            return;
701                        }
702                    }
703                }
704            }
705        }
706
707        // This conditional is a dirty hack to limit the logging done on
708        //     behalf of the download manager without affecting other apps.
709        if (!pkg.equals("com.android.providers.downloads")
710                || Log.isLoggable("DownloadManager", Log.VERBOSE)) {
711            EventLog.writeEvent(EventLogTags.NOTIFICATION_ENQUEUE, pkg, id, notification.toString());
712        }
713
714        if (pkg == null || notification == null) {
715            throw new IllegalArgumentException("null not allowed: pkg=" + pkg
716                    + " id=" + id + " notification=" + notification);
717        }
718        if (notification.icon != 0) {
719            if (notification.contentView == null) {
720                throw new IllegalArgumentException("contentView required: pkg=" + pkg
721                        + " id=" + id + " notification=" + notification);
722            }
723            if (notification.contentIntent == null) {
724                throw new IllegalArgumentException("contentIntent required: pkg=" + pkg
725                        + " id=" + id + " notification=" + notification);
726            }
727        }
728
729        synchronized (mNotificationList) {
730            NotificationRecord r = new NotificationRecord(pkg, tag, id,
731                    callingUid, callingPid, notification);
732            NotificationRecord old = null;
733
734            int index = indexOfNotificationLocked(pkg, tag, id);
735            if (index < 0) {
736                mNotificationList.add(r);
737            } else {
738                old = mNotificationList.remove(index);
739                mNotificationList.add(index, r);
740                // Make sure we don't lose the foreground service state.
741                if (old != null) {
742                    notification.flags |=
743                        old.notification.flags&Notification.FLAG_FOREGROUND_SERVICE;
744                }
745            }
746
747            // Ensure if this is a foreground service that the proper additional
748            // flags are set.
749            if ((notification.flags&Notification.FLAG_FOREGROUND_SERVICE) != 0) {
750                notification.flags |= Notification.FLAG_ONGOING_EVENT
751                        | Notification.FLAG_NO_CLEAR;
752            }
753
754            if (notification.icon != 0) {
755                StatusBarNotification n = new StatusBarNotification(pkg, id, tag,
756                        r.uid, r.initialPid, notification);
757                if (old != null && old.statusBarKey != null) {
758                    r.statusBarKey = old.statusBarKey;
759                    long identity = Binder.clearCallingIdentity();
760                    try {
761                        mStatusBar.updateNotification(r.statusBarKey, n);
762                    }
763                    finally {
764                        Binder.restoreCallingIdentity(identity);
765                    }
766                } else {
767                    long identity = Binder.clearCallingIdentity();
768                    try {
769                        r.statusBarKey = mStatusBar.addNotification(n);
770                        mAttentionLight.pulse();
771                    }
772                    finally {
773                        Binder.restoreCallingIdentity(identity);
774                    }
775                }
776                sendAccessibilityEvent(notification, pkg);
777            } else {
778                if (old != null && old.statusBarKey != null) {
779                    long identity = Binder.clearCallingIdentity();
780                    try {
781                        mStatusBar.removeNotification(old.statusBarKey);
782                    }
783                    finally {
784                        Binder.restoreCallingIdentity(identity);
785                    }
786                }
787            }
788
789            // If we're not supposed to beep, vibrate, etc. then don't.
790            if (((mDisabledNotifications & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) == 0)
791                    && (!(old != null
792                        && (notification.flags & Notification.FLAG_ONLY_ALERT_ONCE) != 0 ))
793                    && mSystemReady) {
794
795                final AudioManager audioManager = (AudioManager) mContext
796                .getSystemService(Context.AUDIO_SERVICE);
797                // sound
798                final boolean useDefaultSound =
799                    (notification.defaults & Notification.DEFAULT_SOUND) != 0;
800                if (useDefaultSound || notification.sound != null) {
801                    Uri uri;
802                    if (useDefaultSound) {
803                        uri = Settings.System.DEFAULT_NOTIFICATION_URI;
804                    } else {
805                        uri = notification.sound;
806                    }
807                    boolean looping = (notification.flags & Notification.FLAG_INSISTENT) != 0;
808                    int audioStreamType;
809                    if (notification.audioStreamType >= 0) {
810                        audioStreamType = notification.audioStreamType;
811                    } else {
812                        audioStreamType = DEFAULT_STREAM_TYPE;
813                    }
814                    mSoundNotification = r;
815                    // do not play notifications if stream volume is 0
816                    // (typically because ringer mode is silent).
817                    if (audioManager.getStreamVolume(audioStreamType) != 0) {
818                        long identity = Binder.clearCallingIdentity();
819                        try {
820                            mSound.play(mContext, uri, looping, audioStreamType);
821                        }
822                        finally {
823                            Binder.restoreCallingIdentity(identity);
824                        }
825                    }
826                }
827
828                // vibrate
829                final boolean useDefaultVibrate =
830                    (notification.defaults & Notification.DEFAULT_VIBRATE) != 0;
831                if ((useDefaultVibrate || notification.vibrate != null)
832                        && audioManager.shouldVibrate(AudioManager.VIBRATE_TYPE_NOTIFICATION)) {
833                    mVibrateNotification = r;
834
835                    mVibrator.vibrate(useDefaultVibrate ? DEFAULT_VIBRATE_PATTERN
836                                                        : notification.vibrate,
837                              ((notification.flags & Notification.FLAG_INSISTENT) != 0) ? 0: -1);
838                }
839            }
840
841            // this option doesn't shut off the lights
842
843            // light
844            // the most recent thing gets the light
845            mLights.remove(old);
846            if (mLedNotification == old) {
847                mLedNotification = null;
848            }
849            //Slog.i(TAG, "notification.lights="
850            //        + ((old.notification.lights.flags & Notification.FLAG_SHOW_LIGHTS) != 0));
851            if ((notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0) {
852                mLights.add(r);
853                updateLightsLocked();
854            } else {
855                if (old != null
856                        && ((old.notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0)) {
857                    updateLightsLocked();
858                }
859            }
860        }
861
862        idOut[0] = id;
863    }
864
865    private void sendAccessibilityEvent(Notification notification, CharSequence packageName) {
866        AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
867        if (!manager.isEnabled()) {
868            return;
869        }
870
871        AccessibilityEvent event =
872            AccessibilityEvent.obtain(AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED);
873        event.setPackageName(packageName);
874        event.setClassName(Notification.class.getName());
875        event.setParcelableData(notification);
876        CharSequence tickerText = notification.tickerText;
877        if (!TextUtils.isEmpty(tickerText)) {
878            event.getText().add(tickerText);
879        }
880
881        manager.sendAccessibilityEvent(event);
882    }
883
884    private void cancelNotificationLocked(NotificationRecord r) {
885        // status bar
886        if (r.notification.icon != 0) {
887            long identity = Binder.clearCallingIdentity();
888            try {
889                mStatusBar.removeNotification(r.statusBarKey);
890            }
891            finally {
892                Binder.restoreCallingIdentity(identity);
893            }
894            r.statusBarKey = null;
895        }
896
897        // sound
898        if (mSoundNotification == r) {
899            mSoundNotification = null;
900            long identity = Binder.clearCallingIdentity();
901            try {
902                mSound.stop();
903            }
904            finally {
905                Binder.restoreCallingIdentity(identity);
906            }
907        }
908
909        // vibrate
910        if (mVibrateNotification == r) {
911            mVibrateNotification = null;
912            long identity = Binder.clearCallingIdentity();
913            try {
914                mVibrator.cancel();
915            }
916            finally {
917                Binder.restoreCallingIdentity(identity);
918            }
919        }
920
921        // light
922        mLights.remove(r);
923        if (mLedNotification == r) {
924            mLedNotification = null;
925        }
926    }
927
928    /**
929     * Cancels a notification ONLY if it has all of the {@code mustHaveFlags}
930     * and none of the {@code mustNotHaveFlags}.
931     */
932    private void cancelNotification(String pkg, String tag, int id, int mustHaveFlags,
933            int mustNotHaveFlags) {
934        EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL, pkg, id, mustHaveFlags);
935
936        synchronized (mNotificationList) {
937            int index = indexOfNotificationLocked(pkg, tag, id);
938            if (index >= 0) {
939                NotificationRecord r = mNotificationList.get(index);
940
941                if ((r.notification.flags & mustHaveFlags) != mustHaveFlags) {
942                    return;
943                }
944                if ((r.notification.flags & mustNotHaveFlags) != 0) {
945                    return;
946                }
947
948                mNotificationList.remove(index);
949
950                cancelNotificationLocked(r);
951                updateLightsLocked();
952            }
953        }
954    }
955
956    /**
957     * Cancels all notifications from a given package that have all of the
958     * {@code mustHaveFlags}.
959     */
960    boolean cancelAllNotificationsInt(String pkg, int mustHaveFlags,
961            int mustNotHaveFlags, boolean doit) {
962        EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL_ALL, pkg, mustHaveFlags);
963
964        synchronized (mNotificationList) {
965            final int N = mNotificationList.size();
966            boolean canceledSomething = false;
967            for (int i = N-1; i >= 0; --i) {
968                NotificationRecord r = mNotificationList.get(i);
969                if ((r.notification.flags & mustHaveFlags) != mustHaveFlags) {
970                    continue;
971                }
972                if ((r.notification.flags & mustNotHaveFlags) != 0) {
973                    continue;
974                }
975                if (!r.pkg.equals(pkg)) {
976                    continue;
977                }
978                canceledSomething = true;
979                if (!doit) {
980                    return true;
981                }
982                mNotificationList.remove(i);
983                cancelNotificationLocked(r);
984            }
985            if (canceledSomething) {
986                updateLightsLocked();
987            }
988            return canceledSomething;
989        }
990    }
991
992
993    public void cancelNotification(String pkg, int id) {
994        cancelNotificationWithTag(pkg, null /* tag */, id);
995    }
996
997    public void cancelNotificationWithTag(String pkg, String tag, int id) {
998        checkIncomingCall(pkg);
999        // Don't allow client applications to cancel foreground service notis.
1000        cancelNotification(pkg, tag, id, 0,
1001                Binder.getCallingUid() == Process.SYSTEM_UID
1002                ? 0 : Notification.FLAG_FOREGROUND_SERVICE);
1003    }
1004
1005    public void cancelAllNotifications(String pkg) {
1006        checkIncomingCall(pkg);
1007
1008        // Calling from user space, don't allow the canceling of actively
1009        // running foreground services.
1010        cancelAllNotificationsInt(pkg, 0, Notification.FLAG_FOREGROUND_SERVICE, true);
1011    }
1012
1013    void checkIncomingCall(String pkg) {
1014        int uid = Binder.getCallingUid();
1015        if (uid == Process.SYSTEM_UID || uid == 0) {
1016            return;
1017        }
1018        try {
1019            ApplicationInfo ai = mContext.getPackageManager().getApplicationInfo(
1020                    pkg, 0);
1021            if (ai.uid != uid) {
1022                throw new SecurityException("Calling uid " + uid + " gave package"
1023                        + pkg + " which is owned by uid " + ai.uid);
1024            }
1025        } catch (PackageManager.NameNotFoundException e) {
1026            throw new SecurityException("Unknown package " + pkg);
1027        }
1028    }
1029
1030    void cancelAll() {
1031        synchronized (mNotificationList) {
1032            final int N = mNotificationList.size();
1033            for (int i=N-1; i>=0; i--) {
1034                NotificationRecord r = mNotificationList.get(i);
1035
1036                if ((r.notification.flags & (Notification.FLAG_ONGOING_EVENT
1037                                | Notification.FLAG_NO_CLEAR)) == 0) {
1038                    if (r.notification.deleteIntent != null) {
1039                        try {
1040                            r.notification.deleteIntent.send();
1041                        } catch (PendingIntent.CanceledException ex) {
1042                            // do nothing - there's no relevant way to recover, and
1043                            //     no reason to let this propagate
1044                            Slog.w(TAG, "canceled PendingIntent for " + r.pkg, ex);
1045                        }
1046                    }
1047                    mNotificationList.remove(i);
1048                    cancelNotificationLocked(r);
1049                }
1050            }
1051
1052            updateLightsLocked();
1053        }
1054    }
1055
1056    private void updateLights() {
1057        synchronized (mNotificationList) {
1058            updateLightsLocked();
1059        }
1060    }
1061
1062    // lock on mNotificationList
1063    private void updateLightsLocked()
1064    {
1065        // Battery low always shows, other states only show if charging.
1066        if (mBatteryLow) {
1067            if (mBatteryCharging) {
1068                mBatteryLight.setColor(BATTERY_LOW_ARGB);
1069            } else {
1070                // Flash when battery is low and not charging
1071                mBatteryLight.setFlashing(BATTERY_LOW_ARGB, LightsService.LIGHT_FLASH_TIMED,
1072                        BATTERY_BLINK_ON, BATTERY_BLINK_OFF);
1073            }
1074        } else if (mBatteryCharging) {
1075            if (mBatteryFull) {
1076                mBatteryLight.setColor(BATTERY_FULL_ARGB);
1077            } else {
1078                mBatteryLight.setColor(BATTERY_MEDIUM_ARGB);
1079            }
1080        } else {
1081            mBatteryLight.turnOff();
1082        }
1083
1084        // clear pending pulse notification if screen is on
1085        if (mScreenOn || mLedNotification == null) {
1086            mPendingPulseNotification = false;
1087        }
1088
1089        // handle notification lights
1090        if (mLedNotification == null) {
1091            // get next notification, if any
1092            int n = mLights.size();
1093            if (n > 0) {
1094                mLedNotification = mLights.get(n-1);
1095            }
1096            if (mLedNotification != null && !mScreenOn) {
1097                mPendingPulseNotification = true;
1098            }
1099        }
1100
1101        // we only flash if screen is off and persistent pulsing is enabled
1102        // and we are not currently in a call
1103        if (!mPendingPulseNotification || mScreenOn || mInCall) {
1104            mNotificationLight.turnOff();
1105        } else {
1106            int ledARGB = mLedNotification.notification.ledARGB;
1107            int ledOnMS = mLedNotification.notification.ledOnMS;
1108            int ledOffMS = mLedNotification.notification.ledOffMS;
1109            if ((mLedNotification.notification.defaults & Notification.DEFAULT_LIGHTS) != 0) {
1110                ledARGB = mDefaultNotificationColor;
1111                ledOnMS = mDefaultNotificationLedOn;
1112                ledOffMS = mDefaultNotificationLedOff;
1113            }
1114            if (mNotificationPulseEnabled) {
1115                // pulse repeatedly
1116                mNotificationLight.setFlashing(ledARGB, LightsService.LIGHT_FLASH_TIMED,
1117                        ledOnMS, ledOffMS);
1118            } else {
1119                // pulse only once
1120                mNotificationLight.pulse(ledARGB, ledOnMS);
1121            }
1122        }
1123    }
1124
1125    // lock on mNotificationList
1126    private int indexOfNotificationLocked(String pkg, String tag, int id)
1127    {
1128        ArrayList<NotificationRecord> list = mNotificationList;
1129        final int len = list.size();
1130        for (int i=0; i<len; i++) {
1131            NotificationRecord r = list.get(i);
1132            if (tag == null) {
1133                if (r.tag != null) {
1134                    continue;
1135                }
1136            } else {
1137                if (!tag.equals(r.tag)) {
1138                    continue;
1139                }
1140            }
1141            if (r.id == id && r.pkg.equals(pkg)) {
1142                return i;
1143            }
1144        }
1145        return -1;
1146    }
1147
1148    // This is here instead of StatusBarPolicy because it is an important
1149    // security feature that we don't want people customizing the platform
1150    // to accidentally lose.
1151    private void updateAdbNotification(boolean adbEnabled) {
1152        if (adbEnabled) {
1153            if ("0".equals(SystemProperties.get("persist.adb.notify"))) {
1154                return;
1155            }
1156            if (!mAdbNotificationShown) {
1157                NotificationManager notificationManager = (NotificationManager) mContext
1158                        .getSystemService(Context.NOTIFICATION_SERVICE);
1159                if (notificationManager != null) {
1160                    Resources r = mContext.getResources();
1161                    CharSequence title = r.getText(
1162                            com.android.internal.R.string.adb_active_notification_title);
1163                    CharSequence message = r.getText(
1164                            com.android.internal.R.string.adb_active_notification_message);
1165
1166                    if (mAdbNotification == null) {
1167                        mAdbNotification = new Notification();
1168                        mAdbNotification.icon = com.android.internal.R.drawable.stat_sys_adb;
1169                        mAdbNotification.when = 0;
1170                        mAdbNotification.flags = Notification.FLAG_ONGOING_EVENT;
1171                        mAdbNotification.tickerText = title;
1172                        mAdbNotification.defaults = 0; // please be quiet
1173                        mAdbNotification.sound = null;
1174                        mAdbNotification.vibrate = null;
1175                    }
1176
1177                    Intent intent = new Intent(
1178                            Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS);
1179                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
1180                            Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
1181                    // Note: we are hard-coding the component because this is
1182                    // an important security UI that we don't want anyone
1183                    // intercepting.
1184                    intent.setComponent(new ComponentName("com.android.settings",
1185                            "com.android.settings.DevelopmentSettings"));
1186                    PendingIntent pi = PendingIntent.getActivity(mContext, 0,
1187                            intent, 0);
1188
1189                    mAdbNotification.setLatestEventInfo(mContext, title, message, pi);
1190
1191                    mAdbNotificationShown = true;
1192                    notificationManager.notify(
1193                            com.android.internal.R.string.adb_active_notification_title,
1194                            mAdbNotification);
1195                }
1196            }
1197
1198        } else if (mAdbNotificationShown) {
1199            NotificationManager notificationManager = (NotificationManager) mContext
1200                    .getSystemService(Context.NOTIFICATION_SERVICE);
1201            if (notificationManager != null) {
1202                mAdbNotificationShown = false;
1203                notificationManager.cancel(
1204                        com.android.internal.R.string.adb_active_notification_title);
1205            }
1206        }
1207    }
1208
1209    private void updateNotificationPulse() {
1210        synchronized (mNotificationList) {
1211            updateLightsLocked();
1212        }
1213    }
1214
1215    // ======================================================================
1216    @Override
1217    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1218        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1219                != PackageManager.PERMISSION_GRANTED) {
1220            pw.println("Permission Denial: can't dump NotificationManager from from pid="
1221                    + Binder.getCallingPid()
1222                    + ", uid=" + Binder.getCallingUid());
1223            return;
1224        }
1225
1226        pw.println("Current Notification Manager state:");
1227
1228        int N;
1229
1230        synchronized (mToastQueue) {
1231            N = mToastQueue.size();
1232            if (N > 0) {
1233                pw.println("  Toast Queue:");
1234                for (int i=0; i<N; i++) {
1235                    mToastQueue.get(i).dump(pw, "    ");
1236                }
1237                pw.println("  ");
1238            }
1239
1240        }
1241
1242        synchronized (mNotificationList) {
1243            N = mNotificationList.size();
1244            if (N > 0) {
1245                pw.println("  Notification List:");
1246                for (int i=0; i<N; i++) {
1247                    mNotificationList.get(i).dump(pw, "    ", mContext);
1248                }
1249                pw.println("  ");
1250            }
1251
1252            N = mLights.size();
1253            if (N > 0) {
1254                pw.println("  Lights List:");
1255                for (int i=0; i<N; i++) {
1256                    mLights.get(i).dump(pw, "    ", mContext);
1257                }
1258                pw.println("  ");
1259            }
1260
1261            pw.println("  mSoundNotification=" + mSoundNotification);
1262            pw.println("  mSound=" + mSound);
1263            pw.println("  mVibrateNotification=" + mVibrateNotification);
1264            pw.println("  mDisabledNotifications=0x" + Integer.toHexString(mDisabledNotifications));
1265            pw.println("  mSystemReady=" + mSystemReady);
1266        }
1267    }
1268}
1269