NotificationManagerService.java revision b880d880c6cd989eacc28c365fc9a41d31900da1
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.notification;
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.ActivityManager;
24import android.app.ActivityManagerNative;
25import android.app.AppGlobals;
26import android.app.AppOpsManager;
27import android.app.IActivityManager;
28import android.app.INotificationManager;
29import android.app.ITransientNotification;
30import android.app.Notification;
31import android.app.PendingIntent;
32import android.app.StatusBarManager;
33import android.content.BroadcastReceiver;
34import android.content.ComponentName;
35import android.content.ContentResolver;
36import android.content.Context;
37import android.content.Intent;
38import android.content.IntentFilter;
39import android.content.ServiceConnection;
40import android.content.pm.ApplicationInfo;
41import android.content.pm.PackageInfo;
42import android.content.pm.PackageManager;
43import android.content.pm.ResolveInfo;
44import android.content.pm.ServiceInfo;
45import android.content.pm.PackageManager.NameNotFoundException;
46import android.content.res.Resources;
47import android.database.ContentObserver;
48import android.graphics.Bitmap;
49import android.media.AudioManager;
50import android.media.IRingtonePlayer;
51import android.net.Uri;
52import android.os.Binder;
53import android.os.Handler;
54import android.os.IBinder;
55import android.os.Message;
56import android.os.Process;
57import android.os.RemoteException;
58import android.os.UserHandle;
59import android.os.Vibrator;
60import android.provider.Settings;
61import android.service.notification.INotificationListener;
62import android.service.notification.NotificationListenerService;
63import android.service.notification.StatusBarNotification;
64import android.telephony.TelephonyManager;
65import android.text.TextUtils;
66import android.util.AtomicFile;
67import android.util.EventLog;
68import android.util.Log;
69import android.util.Slog;
70import android.util.Xml;
71import android.view.accessibility.AccessibilityEvent;
72import android.view.accessibility.AccessibilityManager;
73import android.widget.Toast;
74
75import com.android.internal.R;
76
77import com.android.internal.notification.NotificationScorer;
78import com.android.server.EventLogTags;
79import com.android.server.statusbar.StatusBarManagerInternal;
80import com.android.server.SystemService;
81import com.android.server.lights.Light;
82import com.android.server.lights.LightsManager;
83
84import org.xmlpull.v1.XmlPullParser;
85import org.xmlpull.v1.XmlPullParserException;
86
87import java.io.File;
88import java.io.FileDescriptor;
89import java.io.FileInputStream;
90import java.io.FileNotFoundException;
91import java.io.IOException;
92import java.io.PrintWriter;
93import java.lang.reflect.Array;
94import java.util.ArrayDeque;
95import java.util.ArrayList;
96import java.util.Arrays;
97import java.util.HashSet;
98import java.util.Iterator;
99import java.util.List;
100import java.util.NoSuchElementException;
101import java.util.Set;
102
103import libcore.io.IoUtils;
104
105/** {@hide} */
106public class NotificationManagerService extends SystemService {
107    static final String TAG = "NotificationService";
108    static final boolean DBG = false;
109
110    static final int MAX_PACKAGE_NOTIFICATIONS = 50;
111
112    // message codes
113    static final int MESSAGE_TIMEOUT = 2;
114
115    static final int LONG_DELAY = 3500; // 3.5 seconds
116    static final int SHORT_DELAY = 2000; // 2 seconds
117
118    static final long[] DEFAULT_VIBRATE_PATTERN = {0, 250, 250, 250};
119    static final int VIBRATE_PATTERN_MAXLEN = 8 * 2 + 1; // up to eight bumps
120
121    static final int DEFAULT_STREAM_TYPE = AudioManager.STREAM_NOTIFICATION;
122    static final boolean SCORE_ONGOING_HIGHER = false;
123
124    static final int JUNK_SCORE = -1000;
125    static final int NOTIFICATION_PRIORITY_MULTIPLIER = 10;
126    static final int SCORE_DISPLAY_THRESHOLD = Notification.PRIORITY_MIN * NOTIFICATION_PRIORITY_MULTIPLIER;
127
128    // Notifications with scores below this will not interrupt the user, either via LED or
129    // sound or vibration
130    static final int SCORE_INTERRUPTION_THRESHOLD =
131            Notification.PRIORITY_LOW * NOTIFICATION_PRIORITY_MULTIPLIER;
132
133    static final boolean ENABLE_BLOCKED_NOTIFICATIONS = true;
134    static final boolean ENABLE_BLOCKED_TOASTS = true;
135
136    static final String ENABLED_NOTIFICATION_LISTENERS_SEPARATOR = ":";
137
138    private IActivityManager mAm;
139    AudioManager mAudioManager;
140    StatusBarManagerInternal mStatusBar;
141    Vibrator mVibrator;
142
143    final IBinder mForegroundToken = new Binder();
144    private WorkerHandler mHandler;
145
146    private Light mNotificationLight;
147    Light mAttentionLight;
148    private int mDefaultNotificationColor;
149    private int mDefaultNotificationLedOn;
150
151    private int mDefaultNotificationLedOff;
152    private long[] mDefaultVibrationPattern;
153
154    private long[] mFallbackVibrationPattern;
155    boolean mSystemReady;
156
157    int mDisabledNotifications;
158    NotificationRecord mSoundNotification;
159    NotificationRecord mVibrateNotification;
160
161    // for enabling and disabling notification pulse behavior
162    private boolean mScreenOn = true;
163    private boolean mInCall = false;
164    private boolean mNotificationPulseEnabled;
165
166    // used as a mutex for access to all active notifications & listeners
167    final ArrayList<NotificationRecord> mNotificationList =
168            new ArrayList<NotificationRecord>();
169
170    final ArrayList<ToastRecord> mToastQueue = new ArrayList<ToastRecord>();
171
172    ArrayList<NotificationRecord> mLights = new ArrayList<NotificationRecord>();
173    NotificationRecord mLedNotification;
174
175    private AppOpsManager mAppOps;
176
177    // contains connections to all connected listeners, including app services
178    // and system listeners
179    private ArrayList<NotificationListenerInfo> mListeners
180            = new ArrayList<NotificationListenerInfo>();
181    // things that will be put into mListeners as soon as they're ready
182    private ArrayList<String> mServicesBinding = new ArrayList<String>();
183    // lists the component names of all enabled (and therefore connected) listener
184    // app services for the current user only
185    private HashSet<ComponentName> mEnabledListenersForCurrentUser
186            = new HashSet<ComponentName>();
187    // Just the packages from mEnabledListenersForCurrentUser
188    private HashSet<String> mEnabledListenerPackageNames = new HashSet<String>();
189
190    // Notification control database. For now just contains disabled packages.
191    private AtomicFile mPolicyFile;
192    private HashSet<String> mBlockedPackages = new HashSet<String>();
193
194    private static final int DB_VERSION = 1;
195
196    private static final String TAG_BODY = "notification-policy";
197    private static final String ATTR_VERSION = "version";
198
199    private static final String TAG_BLOCKED_PKGS = "blocked-packages";
200    private static final String TAG_PACKAGE = "package";
201    private static final String ATTR_NAME = "name";
202
203    final ArrayList<NotificationScorer> mScorers = new ArrayList<NotificationScorer>();
204
205    private class NotificationListenerInfo implements IBinder.DeathRecipient {
206        INotificationListener listener;
207        ComponentName component;
208        int userid;
209        boolean isSystem;
210        ServiceConnection connection;
211
212        public NotificationListenerInfo(INotificationListener listener, ComponentName component,
213                int userid, boolean isSystem) {
214            this.listener = listener;
215            this.component = component;
216            this.userid = userid;
217            this.isSystem = isSystem;
218            this.connection = null;
219        }
220
221        public NotificationListenerInfo(INotificationListener listener, ComponentName component,
222                int userid, ServiceConnection connection) {
223            this.listener = listener;
224            this.component = component;
225            this.userid = userid;
226            this.isSystem = false;
227            this.connection = connection;
228        }
229
230        boolean enabledAndUserMatches(StatusBarNotification sbn) {
231            final int nid = sbn.getUserId();
232            if (!isEnabledForCurrentUser()) {
233                return false;
234            }
235            if (this.userid == UserHandle.USER_ALL) return true;
236            return (nid == UserHandle.USER_ALL || nid == this.userid);
237        }
238
239        public void notifyPostedIfUserMatch(StatusBarNotification sbn) {
240            if (!enabledAndUserMatches(sbn)) {
241                return;
242            }
243            try {
244                listener.onNotificationPosted(sbn);
245            } catch (RemoteException ex) {
246                Log.e(TAG, "unable to notify listener (posted): " + listener, ex);
247            }
248        }
249
250        public void notifyRemovedIfUserMatch(StatusBarNotification sbn) {
251            if (!enabledAndUserMatches(sbn)) return;
252            try {
253                listener.onNotificationRemoved(sbn);
254            } catch (RemoteException ex) {
255                Log.e(TAG, "unable to notify listener (removed): " + listener, ex);
256            }
257        }
258
259        @Override
260        public void binderDied() {
261            if (connection == null) {
262                // This is not a service; it won't be recreated. We can give up this connection.
263                unregisterListenerImpl(this.listener, this.userid);
264            }
265        }
266
267        /** convenience method for looking in mEnabledListenersForCurrentUser */
268        public boolean isEnabledForCurrentUser() {
269            if (this.isSystem) return true;
270            if (this.connection == null) return false;
271            return mEnabledListenersForCurrentUser.contains(this.component);
272        }
273    }
274
275    private static class Archive {
276        static final int BUFFER_SIZE = 250;
277        ArrayDeque<StatusBarNotification> mBuffer = new ArrayDeque<StatusBarNotification>(BUFFER_SIZE);
278
279        public Archive() {
280        }
281
282        public String toString() {
283            final StringBuilder sb = new StringBuilder();
284            final int N = mBuffer.size();
285            sb.append("Archive (");
286            sb.append(N);
287            sb.append(" notification");
288            sb.append((N==1)?")":"s)");
289            return sb.toString();
290        }
291
292        public void record(StatusBarNotification nr) {
293            if (mBuffer.size() == BUFFER_SIZE) {
294                mBuffer.removeFirst();
295            }
296
297            // We don't want to store the heavy bits of the notification in the archive,
298            // but other clients in the system process might be using the object, so we
299            // store a (lightened) copy.
300            mBuffer.addLast(nr.cloneLight());
301        }
302
303
304        public void clear() {
305            mBuffer.clear();
306        }
307
308        public Iterator<StatusBarNotification> descendingIterator() {
309            return mBuffer.descendingIterator();
310        }
311        public Iterator<StatusBarNotification> ascendingIterator() {
312            return mBuffer.iterator();
313        }
314        public Iterator<StatusBarNotification> filter(
315                final Iterator<StatusBarNotification> iter, final String pkg, final int userId) {
316            return new Iterator<StatusBarNotification>() {
317                StatusBarNotification mNext = findNext();
318
319                private StatusBarNotification findNext() {
320                    while (iter.hasNext()) {
321                        StatusBarNotification nr = iter.next();
322                        if ((pkg == null || nr.getPackageName() == pkg)
323                                && (userId == UserHandle.USER_ALL || nr.getUserId() == userId)) {
324                            return nr;
325                        }
326                    }
327                    return null;
328                }
329
330                @Override
331                public boolean hasNext() {
332                    return mNext == null;
333                }
334
335                @Override
336                public StatusBarNotification next() {
337                    StatusBarNotification next = mNext;
338                    if (next == null) {
339                        throw new NoSuchElementException();
340                    }
341                    mNext = findNext();
342                    return next;
343                }
344
345                @Override
346                public void remove() {
347                    iter.remove();
348                }
349            };
350        }
351
352        public StatusBarNotification[] getArray(int count) {
353            if (count == 0) count = Archive.BUFFER_SIZE;
354            final StatusBarNotification[] a
355                    = new StatusBarNotification[Math.min(count, mBuffer.size())];
356            Iterator<StatusBarNotification> iter = descendingIterator();
357            int i=0;
358            while (iter.hasNext() && i < count) {
359                a[i++] = iter.next();
360            }
361            return a;
362        }
363
364        public StatusBarNotification[] getArray(int count, String pkg, int userId) {
365            if (count == 0) count = Archive.BUFFER_SIZE;
366            final StatusBarNotification[] a
367                    = new StatusBarNotification[Math.min(count, mBuffer.size())];
368            Iterator<StatusBarNotification> iter = filter(descendingIterator(), pkg, userId);
369            int i=0;
370            while (iter.hasNext() && i < count) {
371                a[i++] = iter.next();
372            }
373            return a;
374        }
375
376    }
377
378    Archive mArchive = new Archive();
379
380    private void loadBlockDb() {
381        synchronized(mBlockedPackages) {
382            if (mPolicyFile == null) {
383                File dir = new File("/data/system");
384                mPolicyFile = new AtomicFile(new File(dir, "notification_policy.xml"));
385
386                mBlockedPackages.clear();
387
388                FileInputStream infile = null;
389                try {
390                    infile = mPolicyFile.openRead();
391                    final XmlPullParser parser = Xml.newPullParser();
392                    parser.setInput(infile, null);
393
394                    int type;
395                    String tag;
396                    int version = DB_VERSION;
397                    while ((type = parser.next()) != END_DOCUMENT) {
398                        tag = parser.getName();
399                        if (type == START_TAG) {
400                            if (TAG_BODY.equals(tag)) {
401                                version = Integer.parseInt(
402                                        parser.getAttributeValue(null, ATTR_VERSION));
403                            } else if (TAG_BLOCKED_PKGS.equals(tag)) {
404                                while ((type = parser.next()) != END_DOCUMENT) {
405                                    tag = parser.getName();
406                                    if (TAG_PACKAGE.equals(tag)) {
407                                        mBlockedPackages.add(
408                                                parser.getAttributeValue(null, ATTR_NAME));
409                                    } else if (TAG_BLOCKED_PKGS.equals(tag) && type == END_TAG) {
410                                        break;
411                                    }
412                                }
413                            }
414                        }
415                    }
416                } catch (FileNotFoundException e) {
417                    // No data yet
418                } catch (IOException e) {
419                    Log.wtf(TAG, "Unable to read blocked notifications database", e);
420                } catch (NumberFormatException e) {
421                    Log.wtf(TAG, "Unable to parse blocked notifications database", e);
422                } catch (XmlPullParserException e) {
423                    Log.wtf(TAG, "Unable to parse blocked notifications database", e);
424                } finally {
425                    IoUtils.closeQuietly(infile);
426                }
427            }
428        }
429    }
430
431    /** Use this when you actually want to post a notification or toast.
432     *
433     * Unchecked. Not exposed via Binder, but can be called in the course of enqueue*().
434     */
435    private boolean noteNotificationOp(String pkg, int uid) {
436        if (mAppOps.noteOpNoThrow(AppOpsManager.OP_POST_NOTIFICATION, uid, pkg)
437                != AppOpsManager.MODE_ALLOWED) {
438            Slog.v(TAG, "notifications are disabled by AppOps for " + pkg);
439            return false;
440        }
441        return true;
442    }
443
444    private static String idDebugString(Context baseContext, String packageName, int id) {
445        Context c = null;
446
447        if (packageName != null) {
448            try {
449                c = baseContext.createPackageContext(packageName, 0);
450            } catch (NameNotFoundException e) {
451                c = baseContext;
452            }
453        } else {
454            c = baseContext;
455        }
456
457        String pkg;
458        String type;
459        String name;
460
461        Resources r = c.getResources();
462        try {
463            return r.getResourceName(id);
464        } catch (Resources.NotFoundException e) {
465            return "<name unknown>";
466        }
467    }
468
469
470    /**
471     * Remove notification access for any services that no longer exist.
472     */
473    void disableNonexistentListeners() {
474        int currentUser = ActivityManager.getCurrentUser();
475        String flatIn = Settings.Secure.getStringForUser(
476                getContext().getContentResolver(),
477                Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
478                currentUser);
479        if (!TextUtils.isEmpty(flatIn)) {
480            if (DBG) Slog.v(TAG, "flat before: " + flatIn);
481            PackageManager pm = getContext().getPackageManager();
482            List<ResolveInfo> installedServices = pm.queryIntentServicesAsUser(
483                    new Intent(NotificationListenerService.SERVICE_INTERFACE),
484                    PackageManager.GET_SERVICES | PackageManager.GET_META_DATA,
485                    currentUser);
486
487            Set<ComponentName> installed = new HashSet<ComponentName>();
488            for (int i = 0, count = installedServices.size(); i < count; i++) {
489                ResolveInfo resolveInfo = installedServices.get(i);
490                ServiceInfo info = resolveInfo.serviceInfo;
491
492                if (!android.Manifest.permission.BIND_NOTIFICATION_LISTENER_SERVICE.equals(
493                                info.permission)) {
494                    Slog.w(TAG, "Skipping notification listener service "
495                            + info.packageName + "/" + info.name
496                            + ": it does not require the permission "
497                            + android.Manifest.permission.BIND_NOTIFICATION_LISTENER_SERVICE);
498                    continue;
499                }
500                installed.add(new ComponentName(info.packageName, info.name));
501            }
502
503            String flatOut = "";
504            if (!installed.isEmpty()) {
505                String[] enabled = flatIn.split(ENABLED_NOTIFICATION_LISTENERS_SEPARATOR);
506                ArrayList<String> remaining = new ArrayList<String>(enabled.length);
507                for (int i = 0; i < enabled.length; i++) {
508                    ComponentName enabledComponent = ComponentName.unflattenFromString(enabled[i]);
509                    if (installed.contains(enabledComponent)) {
510                        remaining.add(enabled[i]);
511                    }
512                }
513                flatOut = TextUtils.join(ENABLED_NOTIFICATION_LISTENERS_SEPARATOR, remaining);
514            }
515            if (DBG) Slog.v(TAG, "flat after: " + flatOut);
516            if (!flatIn.equals(flatOut)) {
517                Settings.Secure.putStringForUser(getContext().getContentResolver(),
518                        Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
519                        flatOut, currentUser);
520            }
521        }
522    }
523
524    /**
525     * Called whenever packages change, the user switches, or ENABLED_NOTIFICATION_LISTENERS
526     * is altered. (For example in response to USER_SWITCHED in our broadcast receiver)
527     */
528    void rebindListenerServices() {
529        final int currentUser = ActivityManager.getCurrentUser();
530        String flat = Settings.Secure.getStringForUser(
531                getContext().getContentResolver(),
532                Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
533                currentUser);
534
535        NotificationListenerInfo[] toRemove = new NotificationListenerInfo[mListeners.size()];
536        final ArrayList<ComponentName> toAdd;
537
538        synchronized (mNotificationList) {
539            // unbind and remove all existing listeners
540            toRemove = mListeners.toArray(toRemove);
541
542            toAdd = new ArrayList<ComponentName>();
543            final HashSet<ComponentName> newEnabled = new HashSet<ComponentName>();
544            final HashSet<String> newPackages = new HashSet<String>();
545
546            // decode the list of components
547            if (flat != null) {
548                String[] components = flat.split(ENABLED_NOTIFICATION_LISTENERS_SEPARATOR);
549                for (int i=0; i<components.length; i++) {
550                    final ComponentName component
551                            = ComponentName.unflattenFromString(components[i]);
552                    if (component != null) {
553                        newEnabled.add(component);
554                        toAdd.add(component);
555                        newPackages.add(component.getPackageName());
556                    }
557                }
558
559                mEnabledListenersForCurrentUser = newEnabled;
560                mEnabledListenerPackageNames = newPackages;
561            }
562        }
563
564        for (NotificationListenerInfo info : toRemove) {
565            final ComponentName component = info.component;
566            final int oldUser = info.userid;
567            Slog.v(TAG, "disabling notification listener for user " + oldUser + ": " + component);
568            unregisterListenerService(component, info.userid);
569        }
570
571        final int N = toAdd.size();
572        for (int i=0; i<N; i++) {
573            final ComponentName component = toAdd.get(i);
574            Slog.v(TAG, "enabling notification listener for user " + currentUser + ": "
575                    + component);
576            registerListenerService(component, currentUser);
577        }
578    }
579
580
581    /**
582     * Version of registerListener that takes the name of a
583     * {@link android.service.notification.NotificationListenerService} to bind to.
584     *
585     * This is the mechanism by which third parties may subscribe to notifications.
586     */
587    private void registerListenerService(final ComponentName name, final int userid) {
588        checkCallerIsSystem();
589
590        if (DBG) Slog.v(TAG, "registerListenerService: " + name + " u=" + userid);
591
592        synchronized (mNotificationList) {
593            final String servicesBindingTag = name.toString() + "/" + userid;
594            if (mServicesBinding.contains(servicesBindingTag)) {
595                // stop registering this thing already! we're working on it
596                return;
597            }
598            mServicesBinding.add(servicesBindingTag);
599
600            final int N = mListeners.size();
601            for (int i=N-1; i>=0; i--) {
602                final NotificationListenerInfo info = mListeners.get(i);
603                if (name.equals(info.component)
604                        && info.userid == userid) {
605                    // cut old connections
606                    if (DBG) Slog.v(TAG, "    disconnecting old listener: " + info.listener);
607                    mListeners.remove(i);
608                    if (info.connection != null) {
609                        getContext().unbindService(info.connection);
610                    }
611                }
612            }
613
614            Intent intent = new Intent(NotificationListenerService.SERVICE_INTERFACE);
615            intent.setComponent(name);
616
617            intent.putExtra(Intent.EXTRA_CLIENT_LABEL,
618                    R.string.notification_listener_binding_label);
619
620            final PendingIntent pendingIntent = PendingIntent.getActivity(
621                    getContext(), 0, new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS), 0);
622            intent.putExtra(Intent.EXTRA_CLIENT_INTENT, pendingIntent);
623
624            try {
625                if (DBG) Slog.v(TAG, "binding: " + intent);
626                if (!getContext().bindServiceAsUser(intent,
627                        new ServiceConnection() {
628                            INotificationListener mListener;
629
630                            @Override
631                            public void onServiceConnected(ComponentName name, IBinder service) {
632                                synchronized (mNotificationList) {
633                                    mServicesBinding.remove(servicesBindingTag);
634                                    try {
635                                        mListener = INotificationListener.Stub.asInterface(service);
636                                        NotificationListenerInfo info
637                                                = new NotificationListenerInfo(
638                                                mListener, name, userid, this);
639                                        service.linkToDeath(info, 0);
640                                        mListeners.add(info);
641                                    } catch (RemoteException e) {
642                                        // already dead
643                                    }
644                                }
645                            }
646
647                            @Override
648                            public void onServiceDisconnected(ComponentName name) {
649                                Slog.v(TAG, "notification listener connection lost: " + name);
650                            }
651                        },
652                        Context.BIND_AUTO_CREATE,
653                        new UserHandle(userid)))
654                {
655                    mServicesBinding.remove(servicesBindingTag);
656                    Slog.w(TAG, "Unable to bind listener service: " + intent);
657                    return;
658                }
659            } catch (SecurityException ex) {
660                Slog.e(TAG, "Unable to bind listener service: " + intent, ex);
661                return;
662            }
663        }
664    }
665
666
667    /**
668     * Remove a listener service for the given user by ComponentName
669     */
670    private void unregisterListenerService(ComponentName name, int userid) {
671        checkCallerIsSystem();
672
673        synchronized (mNotificationList) {
674            final int N = mListeners.size();
675            for (int i=N-1; i>=0; i--) {
676                final NotificationListenerInfo info = mListeners.get(i);
677                if (name.equals(info.component)
678                        && info.userid == userid) {
679                    mListeners.remove(i);
680                    if (info.connection != null) {
681                        try {
682                            getContext().unbindService(info.connection);
683                        } catch (IllegalArgumentException ex) {
684                            // something happened to the service: we think we have a connection
685                            // but it's bogus.
686                            Slog.e(TAG, "Listener " + name + " could not be unbound: " + ex);
687                        }
688                    }
689                }
690            }
691        }
692    }
693
694    /**
695     * asynchronously notify all listeners about a new notification
696     */
697    void notifyPostedLocked(NotificationRecord n) {
698        // make a copy in case changes are made to the underlying Notification object
699        final StatusBarNotification sbn = n.sbn.clone();
700        for (final NotificationListenerInfo info : mListeners) {
701            mHandler.post(new Runnable() {
702                @Override
703                public void run() {
704                    info.notifyPostedIfUserMatch(sbn);
705                }});
706        }
707    }
708
709    /**
710     * asynchronously notify all listeners about a removed notification
711     */
712    void notifyRemovedLocked(NotificationRecord n) {
713        // make a copy in case changes are made to the underlying Notification object
714        // NOTE: this copy is lightweight: it doesn't include heavyweight parts of the notification
715        final StatusBarNotification sbn_light = n.sbn.cloneLight();
716
717        for (final NotificationListenerInfo info : mListeners) {
718            mHandler.post(new Runnable() {
719                @Override
720                public void run() {
721                    info.notifyRemovedIfUserMatch(sbn_light);
722                }});
723        }
724    }
725
726    // -- APIs to support listeners clicking/clearing notifications --
727
728    private NotificationListenerInfo checkListenerToken(INotificationListener listener) {
729        final IBinder token = listener.asBinder();
730        final int N = mListeners.size();
731        for (int i=0; i<N; i++) {
732            final NotificationListenerInfo info = mListeners.get(i);
733            if (info.listener.asBinder() == token) return info;
734        }
735        throw new SecurityException("Disallowed call from unknown listener: " + listener);
736    }
737
738
739
740    // -- end of listener APIs --
741
742    public static final class NotificationRecord
743    {
744        final StatusBarNotification sbn;
745        IBinder statusBarKey;
746
747        NotificationRecord(StatusBarNotification sbn)
748        {
749            this.sbn = sbn;
750        }
751
752        public Notification getNotification() { return sbn.getNotification(); }
753        public int getFlags() { return sbn.getNotification().flags; }
754        public int getUserId() { return sbn.getUserId(); }
755
756        void dump(PrintWriter pw, String prefix, Context baseContext) {
757            final Notification notification = sbn.getNotification();
758            pw.println(prefix + this);
759            pw.println(prefix + "  uid=" + sbn.getUid() + " userId=" + sbn.getUserId());
760            pw.println(prefix + "  icon=0x" + Integer.toHexString(notification.icon)
761                    + " / " + idDebugString(baseContext, sbn.getPackageName(), notification.icon));
762            pw.println(prefix + "  pri=" + notification.priority + " score=" + sbn.getScore());
763            pw.println(prefix + "  contentIntent=" + notification.contentIntent);
764            pw.println(prefix + "  deleteIntent=" + notification.deleteIntent);
765            pw.println(prefix + "  tickerText=" + notification.tickerText);
766            pw.println(prefix + "  contentView=" + notification.contentView);
767            pw.println(prefix + String.format("  defaults=0x%08x flags=0x%08x",
768                    notification.defaults, notification.flags));
769            pw.println(prefix + "  sound=" + notification.sound);
770            pw.println(prefix + "  vibrate=" + Arrays.toString(notification.vibrate));
771            pw.println(prefix + String.format("  led=0x%08x onMs=%d offMs=%d",
772                    notification.ledARGB, notification.ledOnMS, notification.ledOffMS));
773            if (notification.actions != null && notification.actions.length > 0) {
774                pw.println(prefix + "  actions={");
775                final int N = notification.actions.length;
776                for (int i=0; i<N; i++) {
777                    final Notification.Action action = notification.actions[i];
778                    pw.println(String.format("%s    [%d] \"%s\" -> %s",
779                            prefix,
780                            i,
781                            action.title,
782                            action.actionIntent.toString()
783                            ));
784                }
785                pw.println(prefix + "  }");
786            }
787            if (notification.extras != null && notification.extras.size() > 0) {
788                pw.println(prefix + "  extras={");
789                for (String key : notification.extras.keySet()) {
790                    pw.print(prefix + "    " + key + "=");
791                    Object val = notification.extras.get(key);
792                    if (val == null) {
793                        pw.println("null");
794                    } else {
795                        pw.print(val.toString());
796                        if (val instanceof Bitmap) {
797                            pw.print(String.format(" (%dx%d)",
798                                    ((Bitmap) val).getWidth(),
799                                    ((Bitmap) val).getHeight()));
800                        } else if (val.getClass().isArray()) {
801                            pw.println(" {");
802                            final int N = Array.getLength(val);
803                            for (int i=0; i<N; i++) {
804                                if (i > 0) pw.println(",");
805                                pw.print(prefix + "      " + Array.get(val, i));
806                            }
807                            pw.print("\n" + prefix + "    }");
808                        }
809                        pw.println();
810                    }
811                }
812                pw.println(prefix + "  }");
813            }
814        }
815
816        @Override
817        public final String toString() {
818            return String.format(
819                    "NotificationRecord(0x%08x: pkg=%s user=%s id=%d tag=%s score=%d: %s)",
820                    System.identityHashCode(this),
821                    this.sbn.getPackageName(), this.sbn.getUser(), this.sbn.getId(),
822                    this.sbn.getTag(), this.sbn.getScore(), this.sbn.getNotification());
823        }
824    }
825
826    private static final class ToastRecord
827    {
828        final int pid;
829        final String pkg;
830        final ITransientNotification callback;
831        int duration;
832
833        ToastRecord(int pid, String pkg, ITransientNotification callback, int duration)
834        {
835            this.pid = pid;
836            this.pkg = pkg;
837            this.callback = callback;
838            this.duration = duration;
839        }
840
841        void update(int duration) {
842            this.duration = duration;
843        }
844
845        void dump(PrintWriter pw, String prefix) {
846            pw.println(prefix + this);
847        }
848
849        @Override
850        public final String toString()
851        {
852            return "ToastRecord{"
853                + Integer.toHexString(System.identityHashCode(this))
854                + " pkg=" + pkg
855                + " callback=" + callback
856                + " duration=" + duration;
857        }
858    }
859
860    private final NotificationDelegate mNotificationDelegate = new NotificationDelegate() {
861
862        @Override
863        public void onSetDisabled(int status) {
864            synchronized (mNotificationList) {
865                mDisabledNotifications = status;
866                if ((mDisabledNotifications & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) {
867                    // cancel whatever's going on
868                    long identity = Binder.clearCallingIdentity();
869                    try {
870                        final IRingtonePlayer player = mAudioManager.getRingtonePlayer();
871                        if (player != null) {
872                            player.stopAsync();
873                        }
874                    } catch (RemoteException e) {
875                    } finally {
876                        Binder.restoreCallingIdentity(identity);
877                    }
878
879                    identity = Binder.clearCallingIdentity();
880                    try {
881                        mVibrator.cancel();
882                    } finally {
883                        Binder.restoreCallingIdentity(identity);
884                    }
885                }
886            }
887        }
888
889        @Override
890        public void onClearAll() {
891            // XXX to be totally correct, the caller should tell us which user
892            // this is for.
893            cancelAll(ActivityManager.getCurrentUser());
894        }
895
896        @Override
897        public void onNotificationClick(String pkg, String tag, int id) {
898            // XXX to be totally correct, the caller should tell us which user
899            // this is for.
900            cancelNotification(pkg, tag, id, Notification.FLAG_AUTO_CANCEL,
901                    Notification.FLAG_FOREGROUND_SERVICE, false,
902                    ActivityManager.getCurrentUser());
903        }
904
905        @Override
906        public void onNotificationClear(String pkg, String tag, int id) {
907            // XXX to be totally correct, the caller should tell us which user
908            // this is for.
909            cancelNotification(pkg, tag, id, 0,
910                Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE,
911                true, ActivityManager.getCurrentUser());
912        }
913
914        @Override
915        public void onPanelRevealed() {
916            synchronized (mNotificationList) {
917                // sound
918                mSoundNotification = null;
919
920                long identity = Binder.clearCallingIdentity();
921                try {
922                    final IRingtonePlayer player = mAudioManager.getRingtonePlayer();
923                    if (player != null) {
924                        player.stopAsync();
925                    }
926                } catch (RemoteException e) {
927                } finally {
928                    Binder.restoreCallingIdentity(identity);
929                }
930
931                // vibrate
932                mVibrateNotification = null;
933                identity = Binder.clearCallingIdentity();
934                try {
935                    mVibrator.cancel();
936                } finally {
937                    Binder.restoreCallingIdentity(identity);
938                }
939
940                // light
941                mLights.clear();
942                mLedNotification = null;
943                updateLightsLocked();
944            }
945        }
946
947        @Override
948        public void onNotificationError(String pkg, String tag, int id,
949                int uid, int initialPid, String message) {
950            Slog.d(TAG, "onNotification error pkg=" + pkg + " tag=" + tag + " id=" + id
951                    + "; will crashApplication(uid=" + uid + ", pid=" + initialPid + ")");
952            // XXX to be totally correct, the caller should tell us which user
953            // this is for.
954            cancelNotification(pkg, tag, id, 0, 0, false, UserHandle.getUserId(uid));
955            long ident = Binder.clearCallingIdentity();
956            try {
957                ActivityManagerNative.getDefault().crashApplication(uid, initialPid, pkg,
958                        "Bad notification posted from package " + pkg
959                        + ": " + message);
960            } catch (RemoteException e) {
961            }
962            Binder.restoreCallingIdentity(ident);
963        }
964    };
965
966    private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
967        @Override
968        public void onReceive(Context context, Intent intent) {
969            String action = intent.getAction();
970
971            boolean queryRestart = false;
972            boolean queryRemove = false;
973            boolean packageChanged = false;
974            boolean cancelNotifications = true;
975
976            if (action.equals(Intent.ACTION_PACKAGE_ADDED)
977                    || (queryRemove=action.equals(Intent.ACTION_PACKAGE_REMOVED))
978                    || action.equals(Intent.ACTION_PACKAGE_RESTARTED)
979                    || (packageChanged=action.equals(Intent.ACTION_PACKAGE_CHANGED))
980                    || (queryRestart=action.equals(Intent.ACTION_QUERY_PACKAGE_RESTART))
981                    || action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)) {
982                String pkgList[] = null;
983                boolean queryReplace = queryRemove &&
984                        intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
985                if (DBG) Slog.i(TAG, "queryReplace=" + queryReplace);
986                if (action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)) {
987                    pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
988                } else if (queryRestart) {
989                    pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
990                } else {
991                    Uri uri = intent.getData();
992                    if (uri == null) {
993                        return;
994                    }
995                    String pkgName = uri.getSchemeSpecificPart();
996                    if (pkgName == null) {
997                        return;
998                    }
999                    if (packageChanged) {
1000                        // We cancel notifications for packages which have just been disabled
1001                        try {
1002                            final int enabled = getContext().getPackageManager()
1003                                    .getApplicationEnabledSetting(pkgName);
1004                            if (enabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
1005                                    || enabled == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
1006                                cancelNotifications = false;
1007                            }
1008                        } catch (IllegalArgumentException e) {
1009                            // Package doesn't exist; probably racing with uninstall.
1010                            // cancelNotifications is already true, so nothing to do here.
1011                            if (DBG) {
1012                                Slog.i(TAG, "Exception trying to look up app enabled setting", e);
1013                            }
1014                        }
1015                    }
1016                    pkgList = new String[]{pkgName};
1017                }
1018
1019                boolean anyListenersInvolved = false;
1020                if (pkgList != null && (pkgList.length > 0)) {
1021                    for (String pkgName : pkgList) {
1022                        if (cancelNotifications) {
1023                            cancelAllNotificationsInt(pkgName, 0, 0, !queryRestart,
1024                                    UserHandle.USER_ALL);
1025                        }
1026                        if (mEnabledListenerPackageNames.contains(pkgName)) {
1027                            anyListenersInvolved = true;
1028                        }
1029                    }
1030                }
1031
1032                if (anyListenersInvolved) {
1033                    // if we're not replacing a package, clean up orphaned bits
1034                    if (!queryReplace) {
1035                        disableNonexistentListeners();
1036                    }
1037                    // make sure we're still bound to any of our
1038                    // listeners who may have just upgraded
1039                    rebindListenerServices();
1040                }
1041            } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
1042                // Keep track of screen on/off state, but do not turn off the notification light
1043                // until user passes through the lock screen or views the notification.
1044                mScreenOn = true;
1045            } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
1046                mScreenOn = false;
1047            } else if (action.equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
1048                mInCall = (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
1049                        TelephonyManager.EXTRA_STATE_OFFHOOK));
1050                updateNotificationPulse();
1051            } else if (action.equals(Intent.ACTION_USER_STOPPED)) {
1052                int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
1053                if (userHandle >= 0) {
1054                    cancelAllNotificationsInt(null, 0, 0, true, userHandle);
1055                }
1056            } else if (action.equals(Intent.ACTION_USER_PRESENT)) {
1057                // turn off LED when user passes through lock screen
1058                mNotificationLight.turnOff();
1059            } else if (action.equals(Intent.ACTION_USER_SWITCHED)) {
1060                // reload per-user settings
1061                mSettingsObserver.update(null);
1062            }
1063        }
1064    };
1065
1066    class SettingsObserver extends ContentObserver {
1067        private final Uri NOTIFICATION_LIGHT_PULSE_URI
1068                = Settings.System.getUriFor(Settings.System.NOTIFICATION_LIGHT_PULSE);
1069
1070        private final Uri ENABLED_NOTIFICATION_LISTENERS_URI
1071                = Settings.Secure.getUriFor(Settings.Secure.ENABLED_NOTIFICATION_LISTENERS);
1072
1073        SettingsObserver(Handler handler) {
1074            super(handler);
1075        }
1076
1077        void observe() {
1078            ContentResolver resolver = getContext().getContentResolver();
1079            resolver.registerContentObserver(NOTIFICATION_LIGHT_PULSE_URI,
1080                    false, this, UserHandle.USER_ALL);
1081            resolver.registerContentObserver(ENABLED_NOTIFICATION_LISTENERS_URI,
1082                    false, this, UserHandle.USER_ALL);
1083            update(null);
1084        }
1085
1086        @Override public void onChange(boolean selfChange, Uri uri) {
1087            update(uri);
1088        }
1089
1090        public void update(Uri uri) {
1091            ContentResolver resolver = getContext().getContentResolver();
1092            if (uri == null || NOTIFICATION_LIGHT_PULSE_URI.equals(uri)) {
1093                boolean pulseEnabled = Settings.System.getInt(resolver,
1094                            Settings.System.NOTIFICATION_LIGHT_PULSE, 0) != 0;
1095                if (mNotificationPulseEnabled != pulseEnabled) {
1096                    mNotificationPulseEnabled = pulseEnabled;
1097                    updateNotificationPulse();
1098                }
1099            }
1100            if (uri == null || ENABLED_NOTIFICATION_LISTENERS_URI.equals(uri)) {
1101                rebindListenerServices();
1102            }
1103        }
1104    }
1105
1106    private SettingsObserver mSettingsObserver;
1107
1108    static long[] getLongArray(Resources r, int resid, int maxlen, long[] def) {
1109        int[] ar = r.getIntArray(resid);
1110        if (ar == null) {
1111            return def;
1112        }
1113        final int len = ar.length > maxlen ? maxlen : ar.length;
1114        long[] out = new long[len];
1115        for (int i=0; i<len; i++) {
1116            out[i] = ar[i];
1117        }
1118        return out;
1119    }
1120
1121    public NotificationManagerService(Context context) {
1122        super(context);
1123    }
1124
1125    @Override
1126    public void onStart() {
1127        mAm = ActivityManagerNative.getDefault();
1128        mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
1129        mVibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE);
1130
1131        mHandler = new WorkerHandler();
1132
1133        importOldBlockDb();
1134
1135        mStatusBar = getLocalService(StatusBarManagerInternal.class);
1136        mStatusBar.setNotificationDelegate(mNotificationDelegate);
1137
1138        final LightsManager lights = getLocalService(LightsManager.class);
1139        mNotificationLight = lights.getLight(LightsManager.LIGHT_ID_NOTIFICATIONS);
1140        mAttentionLight = lights.getLight(LightsManager.LIGHT_ID_ATTENTION);
1141
1142        Resources resources = getContext().getResources();
1143        mDefaultNotificationColor = resources.getColor(
1144                R.color.config_defaultNotificationColor);
1145        mDefaultNotificationLedOn = resources.getInteger(
1146                R.integer.config_defaultNotificationLedOn);
1147        mDefaultNotificationLedOff = resources.getInteger(
1148                R.integer.config_defaultNotificationLedOff);
1149
1150        mDefaultVibrationPattern = getLongArray(resources,
1151                R.array.config_defaultNotificationVibePattern,
1152                VIBRATE_PATTERN_MAXLEN,
1153                DEFAULT_VIBRATE_PATTERN);
1154
1155        mFallbackVibrationPattern = getLongArray(resources,
1156                R.array.config_notificationFallbackVibePattern,
1157                VIBRATE_PATTERN_MAXLEN,
1158                DEFAULT_VIBRATE_PATTERN);
1159
1160        // Don't start allowing notifications until the setup wizard has run once.
1161        // After that, including subsequent boots, init with notifications turned on.
1162        // This works on the first boot because the setup wizard will toggle this
1163        // flag at least once and we'll go back to 0 after that.
1164        if (0 == Settings.Global.getInt(getContext().getContentResolver(),
1165                    Settings.Global.DEVICE_PROVISIONED, 0)) {
1166            mDisabledNotifications = StatusBarManager.DISABLE_NOTIFICATION_ALERTS;
1167        }
1168
1169        // register for various Intents
1170        IntentFilter filter = new IntentFilter();
1171        filter.addAction(Intent.ACTION_SCREEN_ON);
1172        filter.addAction(Intent.ACTION_SCREEN_OFF);
1173        filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
1174        filter.addAction(Intent.ACTION_USER_PRESENT);
1175        filter.addAction(Intent.ACTION_USER_STOPPED);
1176        filter.addAction(Intent.ACTION_USER_SWITCHED);
1177        getContext().registerReceiver(mIntentReceiver, filter);
1178        IntentFilter pkgFilter = new IntentFilter();
1179        pkgFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1180        pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1181        pkgFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1182        pkgFilter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
1183        pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
1184        pkgFilter.addDataScheme("package");
1185        getContext().registerReceiver(mIntentReceiver, pkgFilter);
1186        IntentFilter sdFilter = new IntentFilter(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1187        getContext().registerReceiver(mIntentReceiver, sdFilter);
1188
1189        mSettingsObserver = new SettingsObserver(mHandler);
1190        mSettingsObserver.observe();
1191
1192        // spin up NotificationScorers
1193        String[] notificationScorerNames = resources.getStringArray(
1194                R.array.config_notificationScorers);
1195        for (String scorerName : notificationScorerNames) {
1196            try {
1197                Class<?> scorerClass = getContext().getClassLoader().loadClass(scorerName);
1198                NotificationScorer scorer = (NotificationScorer) scorerClass.newInstance();
1199                scorer.initialize(getContext());
1200                mScorers.add(scorer);
1201            } catch (ClassNotFoundException e) {
1202                Slog.w(TAG, "Couldn't find scorer " + scorerName + ".", e);
1203            } catch (InstantiationException e) {
1204                Slog.w(TAG, "Couldn't instantiate scorer " + scorerName + ".", e);
1205            } catch (IllegalAccessException e) {
1206                Slog.w(TAG, "Problem accessing scorer " + scorerName + ".", e);
1207            }
1208        }
1209
1210        publishBinderService(Context.NOTIFICATION_SERVICE, mService);
1211        publishLocalService(NotificationManagerInternal.class, mInternalService);
1212    }
1213
1214    /**
1215     * Read the old XML-based app block database and import those blockages into the AppOps system.
1216     */
1217    private void importOldBlockDb() {
1218        loadBlockDb();
1219
1220        PackageManager pm = getContext().getPackageManager();
1221        for (String pkg : mBlockedPackages) {
1222            PackageInfo info = null;
1223            try {
1224                info = pm.getPackageInfo(pkg, 0);
1225                setNotificationsEnabledForPackageImpl(pkg, info.applicationInfo.uid, false);
1226            } catch (NameNotFoundException e) {
1227                // forget you
1228            }
1229        }
1230        mBlockedPackages.clear();
1231        if (mPolicyFile != null) {
1232            mPolicyFile.delete();
1233        }
1234    }
1235
1236    @Override
1237    public void onBootPhase(int phase) {
1238        if (phase == SystemService.PHASE_SYSTEM_SERVICES_READY) {
1239            // no beeping until we're basically done booting
1240            mSystemReady = true;
1241
1242            // Grab our optional AudioService
1243            mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
1244
1245            // make sure our listener services are properly bound
1246            rebindListenerServices();
1247        }
1248    }
1249
1250    void setNotificationsEnabledForPackageImpl(String pkg, int uid, boolean enabled) {
1251        Slog.v(TAG, (enabled?"en":"dis") + "abling notifications for " + pkg);
1252
1253        mAppOps.setMode(AppOpsManager.OP_POST_NOTIFICATION, uid, pkg,
1254                enabled ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
1255
1256        // Now, cancel any outstanding notifications that are part of a just-disabled app
1257        if (ENABLE_BLOCKED_NOTIFICATIONS && !enabled) {
1258            cancelAllNotificationsInt(pkg, 0, 0, true, UserHandle.getUserId(uid));
1259        }
1260    }
1261
1262    private final IBinder mService = new INotificationManager.Stub() {
1263        // Toasts
1264        // ============================================================================
1265
1266        @Override
1267        public void enqueueToast(String pkg, ITransientNotification callback, int duration)
1268        {
1269            if (DBG) {
1270                Slog.i(TAG, "enqueueToast pkg=" + pkg + " callback=" + callback
1271                        + " duration=" + duration);
1272            }
1273
1274            if (pkg == null || callback == null) {
1275                Slog.e(TAG, "Not doing toast. pkg=" + pkg + " callback=" + callback);
1276                return ;
1277            }
1278
1279            final boolean isSystemToast = isCallerSystem() || ("android".equals(pkg));
1280
1281            if (ENABLE_BLOCKED_TOASTS && !noteNotificationOp(pkg, Binder.getCallingUid())) {
1282                if (!isSystemToast) {
1283                    Slog.e(TAG, "Suppressing toast from package " + pkg + " by user request.");
1284                    return;
1285                }
1286            }
1287
1288            synchronized (mToastQueue) {
1289                int callingPid = Binder.getCallingPid();
1290                long callingId = Binder.clearCallingIdentity();
1291                try {
1292                    ToastRecord record;
1293                    int index = indexOfToastLocked(pkg, callback);
1294                    // If it's already in the queue, we update it in place, we don't
1295                    // move it to the end of the queue.
1296                    if (index >= 0) {
1297                        record = mToastQueue.get(index);
1298                        record.update(duration);
1299                    } else {
1300                        // Limit the number of toasts that any given package except the android
1301                        // package can enqueue.  Prevents DOS attacks and deals with leaks.
1302                        if (!isSystemToast) {
1303                            int count = 0;
1304                            final int N = mToastQueue.size();
1305                            for (int i=0; i<N; i++) {
1306                                 final ToastRecord r = mToastQueue.get(i);
1307                                 if (r.pkg.equals(pkg)) {
1308                                     count++;
1309                                     if (count >= MAX_PACKAGE_NOTIFICATIONS) {
1310                                         Slog.e(TAG, "Package has already posted " + count
1311                                                + " toasts. Not showing more. Package=" + pkg);
1312                                         return;
1313                                     }
1314                                 }
1315                            }
1316                        }
1317
1318                        record = new ToastRecord(callingPid, pkg, callback, duration);
1319                        mToastQueue.add(record);
1320                        index = mToastQueue.size() - 1;
1321                        keepProcessAliveLocked(callingPid);
1322                    }
1323                    // If it's at index 0, it's the current toast.  It doesn't matter if it's
1324                    // new or just been updated.  Call back and tell it to show itself.
1325                    // If the callback fails, this will remove it from the list, so don't
1326                    // assume that it's valid after this.
1327                    if (index == 0) {
1328                        showNextToastLocked();
1329                    }
1330                } finally {
1331                    Binder.restoreCallingIdentity(callingId);
1332                }
1333            }
1334        }
1335
1336        @Override
1337        public void cancelToast(String pkg, ITransientNotification callback) {
1338            Slog.i(TAG, "cancelToast pkg=" + pkg + " callback=" + callback);
1339
1340            if (pkg == null || callback == null) {
1341                Slog.e(TAG, "Not cancelling notification. pkg=" + pkg + " callback=" + callback);
1342                return ;
1343            }
1344
1345            synchronized (mToastQueue) {
1346                long callingId = Binder.clearCallingIdentity();
1347                try {
1348                    int index = indexOfToastLocked(pkg, callback);
1349                    if (index >= 0) {
1350                        cancelToastLocked(index);
1351                    } else {
1352                        Slog.w(TAG, "Toast already cancelled. pkg=" + pkg
1353                                + " callback=" + callback);
1354                    }
1355                } finally {
1356                    Binder.restoreCallingIdentity(callingId);
1357                }
1358            }
1359        }
1360
1361        @Override
1362        public void enqueueNotificationWithTag(String pkg, String basePkg, String tag, int id,
1363                Notification notification, int[] idOut, int userId) throws RemoteException {
1364            enqueueNotificationInternal(pkg, basePkg, Binder.getCallingUid(),
1365                    Binder.getCallingPid(), tag, id, notification, idOut, userId);
1366        }
1367
1368        @Override
1369        public void cancelNotificationWithTag(String pkg, String tag, int id, int userId) {
1370            checkCallerIsSystemOrSameApp(pkg);
1371            userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1372                    Binder.getCallingUid(), userId, true, false, "cancelNotificationWithTag", pkg);
1373            // Don't allow client applications to cancel foreground service notis.
1374            cancelNotification(pkg, tag, id, 0,
1375                    Binder.getCallingUid() == Process.SYSTEM_UID
1376                    ? 0 : Notification.FLAG_FOREGROUND_SERVICE, false, userId);
1377        }
1378
1379        @Override
1380        public void cancelAllNotifications(String pkg, int userId) {
1381            checkCallerIsSystemOrSameApp(pkg);
1382
1383            userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1384                    Binder.getCallingUid(), userId, true, false, "cancelAllNotifications", pkg);
1385
1386            // Calling from user space, don't allow the canceling of actively
1387            // running foreground services.
1388            cancelAllNotificationsInt(pkg, 0, Notification.FLAG_FOREGROUND_SERVICE, true, userId);
1389        }
1390
1391        @Override
1392        public void setNotificationsEnabledForPackage(String pkg, int uid, boolean enabled) {
1393            checkCallerIsSystem();
1394
1395            setNotificationsEnabledForPackageImpl(pkg, uid, enabled);
1396        }
1397
1398        /**
1399         * Use this when you just want to know if notifications are OK for this package.
1400         */
1401        @Override
1402        public boolean areNotificationsEnabledForPackage(String pkg, int uid) {
1403            checkCallerIsSystem();
1404            return (mAppOps.checkOpNoThrow(AppOpsManager.OP_POST_NOTIFICATION, uid, pkg)
1405                    == AppOpsManager.MODE_ALLOWED);
1406        }
1407
1408        /**
1409         * System-only API for getting a list of current (i.e. not cleared) notifications.
1410         *
1411         * Requires ACCESS_NOTIFICATIONS which is signature|system.
1412         */
1413        @Override
1414        public StatusBarNotification[] getActiveNotifications(String callingPkg) {
1415            // enforce() will ensure the calling uid has the correct permission
1416            getContext().enforceCallingOrSelfPermission(
1417                    android.Manifest.permission.ACCESS_NOTIFICATIONS,
1418                    "NotificationManagerService.getActiveNotifications");
1419
1420            StatusBarNotification[] tmp = null;
1421            int uid = Binder.getCallingUid();
1422
1423            // noteOp will check to make sure the callingPkg matches the uid
1424            if (mAppOps.noteOpNoThrow(AppOpsManager.OP_ACCESS_NOTIFICATIONS, uid, callingPkg)
1425                    == AppOpsManager.MODE_ALLOWED) {
1426                synchronized (mNotificationList) {
1427                    tmp = new StatusBarNotification[mNotificationList.size()];
1428                    final int N = mNotificationList.size();
1429                    for (int i=0; i<N; i++) {
1430                        tmp[i] = mNotificationList.get(i).sbn;
1431                    }
1432                }
1433            }
1434            return tmp;
1435        }
1436
1437        /**
1438         * System-only API for getting a list of recent (cleared, no longer shown) notifications.
1439         *
1440         * Requires ACCESS_NOTIFICATIONS which is signature|system.
1441         */
1442        @Override
1443        public StatusBarNotification[] getHistoricalNotifications(String callingPkg, int count) {
1444            // enforce() will ensure the calling uid has the correct permission
1445            getContext().enforceCallingOrSelfPermission(
1446                    android.Manifest.permission.ACCESS_NOTIFICATIONS,
1447                    "NotificationManagerService.getHistoricalNotifications");
1448
1449            StatusBarNotification[] tmp = null;
1450            int uid = Binder.getCallingUid();
1451
1452            // noteOp will check to make sure the callingPkg matches the uid
1453            if (mAppOps.noteOpNoThrow(AppOpsManager.OP_ACCESS_NOTIFICATIONS, uid, callingPkg)
1454                    == AppOpsManager.MODE_ALLOWED) {
1455                synchronized (mArchive) {
1456                    tmp = mArchive.getArray(count);
1457                }
1458            }
1459            return tmp;
1460        }
1461
1462        /**
1463         * Register a listener binder directly with the notification manager.
1464         *
1465         * Only works with system callers. Apps should extend
1466         * {@link android.service.notification.NotificationListenerService}.
1467         */
1468        @Override
1469        public void registerListener(final INotificationListener listener,
1470                final ComponentName component, final int userid) {
1471            checkCallerIsSystem();
1472            registerListenerImpl(listener, component, userid);
1473        }
1474
1475        /**
1476         * Remove a listener binder directly
1477         */
1478        @Override
1479        public void unregisterListener(INotificationListener listener, int userid) {
1480            // no need to check permissions; if your listener binder is in the list,
1481            // that's proof that you had permission to add it in the first place
1482            unregisterListenerImpl(listener, userid);
1483        }
1484
1485        /**
1486         * Allow an INotificationListener to simulate a "clear all" operation.
1487         *
1488         * {@see com.android.server.StatusBarManagerService.NotificationCallbacks#onClearAllNotifications}
1489         *
1490         * @param token The binder for the listener, to check that the caller is allowed
1491         */
1492        @Override
1493        public void cancelAllNotificationsFromListener(INotificationListener token) {
1494            NotificationListenerInfo info = checkListenerToken(token);
1495            long identity = Binder.clearCallingIdentity();
1496            try {
1497                cancelAll(info.userid);
1498            } finally {
1499                Binder.restoreCallingIdentity(identity);
1500            }
1501        }
1502
1503        /**
1504         * Allow an INotificationListener to simulate clearing (dismissing) a single notification.
1505         *
1506         * {@see com.android.server.StatusBarManagerService.NotificationCallbacks#onNotificationClear}
1507         *
1508         * @param token The binder for the listener, to check that the caller is allowed
1509         */
1510        @Override
1511        public void cancelNotificationFromListener(INotificationListener token, String pkg,
1512                String tag, int id) {
1513            NotificationListenerInfo info = checkListenerToken(token);
1514            long identity = Binder.clearCallingIdentity();
1515            try {
1516                cancelNotification(pkg, tag, id, 0,
1517                        Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE,
1518                        true,
1519                        info.userid);
1520            } finally {
1521                Binder.restoreCallingIdentity(identity);
1522            }
1523        }
1524
1525        /**
1526         * Allow an INotificationListener to request the list of outstanding notifications seen by
1527         * the current user. Useful when starting up, after which point the listener callbacks
1528         * should be used.
1529         *
1530         * @param token The binder for the listener, to check that the caller is allowed
1531         */
1532        @Override
1533        public StatusBarNotification[] getActiveNotificationsFromListener(
1534                INotificationListener token) {
1535            NotificationListenerInfo info = checkListenerToken(token);
1536
1537            StatusBarNotification[] result = new StatusBarNotification[0];
1538            ArrayList<StatusBarNotification> list = new ArrayList<StatusBarNotification>();
1539            synchronized (mNotificationList) {
1540                final int N = mNotificationList.size();
1541                for (int i=0; i<N; i++) {
1542                    StatusBarNotification sbn = mNotificationList.get(i).sbn;
1543                    if (info.enabledAndUserMatches(sbn)) {
1544                        list.add(sbn);
1545                    }
1546                }
1547            }
1548            return list.toArray(result);
1549        }
1550
1551        @Override
1552        protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1553            if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1554                    != PackageManager.PERMISSION_GRANTED) {
1555                pw.println("Permission Denial: can't dump NotificationManager from from pid="
1556                        + Binder.getCallingPid()
1557                        + ", uid=" + Binder.getCallingUid());
1558                return;
1559            }
1560
1561            dumpImpl(pw);
1562        }
1563    };
1564
1565    void dumpImpl(PrintWriter pw) {
1566        pw.println("Current Notification Manager state:");
1567
1568        pw.println("  Listeners (" + mEnabledListenersForCurrentUser.size()
1569                + ") enabled for current user:");
1570        for (ComponentName cmpt : mEnabledListenersForCurrentUser) {
1571            pw.println("    " + cmpt);
1572        }
1573
1574        pw.println("  Live listeners (" + mListeners.size() + "):");
1575        for (NotificationListenerInfo info : mListeners) {
1576            pw.println("    " + info.component
1577                    + " (user " + info.userid + "): " + info.listener
1578                    + (info.isSystem?" SYSTEM":""));
1579        }
1580
1581        int N;
1582
1583        synchronized (mToastQueue) {
1584            N = mToastQueue.size();
1585            if (N > 0) {
1586                pw.println("  Toast Queue:");
1587                for (int i=0; i<N; i++) {
1588                    mToastQueue.get(i).dump(pw, "    ");
1589                }
1590                pw.println("  ");
1591            }
1592
1593        }
1594
1595        synchronized (mNotificationList) {
1596            N = mNotificationList.size();
1597            if (N > 0) {
1598                pw.println("  Notification List:");
1599                for (int i=0; i<N; i++) {
1600                    mNotificationList.get(i).dump(pw, "    ", getContext());
1601                }
1602                pw.println("  ");
1603            }
1604
1605            N = mLights.size();
1606            if (N > 0) {
1607                pw.println("  Lights List:");
1608                for (int i=0; i<N; i++) {
1609                    pw.println("    " + mLights.get(i));
1610                }
1611                pw.println("  ");
1612            }
1613
1614            pw.println("  mSoundNotification=" + mSoundNotification);
1615            pw.println("  mVibrateNotification=" + mVibrateNotification);
1616            pw.println("  mDisabledNotifications=0x"
1617                    + Integer.toHexString(mDisabledNotifications));
1618            pw.println("  mSystemReady=" + mSystemReady);
1619            pw.println("  mArchive=" + mArchive.toString());
1620            Iterator<StatusBarNotification> iter = mArchive.descendingIterator();
1621            int i=0;
1622            while (iter.hasNext()) {
1623                pw.println("    " + iter.next());
1624                if (++i >= 5) {
1625                    if (iter.hasNext()) pw.println("    ...");
1626                    break;
1627                }
1628            }
1629
1630        }
1631    }
1632
1633    /**
1634     * The private API only accessible to the system process.
1635     */
1636    private final NotificationManagerInternal mInternalService = new NotificationManagerInternal() {
1637        @Override
1638        public void enqueueNotification(String pkg, String basePkg, int callingUid, int callingPid,
1639                String tag, int id, Notification notification, int[] idReceived, int userId) {
1640            enqueueNotificationInternal(pkg, basePkg, callingUid, callingPid, tag, id, notification,
1641                    idReceived, userId);
1642        }
1643    };
1644
1645    void enqueueNotificationInternal(final String pkg, String basePkg, final int callingUid,
1646            final int callingPid, final String tag, final int id, final Notification notification,
1647            int[] idOut, int incomingUserId) {
1648        if (DBG) {
1649            Slog.v(TAG, "enqueueNotificationInternal: pkg=" + pkg + " id=" + id
1650                    + " notification=" + notification);
1651        }
1652        checkCallerIsSystemOrSameApp(pkg);
1653        final boolean isSystemNotification = isUidSystem(callingUid) || ("android".equals(pkg));
1654
1655        final int userId = ActivityManager.handleIncomingUser(callingPid,
1656                callingUid, incomingUserId, true, false, "enqueueNotification", pkg);
1657        final UserHandle user = new UserHandle(userId);
1658
1659        // Limit the number of notifications that any given package except the android
1660        // package can enqueue.  Prevents DOS attacks and deals with leaks.
1661        if (!isSystemNotification) {
1662            synchronized (mNotificationList) {
1663                int count = 0;
1664                final int N = mNotificationList.size();
1665                for (int i=0; i<N; i++) {
1666                    final NotificationRecord r = mNotificationList.get(i);
1667                    if (r.sbn.getPackageName().equals(pkg) && r.sbn.getUserId() == userId) {
1668                        count++;
1669                        if (count >= MAX_PACKAGE_NOTIFICATIONS) {
1670                            Slog.e(TAG, "Package has already posted " + count
1671                                    + " notifications.  Not showing more.  package=" + pkg);
1672                            return;
1673                        }
1674                    }
1675                }
1676            }
1677        }
1678
1679        // This conditional is a dirty hack to limit the logging done on
1680        //     behalf of the download manager without affecting other apps.
1681        if (!pkg.equals("com.android.providers.downloads")
1682                || Log.isLoggable("DownloadManager", Log.VERBOSE)) {
1683            EventLog.writeEvent(EventLogTags.NOTIFICATION_ENQUEUE, pkg, id, tag, userId,
1684                    notification.toString());
1685        }
1686
1687        if (pkg == null || notification == null) {
1688            throw new IllegalArgumentException("null not allowed: pkg=" + pkg
1689                    + " id=" + id + " notification=" + notification);
1690        }
1691        if (notification.icon != 0) {
1692            if (notification.contentView == null) {
1693                throw new IllegalArgumentException("contentView required: pkg=" + pkg
1694                        + " id=" + id + " notification=" + notification);
1695            }
1696        }
1697
1698        mHandler.post(new Runnable() {
1699            @Override
1700            public void run() {
1701
1702                // === Scoring ===
1703
1704                // 0. Sanitize inputs
1705                notification.priority = clamp(notification.priority, Notification.PRIORITY_MIN,
1706                        Notification.PRIORITY_MAX);
1707                // Migrate notification flags to scores
1708                if (0 != (notification.flags & Notification.FLAG_HIGH_PRIORITY)) {
1709                    if (notification.priority < Notification.PRIORITY_MAX) {
1710                        notification.priority = Notification.PRIORITY_MAX;
1711                    }
1712                } else if (SCORE_ONGOING_HIGHER &&
1713                        0 != (notification.flags & Notification.FLAG_ONGOING_EVENT)) {
1714                    if (notification.priority < Notification.PRIORITY_HIGH) {
1715                        notification.priority = Notification.PRIORITY_HIGH;
1716                    }
1717                }
1718
1719                // 1. initial score: buckets of 10, around the app
1720                int score = notification.priority * NOTIFICATION_PRIORITY_MULTIPLIER; //[-20..20]
1721
1722                // 2. Consult external heuristics (TBD)
1723
1724                // 3. Apply local rules
1725
1726                int initialScore = score;
1727                if (!mScorers.isEmpty()) {
1728                    if (DBG) Slog.v(TAG, "Initial score is " + score + ".");
1729                    for (NotificationScorer scorer : mScorers) {
1730                        try {
1731                            score = scorer.getScore(notification, score);
1732                        } catch (Throwable t) {
1733                            Slog.w(TAG, "Scorer threw on .getScore.", t);
1734                        }
1735                    }
1736                    if (DBG) Slog.v(TAG, "Final score is " + score + ".");
1737                }
1738
1739                // add extra to indicate score modified by NotificationScorer
1740                notification.extras.putBoolean(Notification.EXTRA_SCORE_MODIFIED,
1741                        score != initialScore);
1742
1743                // blocked apps
1744                if (ENABLE_BLOCKED_NOTIFICATIONS && !noteNotificationOp(pkg, callingUid)) {
1745                    if (!isSystemNotification) {
1746                        score = JUNK_SCORE;
1747                        Slog.e(TAG, "Suppressing notification from package " + pkg
1748                                + " by user request.");
1749                    }
1750                }
1751
1752                if (DBG) {
1753                    Slog.v(TAG, "Assigned score=" + score + " to " + notification);
1754                }
1755
1756                if (score < SCORE_DISPLAY_THRESHOLD) {
1757                    // Notification will be blocked because the score is too low.
1758                    return;
1759                }
1760
1761                // Should this notification make noise, vibe, or use the LED?
1762                final boolean canInterrupt = (score >= SCORE_INTERRUPTION_THRESHOLD);
1763
1764                synchronized (mNotificationList) {
1765                    final StatusBarNotification n = new StatusBarNotification(
1766                            pkg, id, tag, callingUid, callingPid, score, notification, user);
1767                    NotificationRecord r = new NotificationRecord(n);
1768                    NotificationRecord old = null;
1769
1770                    int index = indexOfNotificationLocked(pkg, tag, id, userId);
1771                    if (index < 0) {
1772                        mNotificationList.add(r);
1773                    } else {
1774                        old = mNotificationList.remove(index);
1775                        mNotificationList.add(index, r);
1776                        // Make sure we don't lose the foreground service state.
1777                        if (old != null) {
1778                            notification.flags |=
1779                                old.getNotification().flags & Notification.FLAG_FOREGROUND_SERVICE;
1780                        }
1781                    }
1782
1783                    // Ensure if this is a foreground service that the proper additional
1784                    // flags are set.
1785                    if ((notification.flags&Notification.FLAG_FOREGROUND_SERVICE) != 0) {
1786                        notification.flags |= Notification.FLAG_ONGOING_EVENT
1787                                | Notification.FLAG_NO_CLEAR;
1788                    }
1789
1790                    final int currentUser;
1791                    final long token = Binder.clearCallingIdentity();
1792                    try {
1793                        currentUser = ActivityManager.getCurrentUser();
1794                    } finally {
1795                        Binder.restoreCallingIdentity(token);
1796                    }
1797
1798                    if (notification.icon != 0) {
1799                        if (old != null && old.statusBarKey != null) {
1800                            r.statusBarKey = old.statusBarKey;
1801                            final long identity = Binder.clearCallingIdentity();
1802                            try {
1803                                mStatusBar.updateNotification(r.statusBarKey, n);
1804                            } finally {
1805                                Binder.restoreCallingIdentity(identity);
1806                            }
1807                        } else {
1808                            final long identity = Binder.clearCallingIdentity();
1809                            try {
1810                                r.statusBarKey = mStatusBar.addNotification(n);
1811                                if ((n.getNotification().flags & Notification.FLAG_SHOW_LIGHTS) != 0
1812                                        && canInterrupt) {
1813                                    mAttentionLight.pulse();
1814                                }
1815                            } finally {
1816                                Binder.restoreCallingIdentity(identity);
1817                            }
1818                        }
1819                        // Send accessibility events only for the current user.
1820                        if (currentUser == userId) {
1821                            sendAccessibilityEvent(notification, pkg);
1822                        }
1823
1824                        notifyPostedLocked(r);
1825                    } else {
1826                        Slog.e(TAG, "Not posting notification with icon==0: " + notification);
1827                        if (old != null && old.statusBarKey != null) {
1828                            final long identity = Binder.clearCallingIdentity();
1829                            try {
1830                                mStatusBar.removeNotification(old.statusBarKey);
1831                            } finally {
1832                                Binder.restoreCallingIdentity(identity);
1833                            }
1834
1835                            notifyRemovedLocked(r);
1836                        }
1837                        // ATTENTION: in a future release we will bail out here
1838                        // so that we do not play sounds, show lights, etc. for invalid
1839                        // notifications
1840                        Slog.e(TAG, "WARNING: In a future release this will crash the app: "
1841                                + n.getPackageName());
1842                    }
1843
1844                    // If we're not supposed to beep, vibrate, etc. then don't.
1845                    if (((mDisabledNotifications
1846                            & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) == 0)
1847                            && (!(old != null
1848                                && (notification.flags & Notification.FLAG_ONLY_ALERT_ONCE) != 0 ))
1849                            && (r.getUserId() == UserHandle.USER_ALL ||
1850                                (r.getUserId() == userId && r.getUserId() == currentUser))
1851                            && canInterrupt
1852                            && mSystemReady
1853                            && mAudioManager != null) {
1854
1855                        // sound
1856
1857                        // should we use the default notification sound? (indicated either by
1858                        // DEFAULT_SOUND or because notification.sound is pointing at
1859                        // Settings.System.NOTIFICATION_SOUND)
1860                        final boolean useDefaultSound =
1861                               (notification.defaults & Notification.DEFAULT_SOUND) != 0 ||
1862                                       Settings.System.DEFAULT_NOTIFICATION_URI
1863                                               .equals(notification.sound);
1864
1865                        Uri soundUri = null;
1866                        boolean hasValidSound = false;
1867
1868                        if (useDefaultSound) {
1869                            soundUri = Settings.System.DEFAULT_NOTIFICATION_URI;
1870
1871                            // check to see if the default notification sound is silent
1872                            ContentResolver resolver = getContext().getContentResolver();
1873                            hasValidSound = Settings.System.getString(resolver,
1874                                   Settings.System.NOTIFICATION_SOUND) != null;
1875                        } else if (notification.sound != null) {
1876                            soundUri = notification.sound;
1877                            hasValidSound = (soundUri != null);
1878                        }
1879
1880                        if (hasValidSound) {
1881                            boolean looping =
1882                                    (notification.flags & Notification.FLAG_INSISTENT) != 0;
1883                            int audioStreamType;
1884                            if (notification.audioStreamType >= 0) {
1885                                audioStreamType = notification.audioStreamType;
1886                            } else {
1887                                audioStreamType = DEFAULT_STREAM_TYPE;
1888                            }
1889                            mSoundNotification = r;
1890                            // do not play notifications if stream volume is 0 (typically because
1891                            // ringer mode is silent) or if there is a user of exclusive audio focus
1892                            if ((mAudioManager.getStreamVolume(audioStreamType) != 0)
1893                                    && !mAudioManager.isAudioFocusExclusive()) {
1894                                final long identity = Binder.clearCallingIdentity();
1895                                try {
1896                                    final IRingtonePlayer player =
1897                                            mAudioManager.getRingtonePlayer();
1898                                    if (player != null) {
1899                                        player.playAsync(soundUri, user, looping, audioStreamType);
1900                                    }
1901                                } catch (RemoteException e) {
1902                                } finally {
1903                                    Binder.restoreCallingIdentity(identity);
1904                                }
1905                            }
1906                        }
1907
1908                        // vibrate
1909                        // Does the notification want to specify its own vibration?
1910                        final boolean hasCustomVibrate = notification.vibrate != null;
1911
1912                        // new in 4.2: if there was supposed to be a sound and we're in vibrate
1913                        // mode, and no other vibration is specified, we fall back to vibration
1914                        final boolean convertSoundToVibration =
1915                                   !hasCustomVibrate
1916                                && hasValidSound
1917                                && (mAudioManager.getRingerMode()
1918                                           == AudioManager.RINGER_MODE_VIBRATE);
1919
1920                        // The DEFAULT_VIBRATE flag trumps any custom vibration AND the fallback.
1921                        final boolean useDefaultVibrate =
1922                                (notification.defaults & Notification.DEFAULT_VIBRATE) != 0;
1923
1924                        if ((useDefaultVibrate || convertSoundToVibration || hasCustomVibrate)
1925                                && !(mAudioManager.getRingerMode()
1926                                        == AudioManager.RINGER_MODE_SILENT)) {
1927                            mVibrateNotification = r;
1928
1929                            if (useDefaultVibrate || convertSoundToVibration) {
1930                                // Escalate privileges so we can use the vibrator even if the
1931                                // notifying app does not have the VIBRATE permission.
1932                                long identity = Binder.clearCallingIdentity();
1933                                try {
1934                                    mVibrator.vibrate(r.sbn.getUid(), r.sbn.getBasePkg(),
1935                                        useDefaultVibrate ? mDefaultVibrationPattern
1936                                            : mFallbackVibrationPattern,
1937                                        ((notification.flags & Notification.FLAG_INSISTENT) != 0)
1938                                                ? 0: -1);
1939                                } finally {
1940                                    Binder.restoreCallingIdentity(identity);
1941                                }
1942                            } else if (notification.vibrate.length > 1) {
1943                                // If you want your own vibration pattern, you need the VIBRATE
1944                                // permission
1945                                mVibrator.vibrate(r.sbn.getUid(), r.sbn.getBasePkg(),
1946                                        notification.vibrate,
1947                                    ((notification.flags & Notification.FLAG_INSISTENT) != 0)
1948                                            ? 0: -1);
1949                            }
1950                        }
1951                    }
1952
1953                    // light
1954                    // the most recent thing gets the light
1955                    mLights.remove(old);
1956                    if (mLedNotification == old) {
1957                        mLedNotification = null;
1958                    }
1959                    //Slog.i(TAG, "notification.lights="
1960                    //        + ((old.notification.lights.flags & Notification.FLAG_SHOW_LIGHTS)
1961                    //                  != 0));
1962                    if ((notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0
1963                            && canInterrupt) {
1964                        mLights.add(r);
1965                        updateLightsLocked();
1966                    } else {
1967                        if (old != null
1968                                && ((old.getFlags() & Notification.FLAG_SHOW_LIGHTS) != 0)) {
1969                            updateLightsLocked();
1970                        }
1971                    }
1972                }
1973            }
1974        });
1975
1976        idOut[0] = id;
1977    }
1978
1979     void registerListenerImpl(final INotificationListener listener,
1980            final ComponentName component, final int userid) {
1981        synchronized (mNotificationList) {
1982            try {
1983                NotificationListenerInfo info
1984                        = new NotificationListenerInfo(listener, component, userid, true);
1985                listener.asBinder().linkToDeath(info, 0);
1986                mListeners.add(info);
1987            } catch (RemoteException e) {
1988                // already dead
1989            }
1990        }
1991    }
1992
1993    void unregisterListenerImpl(final INotificationListener listener, final int userid) {
1994        synchronized (mNotificationList) {
1995            final int N = mListeners.size();
1996            for (int i=N-1; i>=0; i--) {
1997                final NotificationListenerInfo info = mListeners.get(i);
1998                if (info.listener.asBinder() == listener.asBinder()
1999                        && info.userid == userid) {
2000                    mListeners.remove(i);
2001                    if (info.connection != null) {
2002                        getContext().unbindService(info.connection);
2003                    }
2004                }
2005            }
2006        }
2007    }
2008
2009    void showNextToastLocked() {
2010        ToastRecord record = mToastQueue.get(0);
2011        while (record != null) {
2012            if (DBG) Slog.d(TAG, "Show pkg=" + record.pkg + " callback=" + record.callback);
2013            try {
2014                record.callback.show();
2015                scheduleTimeoutLocked(record);
2016                return;
2017            } catch (RemoteException e) {
2018                Slog.w(TAG, "Object died trying to show notification " + record.callback
2019                        + " in package " + record.pkg);
2020                // remove it from the list and let the process die
2021                int index = mToastQueue.indexOf(record);
2022                if (index >= 0) {
2023                    mToastQueue.remove(index);
2024                }
2025                keepProcessAliveLocked(record.pid);
2026                if (mToastQueue.size() > 0) {
2027                    record = mToastQueue.get(0);
2028                } else {
2029                    record = null;
2030                }
2031            }
2032        }
2033    }
2034
2035    void cancelToastLocked(int index) {
2036        ToastRecord record = mToastQueue.get(index);
2037        try {
2038            record.callback.hide();
2039        } catch (RemoteException e) {
2040            Slog.w(TAG, "Object died trying to hide notification " + record.callback
2041                    + " in package " + record.pkg);
2042            // don't worry about this, we're about to remove it from
2043            // the list anyway
2044        }
2045        mToastQueue.remove(index);
2046        keepProcessAliveLocked(record.pid);
2047        if (mToastQueue.size() > 0) {
2048            // Show the next one. If the callback fails, this will remove
2049            // it from the list, so don't assume that the list hasn't changed
2050            // after this point.
2051            showNextToastLocked();
2052        }
2053    }
2054
2055    private void scheduleTimeoutLocked(ToastRecord r)
2056    {
2057        mHandler.removeCallbacksAndMessages(r);
2058        Message m = Message.obtain(mHandler, MESSAGE_TIMEOUT, r);
2059        long delay = r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY;
2060        mHandler.sendMessageDelayed(m, delay);
2061    }
2062
2063    private void handleTimeout(ToastRecord record)
2064    {
2065        if (DBG) Slog.d(TAG, "Timeout pkg=" + record.pkg + " callback=" + record.callback);
2066        synchronized (mToastQueue) {
2067            int index = indexOfToastLocked(record.pkg, record.callback);
2068            if (index >= 0) {
2069                cancelToastLocked(index);
2070            }
2071        }
2072    }
2073
2074    // lock on mToastQueue
2075    int indexOfToastLocked(String pkg, ITransientNotification callback)
2076    {
2077        IBinder cbak = callback.asBinder();
2078        ArrayList<ToastRecord> list = mToastQueue;
2079        int len = list.size();
2080        for (int i=0; i<len; i++) {
2081            ToastRecord r = list.get(i);
2082            if (r.pkg.equals(pkg) && r.callback.asBinder() == cbak) {
2083                return i;
2084            }
2085        }
2086        return -1;
2087    }
2088
2089    // lock on mToastQueue
2090    void keepProcessAliveLocked(int pid)
2091    {
2092        int toastCount = 0; // toasts from this pid
2093        ArrayList<ToastRecord> list = mToastQueue;
2094        int N = list.size();
2095        for (int i=0; i<N; i++) {
2096            ToastRecord r = list.get(i);
2097            if (r.pid == pid) {
2098                toastCount++;
2099            }
2100        }
2101        try {
2102            mAm.setProcessForeground(mForegroundToken, pid, toastCount > 0);
2103        } catch (RemoteException e) {
2104            // Shouldn't happen.
2105        }
2106    }
2107
2108    private final class WorkerHandler extends Handler
2109    {
2110        @Override
2111        public void handleMessage(Message msg)
2112        {
2113            switch (msg.what)
2114            {
2115                case MESSAGE_TIMEOUT:
2116                    handleTimeout((ToastRecord)msg.obj);
2117                    break;
2118            }
2119        }
2120    }
2121
2122
2123    // Notifications
2124    // ============================================================================
2125    static int clamp(int x, int low, int high) {
2126        return (x < low) ? low : ((x > high) ? high : x);
2127    }
2128
2129    void sendAccessibilityEvent(Notification notification, CharSequence packageName) {
2130        AccessibilityManager manager = AccessibilityManager.getInstance(getContext());
2131        if (!manager.isEnabled()) {
2132            return;
2133        }
2134
2135        AccessibilityEvent event =
2136            AccessibilityEvent.obtain(AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED);
2137        event.setPackageName(packageName);
2138        event.setClassName(Notification.class.getName());
2139        event.setParcelableData(notification);
2140        CharSequence tickerText = notification.tickerText;
2141        if (!TextUtils.isEmpty(tickerText)) {
2142            event.getText().add(tickerText);
2143        }
2144
2145        manager.sendAccessibilityEvent(event);
2146    }
2147
2148    private void cancelNotificationLocked(NotificationRecord r, boolean sendDelete) {
2149        // tell the app
2150        if (sendDelete) {
2151            if (r.getNotification().deleteIntent != null) {
2152                try {
2153                    r.getNotification().deleteIntent.send();
2154                } catch (PendingIntent.CanceledException ex) {
2155                    // do nothing - there's no relevant way to recover, and
2156                    //     no reason to let this propagate
2157                    Slog.w(TAG, "canceled PendingIntent for " + r.sbn.getPackageName(), ex);
2158                }
2159            }
2160        }
2161
2162        // status bar
2163        if (r.getNotification().icon != 0) {
2164            final long identity = Binder.clearCallingIdentity();
2165            try {
2166                mStatusBar.removeNotification(r.statusBarKey);
2167            } finally {
2168                Binder.restoreCallingIdentity(identity);
2169            }
2170            r.statusBarKey = null;
2171            notifyRemovedLocked(r);
2172        }
2173
2174        // sound
2175        if (mSoundNotification == r) {
2176            mSoundNotification = null;
2177            final long identity = Binder.clearCallingIdentity();
2178            try {
2179                final IRingtonePlayer player = mAudioManager.getRingtonePlayer();
2180                if (player != null) {
2181                    player.stopAsync();
2182                }
2183            } catch (RemoteException e) {
2184            } finally {
2185                Binder.restoreCallingIdentity(identity);
2186            }
2187        }
2188
2189        // vibrate
2190        if (mVibrateNotification == r) {
2191            mVibrateNotification = null;
2192            long identity = Binder.clearCallingIdentity();
2193            try {
2194                mVibrator.cancel();
2195            }
2196            finally {
2197                Binder.restoreCallingIdentity(identity);
2198            }
2199        }
2200
2201        // light
2202        mLights.remove(r);
2203        if (mLedNotification == r) {
2204            mLedNotification = null;
2205        }
2206
2207        // Save it for users of getHistoricalNotifications()
2208        mArchive.record(r.sbn);
2209    }
2210
2211    /**
2212     * Cancels a notification ONLY if it has all of the {@code mustHaveFlags}
2213     * and none of the {@code mustNotHaveFlags}.
2214     */
2215    void cancelNotification(final String pkg, final String tag, final int id,
2216            final int mustHaveFlags, final int mustNotHaveFlags, final boolean sendDelete,
2217            final int userId) {
2218        // In enqueueNotificationInternal notifications are added by scheduling the
2219        // work on the worker handler. Hence, we also schedule the cancel on this
2220        // handler to avoid a scenario where an add notification call followed by a
2221        // remove notification call ends up in not removing the notification.
2222        mHandler.post(new Runnable() {
2223            @Override
2224            public void run() {
2225                EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL, pkg, id, tag, userId,
2226                        mustHaveFlags, mustNotHaveFlags);
2227
2228                synchronized (mNotificationList) {
2229                    int index = indexOfNotificationLocked(pkg, tag, id, userId);
2230                    if (index >= 0) {
2231                        NotificationRecord r = mNotificationList.get(index);
2232
2233                        if ((r.getNotification().flags & mustHaveFlags) != mustHaveFlags) {
2234                            return;
2235                        }
2236                        if ((r.getNotification().flags & mustNotHaveFlags) != 0) {
2237                            return;
2238                        }
2239
2240                        mNotificationList.remove(index);
2241
2242                        cancelNotificationLocked(r, sendDelete);
2243                        updateLightsLocked();
2244                    }
2245                }
2246            }
2247        });
2248    }
2249
2250    /**
2251     * Determine whether the userId applies to the notification in question, either because
2252     * they match exactly, or one of them is USER_ALL (which is treated as a wildcard).
2253     */
2254    private boolean notificationMatchesUserId(NotificationRecord r, int userId) {
2255        return
2256                // looking for USER_ALL notifications? match everything
2257                   userId == UserHandle.USER_ALL
2258                // a notification sent to USER_ALL matches any query
2259                || r.getUserId() == UserHandle.USER_ALL
2260                // an exact user match
2261                || r.getUserId() == userId;
2262    }
2263
2264    /**
2265     * Cancels all notifications from a given package that have all of the
2266     * {@code mustHaveFlags}.
2267     */
2268    boolean cancelAllNotificationsInt(String pkg, int mustHaveFlags,
2269            int mustNotHaveFlags, boolean doit, int userId) {
2270        EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL_ALL, pkg, userId,
2271                mustHaveFlags, mustNotHaveFlags);
2272
2273        synchronized (mNotificationList) {
2274            final int N = mNotificationList.size();
2275            boolean canceledSomething = false;
2276            for (int i = N-1; i >= 0; --i) {
2277                NotificationRecord r = mNotificationList.get(i);
2278                if (!notificationMatchesUserId(r, userId)) {
2279                    continue;
2280                }
2281                // Don't remove notifications to all, if there's no package name specified
2282                if (r.getUserId() == UserHandle.USER_ALL && pkg == null) {
2283                    continue;
2284                }
2285                if ((r.getFlags() & mustHaveFlags) != mustHaveFlags) {
2286                    continue;
2287                }
2288                if ((r.getFlags() & mustNotHaveFlags) != 0) {
2289                    continue;
2290                }
2291                if (pkg != null && !r.sbn.getPackageName().equals(pkg)) {
2292                    continue;
2293                }
2294                canceledSomething = true;
2295                if (!doit) {
2296                    return true;
2297                }
2298                mNotificationList.remove(i);
2299                cancelNotificationLocked(r, false);
2300            }
2301            if (canceledSomething) {
2302                updateLightsLocked();
2303            }
2304            return canceledSomething;
2305        }
2306    }
2307
2308
2309
2310    // Return true if the UID is a system or phone UID and therefore should not have
2311    // any notifications or toasts blocked.
2312    boolean isUidSystem(int uid) {
2313        final int appid = UserHandle.getAppId(uid);
2314        return (appid == Process.SYSTEM_UID || appid == Process.PHONE_UID || uid == 0);
2315    }
2316
2317    // same as isUidSystem(int, int) for the Binder caller's UID.
2318    boolean isCallerSystem() {
2319        return isUidSystem(Binder.getCallingUid());
2320    }
2321
2322    void checkCallerIsSystem() {
2323        if (isCallerSystem()) {
2324            return;
2325        }
2326        throw new SecurityException("Disallowed call for uid " + Binder.getCallingUid());
2327    }
2328
2329    void checkCallerIsSystemOrSameApp(String pkg) {
2330        if (isCallerSystem()) {
2331            return;
2332        }
2333        final int uid = Binder.getCallingUid();
2334        try {
2335            ApplicationInfo ai = AppGlobals.getPackageManager().getApplicationInfo(
2336                    pkg, 0, UserHandle.getCallingUserId());
2337            if (!UserHandle.isSameApp(ai.uid, uid)) {
2338                throw new SecurityException("Calling uid " + uid + " gave package"
2339                        + pkg + " which is owned by uid " + ai.uid);
2340            }
2341        } catch (RemoteException re) {
2342            throw new SecurityException("Unknown package " + pkg + "\n" + re);
2343        }
2344    }
2345
2346    void cancelAll(int userId) {
2347        synchronized (mNotificationList) {
2348            final int N = mNotificationList.size();
2349            for (int i=N-1; i>=0; i--) {
2350                NotificationRecord r = mNotificationList.get(i);
2351
2352                if (!notificationMatchesUserId(r, userId)) {
2353                    continue;
2354                }
2355
2356                if ((r.getFlags() & (Notification.FLAG_ONGOING_EVENT
2357                                | Notification.FLAG_NO_CLEAR)) == 0) {
2358                    mNotificationList.remove(i);
2359                    cancelNotificationLocked(r, true);
2360                }
2361            }
2362
2363            updateLightsLocked();
2364        }
2365    }
2366
2367    // lock on mNotificationList
2368    void updateLightsLocked()
2369    {
2370        // handle notification lights
2371        if (mLedNotification == null) {
2372            // get next notification, if any
2373            int n = mLights.size();
2374            if (n > 0) {
2375                mLedNotification = mLights.get(n-1);
2376            }
2377        }
2378
2379        // Don't flash while we are in a call or screen is on
2380        if (mLedNotification == null || mInCall || mScreenOn) {
2381            mNotificationLight.turnOff();
2382        } else {
2383            final Notification ledno = mLedNotification.sbn.getNotification();
2384            int ledARGB = ledno.ledARGB;
2385            int ledOnMS = ledno.ledOnMS;
2386            int ledOffMS = ledno.ledOffMS;
2387            if ((ledno.defaults & Notification.DEFAULT_LIGHTS) != 0) {
2388                ledARGB = mDefaultNotificationColor;
2389                ledOnMS = mDefaultNotificationLedOn;
2390                ledOffMS = mDefaultNotificationLedOff;
2391            }
2392            if (mNotificationPulseEnabled) {
2393                // pulse repeatedly
2394                mNotificationLight.setFlashing(ledARGB, Light.LIGHT_FLASH_TIMED,
2395                        ledOnMS, ledOffMS);
2396            }
2397        }
2398    }
2399
2400    // lock on mNotificationList
2401    int indexOfNotificationLocked(String pkg, String tag, int id, int userId)
2402    {
2403        ArrayList<NotificationRecord> list = mNotificationList;
2404        final int len = list.size();
2405        for (int i=0; i<len; i++) {
2406            NotificationRecord r = list.get(i);
2407            if (!notificationMatchesUserId(r, userId) || r.sbn.getId() != id) {
2408                continue;
2409            }
2410            if (tag == null) {
2411                if (r.sbn.getTag() != null) {
2412                    continue;
2413                }
2414            } else {
2415                if (!tag.equals(r.sbn.getTag())) {
2416                    continue;
2417                }
2418            }
2419            if (r.sbn.getPackageName().equals(pkg)) {
2420                return i;
2421            }
2422        }
2423        return -1;
2424    }
2425
2426    private void updateNotificationPulse() {
2427        synchronized (mNotificationList) {
2428            updateLightsLocked();
2429        }
2430    }
2431}
2432