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