NotificationManagerService.java revision 9158825f9c41869689d6b1786d7c7aa8bdd524ce
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    @Override
1122    public void onStart() {
1123        mAm = ActivityManagerNative.getDefault();
1124        mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
1125        mVibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE);
1126
1127        mHandler = new WorkerHandler();
1128
1129        importOldBlockDb();
1130
1131        mStatusBar = getLocalService(StatusBarManagerInternal.class);
1132        mStatusBar.setNotificationDelegate(mNotificationDelegate);
1133
1134        final LightsManager lights = getLocalService(LightsManager.class);
1135        mNotificationLight = lights.getLight(LightsManager.LIGHT_ID_NOTIFICATIONS);
1136        mAttentionLight = lights.getLight(LightsManager.LIGHT_ID_ATTENTION);
1137
1138        Resources resources = getContext().getResources();
1139        mDefaultNotificationColor = resources.getColor(
1140                R.color.config_defaultNotificationColor);
1141        mDefaultNotificationLedOn = resources.getInteger(
1142                R.integer.config_defaultNotificationLedOn);
1143        mDefaultNotificationLedOff = resources.getInteger(
1144                R.integer.config_defaultNotificationLedOff);
1145
1146        mDefaultVibrationPattern = getLongArray(resources,
1147                R.array.config_defaultNotificationVibePattern,
1148                VIBRATE_PATTERN_MAXLEN,
1149                DEFAULT_VIBRATE_PATTERN);
1150
1151        mFallbackVibrationPattern = getLongArray(resources,
1152                R.array.config_notificationFallbackVibePattern,
1153                VIBRATE_PATTERN_MAXLEN,
1154                DEFAULT_VIBRATE_PATTERN);
1155
1156        // Don't start allowing notifications until the setup wizard has run once.
1157        // After that, including subsequent boots, init with notifications turned on.
1158        // This works on the first boot because the setup wizard will toggle this
1159        // flag at least once and we'll go back to 0 after that.
1160        if (0 == Settings.Global.getInt(getContext().getContentResolver(),
1161                    Settings.Global.DEVICE_PROVISIONED, 0)) {
1162            mDisabledNotifications = StatusBarManager.DISABLE_NOTIFICATION_ALERTS;
1163        }
1164
1165        // register for various Intents
1166        IntentFilter filter = new IntentFilter();
1167        filter.addAction(Intent.ACTION_SCREEN_ON);
1168        filter.addAction(Intent.ACTION_SCREEN_OFF);
1169        filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
1170        filter.addAction(Intent.ACTION_USER_PRESENT);
1171        filter.addAction(Intent.ACTION_USER_STOPPED);
1172        filter.addAction(Intent.ACTION_USER_SWITCHED);
1173        getContext().registerReceiver(mIntentReceiver, filter);
1174        IntentFilter pkgFilter = new IntentFilter();
1175        pkgFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
1176        pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
1177        pkgFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
1178        pkgFilter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
1179        pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
1180        pkgFilter.addDataScheme("package");
1181        getContext().registerReceiver(mIntentReceiver, pkgFilter);
1182        IntentFilter sdFilter = new IntentFilter(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
1183        getContext().registerReceiver(mIntentReceiver, sdFilter);
1184
1185        mSettingsObserver = new SettingsObserver(mHandler);
1186        mSettingsObserver.observe();
1187
1188        // spin up NotificationScorers
1189        String[] notificationScorerNames = resources.getStringArray(
1190                R.array.config_notificationScorers);
1191        for (String scorerName : notificationScorerNames) {
1192            try {
1193                Class<?> scorerClass = getContext().getClassLoader().loadClass(scorerName);
1194                NotificationScorer scorer = (NotificationScorer) scorerClass.newInstance();
1195                scorer.initialize(getContext());
1196                mScorers.add(scorer);
1197            } catch (ClassNotFoundException e) {
1198                Slog.w(TAG, "Couldn't find scorer " + scorerName + ".", e);
1199            } catch (InstantiationException e) {
1200                Slog.w(TAG, "Couldn't instantiate scorer " + scorerName + ".", e);
1201            } catch (IllegalAccessException e) {
1202                Slog.w(TAG, "Problem accessing scorer " + scorerName + ".", e);
1203            }
1204        }
1205
1206        publishBinderService(Context.NOTIFICATION_SERVICE, mService);
1207        publishLocalService(NotificationManagerInternal.class, mInternalService);
1208    }
1209
1210    /**
1211     * Read the old XML-based app block database and import those blockages into the AppOps system.
1212     */
1213    private void importOldBlockDb() {
1214        loadBlockDb();
1215
1216        PackageManager pm = getContext().getPackageManager();
1217        for (String pkg : mBlockedPackages) {
1218            PackageInfo info = null;
1219            try {
1220                info = pm.getPackageInfo(pkg, 0);
1221                setNotificationsEnabledForPackageImpl(pkg, info.applicationInfo.uid, false);
1222            } catch (NameNotFoundException e) {
1223                // forget you
1224            }
1225        }
1226        mBlockedPackages.clear();
1227        if (mPolicyFile != null) {
1228            mPolicyFile.delete();
1229        }
1230    }
1231
1232    @Override
1233    public void onBootPhase(int phase) {
1234        if (phase == SystemService.PHASE_SYSTEM_SERVICES_READY) {
1235            // no beeping until we're basically done booting
1236            mSystemReady = true;
1237
1238            // Grab our optional AudioService
1239            mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
1240
1241            // make sure our listener services are properly bound
1242            rebindListenerServices();
1243        }
1244    }
1245
1246    void setNotificationsEnabledForPackageImpl(String pkg, int uid, boolean enabled) {
1247        Slog.v(TAG, (enabled?"en":"dis") + "abling notifications for " + pkg);
1248
1249        mAppOps.setMode(AppOpsManager.OP_POST_NOTIFICATION, uid, pkg,
1250                enabled ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
1251
1252        // Now, cancel any outstanding notifications that are part of a just-disabled app
1253        if (ENABLE_BLOCKED_NOTIFICATIONS && !enabled) {
1254            cancelAllNotificationsInt(pkg, 0, 0, true, UserHandle.getUserId(uid));
1255        }
1256    }
1257
1258    private final IBinder mService = new INotificationManager.Stub() {
1259        // Toasts
1260        // ============================================================================
1261
1262        @Override
1263        public void enqueueToast(String pkg, ITransientNotification callback, int duration)
1264        {
1265            if (DBG) {
1266                Slog.i(TAG, "enqueueToast pkg=" + pkg + " callback=" + callback
1267                        + " duration=" + duration);
1268            }
1269
1270            if (pkg == null || callback == null) {
1271                Slog.e(TAG, "Not doing toast. pkg=" + pkg + " callback=" + callback);
1272                return ;
1273            }
1274
1275            final boolean isSystemToast = isCallerSystem() || ("android".equals(pkg));
1276
1277            if (ENABLE_BLOCKED_TOASTS && !noteNotificationOp(pkg, Binder.getCallingUid())) {
1278                if (!isSystemToast) {
1279                    Slog.e(TAG, "Suppressing toast from package " + pkg + " by user request.");
1280                    return;
1281                }
1282            }
1283
1284            synchronized (mToastQueue) {
1285                int callingPid = Binder.getCallingPid();
1286                long callingId = Binder.clearCallingIdentity();
1287                try {
1288                    ToastRecord record;
1289                    int index = indexOfToastLocked(pkg, callback);
1290                    // If it's already in the queue, we update it in place, we don't
1291                    // move it to the end of the queue.
1292                    if (index >= 0) {
1293                        record = mToastQueue.get(index);
1294                        record.update(duration);
1295                    } else {
1296                        // Limit the number of toasts that any given package except the android
1297                        // package can enqueue.  Prevents DOS attacks and deals with leaks.
1298                        if (!isSystemToast) {
1299                            int count = 0;
1300                            final int N = mToastQueue.size();
1301                            for (int i=0; i<N; i++) {
1302                                 final ToastRecord r = mToastQueue.get(i);
1303                                 if (r.pkg.equals(pkg)) {
1304                                     count++;
1305                                     if (count >= MAX_PACKAGE_NOTIFICATIONS) {
1306                                         Slog.e(TAG, "Package has already posted " + count
1307                                                + " toasts. Not showing more. Package=" + pkg);
1308                                         return;
1309                                     }
1310                                 }
1311                            }
1312                        }
1313
1314                        record = new ToastRecord(callingPid, pkg, callback, duration);
1315                        mToastQueue.add(record);
1316                        index = mToastQueue.size() - 1;
1317                        keepProcessAliveLocked(callingPid);
1318                    }
1319                    // If it's at index 0, it's the current toast.  It doesn't matter if it's
1320                    // new or just been updated.  Call back and tell it to show itself.
1321                    // If the callback fails, this will remove it from the list, so don't
1322                    // assume that it's valid after this.
1323                    if (index == 0) {
1324                        showNextToastLocked();
1325                    }
1326                } finally {
1327                    Binder.restoreCallingIdentity(callingId);
1328                }
1329            }
1330        }
1331
1332        @Override
1333        public void cancelToast(String pkg, ITransientNotification callback) {
1334            Slog.i(TAG, "cancelToast pkg=" + pkg + " callback=" + callback);
1335
1336            if (pkg == null || callback == null) {
1337                Slog.e(TAG, "Not cancelling notification. pkg=" + pkg + " callback=" + callback);
1338                return ;
1339            }
1340
1341            synchronized (mToastQueue) {
1342                long callingId = Binder.clearCallingIdentity();
1343                try {
1344                    int index = indexOfToastLocked(pkg, callback);
1345                    if (index >= 0) {
1346                        cancelToastLocked(index);
1347                    } else {
1348                        Slog.w(TAG, "Toast already cancelled. pkg=" + pkg
1349                                + " callback=" + callback);
1350                    }
1351                } finally {
1352                    Binder.restoreCallingIdentity(callingId);
1353                }
1354            }
1355        }
1356
1357        @Override
1358        public void enqueueNotificationWithTag(String pkg, String basePkg, String tag, int id,
1359                Notification notification, int[] idOut, int userId) throws RemoteException {
1360            enqueueNotificationInternal(pkg, basePkg, Binder.getCallingUid(),
1361                    Binder.getCallingPid(), tag, id, notification, idOut, userId);
1362        }
1363
1364        @Override
1365        public void cancelNotificationWithTag(String pkg, String tag, int id, int userId) {
1366            checkCallerIsSystemOrSameApp(pkg);
1367            userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1368                    Binder.getCallingUid(), userId, true, false, "cancelNotificationWithTag", pkg);
1369            // Don't allow client applications to cancel foreground service notis.
1370            cancelNotification(pkg, tag, id, 0,
1371                    Binder.getCallingUid() == Process.SYSTEM_UID
1372                    ? 0 : Notification.FLAG_FOREGROUND_SERVICE, false, userId);
1373        }
1374
1375        @Override
1376        public void cancelAllNotifications(String pkg, int userId) {
1377            checkCallerIsSystemOrSameApp(pkg);
1378
1379            userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1380                    Binder.getCallingUid(), userId, true, false, "cancelAllNotifications", pkg);
1381
1382            // Calling from user space, don't allow the canceling of actively
1383            // running foreground services.
1384            cancelAllNotificationsInt(pkg, 0, Notification.FLAG_FOREGROUND_SERVICE, true, userId);
1385        }
1386
1387        @Override
1388        public void setNotificationsEnabledForPackage(String pkg, int uid, boolean enabled) {
1389            checkCallerIsSystem();
1390
1391            setNotificationsEnabledForPackageImpl(pkg, uid, enabled);
1392        }
1393
1394        /**
1395         * Use this when you just want to know if notifications are OK for this package.
1396         */
1397        @Override
1398        public boolean areNotificationsEnabledForPackage(String pkg, int uid) {
1399            checkCallerIsSystem();
1400            return (mAppOps.checkOpNoThrow(AppOpsManager.OP_POST_NOTIFICATION, uid, pkg)
1401                    == AppOpsManager.MODE_ALLOWED);
1402        }
1403
1404        /**
1405         * System-only API for getting a list of current (i.e. not cleared) notifications.
1406         *
1407         * Requires ACCESS_NOTIFICATIONS which is signature|system.
1408         */
1409        @Override
1410        public StatusBarNotification[] getActiveNotifications(String callingPkg) {
1411            // enforce() will ensure the calling uid has the correct permission
1412            getContext().enforceCallingOrSelfPermission(
1413                    android.Manifest.permission.ACCESS_NOTIFICATIONS,
1414                    "NotificationManagerService.getActiveNotifications");
1415
1416            StatusBarNotification[] tmp = null;
1417            int uid = Binder.getCallingUid();
1418
1419            // noteOp will check to make sure the callingPkg matches the uid
1420            if (mAppOps.noteOpNoThrow(AppOpsManager.OP_ACCESS_NOTIFICATIONS, uid, callingPkg)
1421                    == AppOpsManager.MODE_ALLOWED) {
1422                synchronized (mNotificationList) {
1423                    tmp = new StatusBarNotification[mNotificationList.size()];
1424                    final int N = mNotificationList.size();
1425                    for (int i=0; i<N; i++) {
1426                        tmp[i] = mNotificationList.get(i).sbn;
1427                    }
1428                }
1429            }
1430            return tmp;
1431        }
1432
1433        /**
1434         * System-only API for getting a list of recent (cleared, no longer shown) notifications.
1435         *
1436         * Requires ACCESS_NOTIFICATIONS which is signature|system.
1437         */
1438        @Override
1439        public StatusBarNotification[] getHistoricalNotifications(String callingPkg, int count) {
1440            // enforce() will ensure the calling uid has the correct permission
1441            getContext().enforceCallingOrSelfPermission(
1442                    android.Manifest.permission.ACCESS_NOTIFICATIONS,
1443                    "NotificationManagerService.getHistoricalNotifications");
1444
1445            StatusBarNotification[] tmp = null;
1446            int uid = Binder.getCallingUid();
1447
1448            // noteOp will check to make sure the callingPkg matches the uid
1449            if (mAppOps.noteOpNoThrow(AppOpsManager.OP_ACCESS_NOTIFICATIONS, uid, callingPkg)
1450                    == AppOpsManager.MODE_ALLOWED) {
1451                synchronized (mArchive) {
1452                    tmp = mArchive.getArray(count);
1453                }
1454            }
1455            return tmp;
1456        }
1457
1458        /**
1459         * Register a listener binder directly with the notification manager.
1460         *
1461         * Only works with system callers. Apps should extend
1462         * {@link android.service.notification.NotificationListenerService}.
1463         */
1464        @Override
1465        public void registerListener(final INotificationListener listener,
1466                final ComponentName component, final int userid) {
1467            checkCallerIsSystem();
1468            registerListenerImpl(listener, component, userid);
1469        }
1470
1471        /**
1472         * Remove a listener binder directly
1473         */
1474        @Override
1475        public void unregisterListener(INotificationListener listener, int userid) {
1476            // no need to check permissions; if your listener binder is in the list,
1477            // that's proof that you had permission to add it in the first place
1478            unregisterListenerImpl(listener, userid);
1479        }
1480
1481        /**
1482         * Allow an INotificationListener to simulate a "clear all" operation.
1483         *
1484         * {@see com.android.server.StatusBarManagerService.NotificationCallbacks#onClearAllNotifications}
1485         *
1486         * @param token The binder for the listener, to check that the caller is allowed
1487         */
1488        @Override
1489        public void cancelAllNotificationsFromListener(INotificationListener token) {
1490            NotificationListenerInfo info = checkListenerToken(token);
1491            long identity = Binder.clearCallingIdentity();
1492            try {
1493                cancelAll(info.userid);
1494            } finally {
1495                Binder.restoreCallingIdentity(identity);
1496            }
1497        }
1498
1499        /**
1500         * Allow an INotificationListener to simulate clearing (dismissing) a single notification.
1501         *
1502         * {@see com.android.server.StatusBarManagerService.NotificationCallbacks#onNotificationClear}
1503         *
1504         * @param token The binder for the listener, to check that the caller is allowed
1505         */
1506        @Override
1507        public void cancelNotificationFromListener(INotificationListener token, String pkg,
1508                String tag, int id) {
1509            NotificationListenerInfo info = checkListenerToken(token);
1510            long identity = Binder.clearCallingIdentity();
1511            try {
1512                cancelNotification(pkg, tag, id, 0,
1513                        Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE,
1514                        true,
1515                        info.userid);
1516            } finally {
1517                Binder.restoreCallingIdentity(identity);
1518            }
1519        }
1520
1521        /**
1522         * Allow an INotificationListener to request the list of outstanding notifications seen by
1523         * the current user. Useful when starting up, after which point the listener callbacks
1524         * should be used.
1525         *
1526         * @param token The binder for the listener, to check that the caller is allowed
1527         */
1528        @Override
1529        public StatusBarNotification[] getActiveNotificationsFromListener(
1530                INotificationListener token) {
1531            NotificationListenerInfo info = checkListenerToken(token);
1532
1533            StatusBarNotification[] result = new StatusBarNotification[0];
1534            ArrayList<StatusBarNotification> list = new ArrayList<StatusBarNotification>();
1535            synchronized (mNotificationList) {
1536                final int N = mNotificationList.size();
1537                for (int i=0; i<N; i++) {
1538                    StatusBarNotification sbn = mNotificationList.get(i).sbn;
1539                    if (info.enabledAndUserMatches(sbn)) {
1540                        list.add(sbn);
1541                    }
1542                }
1543            }
1544            return list.toArray(result);
1545        }
1546
1547        @Override
1548        protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1549            if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1550                    != PackageManager.PERMISSION_GRANTED) {
1551                pw.println("Permission Denial: can't dump NotificationManager from from pid="
1552                        + Binder.getCallingPid()
1553                        + ", uid=" + Binder.getCallingUid());
1554                return;
1555            }
1556
1557            dumpImpl(pw);
1558        }
1559    };
1560
1561    void dumpImpl(PrintWriter pw) {
1562        pw.println("Current Notification Manager state:");
1563
1564        pw.println("  Listeners (" + mEnabledListenersForCurrentUser.size()
1565                + ") enabled for current user:");
1566        for (ComponentName cmpt : mEnabledListenersForCurrentUser) {
1567            pw.println("    " + cmpt);
1568        }
1569
1570        pw.println("  Live listeners (" + mListeners.size() + "):");
1571        for (NotificationListenerInfo info : mListeners) {
1572            pw.println("    " + info.component
1573                    + " (user " + info.userid + "): " + info.listener
1574                    + (info.isSystem?" SYSTEM":""));
1575        }
1576
1577        int N;
1578
1579        synchronized (mToastQueue) {
1580            N = mToastQueue.size();
1581            if (N > 0) {
1582                pw.println("  Toast Queue:");
1583                for (int i=0; i<N; i++) {
1584                    mToastQueue.get(i).dump(pw, "    ");
1585                }
1586                pw.println("  ");
1587            }
1588
1589        }
1590
1591        synchronized (mNotificationList) {
1592            N = mNotificationList.size();
1593            if (N > 0) {
1594                pw.println("  Notification List:");
1595                for (int i=0; i<N; i++) {
1596                    mNotificationList.get(i).dump(pw, "    ", getContext());
1597                }
1598                pw.println("  ");
1599            }
1600
1601            N = mLights.size();
1602            if (N > 0) {
1603                pw.println("  Lights List:");
1604                for (int i=0; i<N; i++) {
1605                    pw.println("    " + mLights.get(i));
1606                }
1607                pw.println("  ");
1608            }
1609
1610            pw.println("  mSoundNotification=" + mSoundNotification);
1611            pw.println("  mVibrateNotification=" + mVibrateNotification);
1612            pw.println("  mDisabledNotifications=0x"
1613                    + Integer.toHexString(mDisabledNotifications));
1614            pw.println("  mSystemReady=" + mSystemReady);
1615            pw.println("  mArchive=" + mArchive.toString());
1616            Iterator<StatusBarNotification> iter = mArchive.descendingIterator();
1617            int i=0;
1618            while (iter.hasNext()) {
1619                pw.println("    " + iter.next());
1620                if (++i >= 5) {
1621                    if (iter.hasNext()) pw.println("    ...");
1622                    break;
1623                }
1624            }
1625
1626        }
1627    }
1628
1629    /**
1630     * The private API only accessible to the system process.
1631     */
1632    private final NotificationManagerInternal mInternalService = new NotificationManagerInternal() {
1633        @Override
1634        public void enqueueNotification(String pkg, String basePkg, int callingUid, int callingPid,
1635                String tag, int id, Notification notification, int[] idReceived, int userId) {
1636            enqueueNotificationInternal(pkg, basePkg, callingUid, callingPid, tag, id, notification,
1637                    idReceived, userId);
1638        }
1639    };
1640
1641    void enqueueNotificationInternal(final String pkg, String basePkg, final int callingUid,
1642            final int callingPid, final String tag, final int id, final Notification notification,
1643            int[] idOut, int incomingUserId) {
1644        if (DBG) {
1645            Slog.v(TAG, "enqueueNotificationInternal: pkg=" + pkg + " id=" + id
1646                    + " notification=" + notification);
1647        }
1648        checkCallerIsSystemOrSameApp(pkg);
1649        final boolean isSystemNotification = isUidSystem(callingUid) || ("android".equals(pkg));
1650
1651        final int userId = ActivityManager.handleIncomingUser(callingPid,
1652                callingUid, incomingUserId, true, false, "enqueueNotification", pkg);
1653        final UserHandle user = new UserHandle(userId);
1654
1655        // Limit the number of notifications that any given package except the android
1656        // package can enqueue.  Prevents DOS attacks and deals with leaks.
1657        if (!isSystemNotification) {
1658            synchronized (mNotificationList) {
1659                int count = 0;
1660                final int N = mNotificationList.size();
1661                for (int i=0; i<N; i++) {
1662                    final NotificationRecord r = mNotificationList.get(i);
1663                    if (r.sbn.getPackageName().equals(pkg) && r.sbn.getUserId() == userId) {
1664                        count++;
1665                        if (count >= MAX_PACKAGE_NOTIFICATIONS) {
1666                            Slog.e(TAG, "Package has already posted " + count
1667                                    + " notifications.  Not showing more.  package=" + pkg);
1668                            return;
1669                        }
1670                    }
1671                }
1672            }
1673        }
1674
1675        // This conditional is a dirty hack to limit the logging done on
1676        //     behalf of the download manager without affecting other apps.
1677        if (!pkg.equals("com.android.providers.downloads")
1678                || Log.isLoggable("DownloadManager", Log.VERBOSE)) {
1679            EventLog.writeEvent(EventLogTags.NOTIFICATION_ENQUEUE, pkg, id, tag, userId,
1680                    notification.toString());
1681        }
1682
1683        if (pkg == null || notification == null) {
1684            throw new IllegalArgumentException("null not allowed: pkg=" + pkg
1685                    + " id=" + id + " notification=" + notification);
1686        }
1687        if (notification.icon != 0) {
1688            if (notification.contentView == null) {
1689                throw new IllegalArgumentException("contentView required: pkg=" + pkg
1690                        + " id=" + id + " notification=" + notification);
1691            }
1692        }
1693
1694        mHandler.post(new Runnable() {
1695            @Override
1696            public void run() {
1697
1698                // === Scoring ===
1699
1700                // 0. Sanitize inputs
1701                notification.priority = clamp(notification.priority, Notification.PRIORITY_MIN,
1702                        Notification.PRIORITY_MAX);
1703                // Migrate notification flags to scores
1704                if (0 != (notification.flags & Notification.FLAG_HIGH_PRIORITY)) {
1705                    if (notification.priority < Notification.PRIORITY_MAX) {
1706                        notification.priority = Notification.PRIORITY_MAX;
1707                    }
1708                } else if (SCORE_ONGOING_HIGHER &&
1709                        0 != (notification.flags & Notification.FLAG_ONGOING_EVENT)) {
1710                    if (notification.priority < Notification.PRIORITY_HIGH) {
1711                        notification.priority = Notification.PRIORITY_HIGH;
1712                    }
1713                }
1714
1715                // 1. initial score: buckets of 10, around the app
1716                int score = notification.priority * NOTIFICATION_PRIORITY_MULTIPLIER; //[-20..20]
1717
1718                // 2. Consult external heuristics (TBD)
1719
1720                // 3. Apply local rules
1721
1722                int initialScore = score;
1723                if (!mScorers.isEmpty()) {
1724                    if (DBG) Slog.v(TAG, "Initial score is " + score + ".");
1725                    for (NotificationScorer scorer : mScorers) {
1726                        try {
1727                            score = scorer.getScore(notification, score);
1728                        } catch (Throwable t) {
1729                            Slog.w(TAG, "Scorer threw on .getScore.", t);
1730                        }
1731                    }
1732                    if (DBG) Slog.v(TAG, "Final score is " + score + ".");
1733                }
1734
1735                // add extra to indicate score modified by NotificationScorer
1736                notification.extras.putBoolean(Notification.EXTRA_SCORE_MODIFIED,
1737                        score != initialScore);
1738
1739                // blocked apps
1740                if (ENABLE_BLOCKED_NOTIFICATIONS && !noteNotificationOp(pkg, callingUid)) {
1741                    if (!isSystemNotification) {
1742                        score = JUNK_SCORE;
1743                        Slog.e(TAG, "Suppressing notification from package " + pkg
1744                                + " by user request.");
1745                    }
1746                }
1747
1748                if (DBG) {
1749                    Slog.v(TAG, "Assigned score=" + score + " to " + notification);
1750                }
1751
1752                if (score < SCORE_DISPLAY_THRESHOLD) {
1753                    // Notification will be blocked because the score is too low.
1754                    return;
1755                }
1756
1757                // Should this notification make noise, vibe, or use the LED?
1758                final boolean canInterrupt = (score >= SCORE_INTERRUPTION_THRESHOLD);
1759
1760                synchronized (mNotificationList) {
1761                    final StatusBarNotification n = new StatusBarNotification(
1762                            pkg, id, tag, callingUid, callingPid, score, notification, user);
1763                    NotificationRecord r = new NotificationRecord(n);
1764                    NotificationRecord old = null;
1765
1766                    int index = indexOfNotificationLocked(pkg, tag, id, userId);
1767                    if (index < 0) {
1768                        mNotificationList.add(r);
1769                    } else {
1770                        old = mNotificationList.remove(index);
1771                        mNotificationList.add(index, r);
1772                        // Make sure we don't lose the foreground service state.
1773                        if (old != null) {
1774                            notification.flags |=
1775                                old.getNotification().flags & Notification.FLAG_FOREGROUND_SERVICE;
1776                        }
1777                    }
1778
1779                    // Ensure if this is a foreground service that the proper additional
1780                    // flags are set.
1781                    if ((notification.flags&Notification.FLAG_FOREGROUND_SERVICE) != 0) {
1782                        notification.flags |= Notification.FLAG_ONGOING_EVENT
1783                                | Notification.FLAG_NO_CLEAR;
1784                    }
1785
1786                    final int currentUser;
1787                    final long token = Binder.clearCallingIdentity();
1788                    try {
1789                        currentUser = ActivityManager.getCurrentUser();
1790                    } finally {
1791                        Binder.restoreCallingIdentity(token);
1792                    }
1793
1794                    if (notification.icon != 0) {
1795                        if (old != null && old.statusBarKey != null) {
1796                            r.statusBarKey = old.statusBarKey;
1797                            final long identity = Binder.clearCallingIdentity();
1798                            try {
1799                                mStatusBar.updateNotification(r.statusBarKey, n);
1800                            } finally {
1801                                Binder.restoreCallingIdentity(identity);
1802                            }
1803                        } else {
1804                            final long identity = Binder.clearCallingIdentity();
1805                            try {
1806                                r.statusBarKey = mStatusBar.addNotification(n);
1807                                if ((n.getNotification().flags & Notification.FLAG_SHOW_LIGHTS) != 0
1808                                        && canInterrupt) {
1809                                    mAttentionLight.pulse();
1810                                }
1811                            } finally {
1812                                Binder.restoreCallingIdentity(identity);
1813                            }
1814                        }
1815                        // Send accessibility events only for the current user.
1816                        if (currentUser == userId) {
1817                            sendAccessibilityEvent(notification, pkg);
1818                        }
1819
1820                        notifyPostedLocked(r);
1821                    } else {
1822                        Slog.e(TAG, "Not posting notification with icon==0: " + notification);
1823                        if (old != null && old.statusBarKey != null) {
1824                            final long identity = Binder.clearCallingIdentity();
1825                            try {
1826                                mStatusBar.removeNotification(old.statusBarKey);
1827                            } finally {
1828                                Binder.restoreCallingIdentity(identity);
1829                            }
1830
1831                            notifyRemovedLocked(r);
1832                        }
1833                        // ATTENTION: in a future release we will bail out here
1834                        // so that we do not play sounds, show lights, etc. for invalid
1835                        // notifications
1836                        Slog.e(TAG, "WARNING: In a future release this will crash the app: "
1837                                + n.getPackageName());
1838                    }
1839
1840                    // If we're not supposed to beep, vibrate, etc. then don't.
1841                    if (((mDisabledNotifications
1842                            & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) == 0)
1843                            && (!(old != null
1844                                && (notification.flags & Notification.FLAG_ONLY_ALERT_ONCE) != 0 ))
1845                            && (r.getUserId() == UserHandle.USER_ALL ||
1846                                (r.getUserId() == userId && r.getUserId() == currentUser))
1847                            && canInterrupt
1848                            && mSystemReady
1849                            && mAudioManager != null) {
1850
1851                        // sound
1852
1853                        // should we use the default notification sound? (indicated either by
1854                        // DEFAULT_SOUND or because notification.sound is pointing at
1855                        // Settings.System.NOTIFICATION_SOUND)
1856                        final boolean useDefaultSound =
1857                               (notification.defaults & Notification.DEFAULT_SOUND) != 0 ||
1858                                       Settings.System.DEFAULT_NOTIFICATION_URI
1859                                               .equals(notification.sound);
1860
1861                        Uri soundUri = null;
1862                        boolean hasValidSound = false;
1863
1864                        if (useDefaultSound) {
1865                            soundUri = Settings.System.DEFAULT_NOTIFICATION_URI;
1866
1867                            // check to see if the default notification sound is silent
1868                            ContentResolver resolver = getContext().getContentResolver();
1869                            hasValidSound = Settings.System.getString(resolver,
1870                                   Settings.System.NOTIFICATION_SOUND) != null;
1871                        } else if (notification.sound != null) {
1872                            soundUri = notification.sound;
1873                            hasValidSound = (soundUri != null);
1874                        }
1875
1876                        if (hasValidSound) {
1877                            boolean looping =
1878                                    (notification.flags & Notification.FLAG_INSISTENT) != 0;
1879                            int audioStreamType;
1880                            if (notification.audioStreamType >= 0) {
1881                                audioStreamType = notification.audioStreamType;
1882                            } else {
1883                                audioStreamType = DEFAULT_STREAM_TYPE;
1884                            }
1885                            mSoundNotification = r;
1886                            // do not play notifications if stream volume is 0 (typically because
1887                            // ringer mode is silent) or if there is a user of exclusive audio focus
1888                            if ((mAudioManager.getStreamVolume(audioStreamType) != 0)
1889                                    && !mAudioManager.isAudioFocusExclusive()) {
1890                                final long identity = Binder.clearCallingIdentity();
1891                                try {
1892                                    final IRingtonePlayer player =
1893                                            mAudioManager.getRingtonePlayer();
1894                                    if (player != null) {
1895                                        player.playAsync(soundUri, user, looping, audioStreamType);
1896                                    }
1897                                } catch (RemoteException e) {
1898                                } finally {
1899                                    Binder.restoreCallingIdentity(identity);
1900                                }
1901                            }
1902                        }
1903
1904                        // vibrate
1905                        // Does the notification want to specify its own vibration?
1906                        final boolean hasCustomVibrate = notification.vibrate != null;
1907
1908                        // new in 4.2: if there was supposed to be a sound and we're in vibrate
1909                        // mode, and no other vibration is specified, we fall back to vibration
1910                        final boolean convertSoundToVibration =
1911                                   !hasCustomVibrate
1912                                && hasValidSound
1913                                && (mAudioManager.getRingerMode()
1914                                           == AudioManager.RINGER_MODE_VIBRATE);
1915
1916                        // The DEFAULT_VIBRATE flag trumps any custom vibration AND the fallback.
1917                        final boolean useDefaultVibrate =
1918                                (notification.defaults & Notification.DEFAULT_VIBRATE) != 0;
1919
1920                        if ((useDefaultVibrate || convertSoundToVibration || hasCustomVibrate)
1921                                && !(mAudioManager.getRingerMode()
1922                                        == AudioManager.RINGER_MODE_SILENT)) {
1923                            mVibrateNotification = r;
1924
1925                            if (useDefaultVibrate || convertSoundToVibration) {
1926                                // Escalate privileges so we can use the vibrator even if the
1927                                // notifying app does not have the VIBRATE permission.
1928                                long identity = Binder.clearCallingIdentity();
1929                                try {
1930                                    mVibrator.vibrate(r.sbn.getUid(), r.sbn.getBasePkg(),
1931                                        useDefaultVibrate ? mDefaultVibrationPattern
1932                                            : mFallbackVibrationPattern,
1933                                        ((notification.flags & Notification.FLAG_INSISTENT) != 0)
1934                                                ? 0: -1);
1935                                } finally {
1936                                    Binder.restoreCallingIdentity(identity);
1937                                }
1938                            } else if (notification.vibrate.length > 1) {
1939                                // If you want your own vibration pattern, you need the VIBRATE
1940                                // permission
1941                                mVibrator.vibrate(r.sbn.getUid(), r.sbn.getBasePkg(),
1942                                        notification.vibrate,
1943                                    ((notification.flags & Notification.FLAG_INSISTENT) != 0)
1944                                            ? 0: -1);
1945                            }
1946                        }
1947                    }
1948
1949                    // light
1950                    // the most recent thing gets the light
1951                    mLights.remove(old);
1952                    if (mLedNotification == old) {
1953                        mLedNotification = null;
1954                    }
1955                    //Slog.i(TAG, "notification.lights="
1956                    //        + ((old.notification.lights.flags & Notification.FLAG_SHOW_LIGHTS)
1957                    //                  != 0));
1958                    if ((notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0
1959                            && canInterrupt) {
1960                        mLights.add(r);
1961                        updateLightsLocked();
1962                    } else {
1963                        if (old != null
1964                                && ((old.getFlags() & Notification.FLAG_SHOW_LIGHTS) != 0)) {
1965                            updateLightsLocked();
1966                        }
1967                    }
1968                }
1969            }
1970        });
1971
1972        idOut[0] = id;
1973    }
1974
1975     void registerListenerImpl(final INotificationListener listener,
1976            final ComponentName component, final int userid) {
1977        synchronized (mNotificationList) {
1978            try {
1979                NotificationListenerInfo info
1980                        = new NotificationListenerInfo(listener, component, userid, true);
1981                listener.asBinder().linkToDeath(info, 0);
1982                mListeners.add(info);
1983            } catch (RemoteException e) {
1984                // already dead
1985            }
1986        }
1987    }
1988
1989    void unregisterListenerImpl(final INotificationListener listener, final int userid) {
1990        synchronized (mNotificationList) {
1991            final int N = mListeners.size();
1992            for (int i=N-1; i>=0; i--) {
1993                final NotificationListenerInfo info = mListeners.get(i);
1994                if (info.listener.asBinder() == listener.asBinder()
1995                        && info.userid == userid) {
1996                    mListeners.remove(i);
1997                    if (info.connection != null) {
1998                        getContext().unbindService(info.connection);
1999                    }
2000                }
2001            }
2002        }
2003    }
2004
2005    void showNextToastLocked() {
2006        ToastRecord record = mToastQueue.get(0);
2007        while (record != null) {
2008            if (DBG) Slog.d(TAG, "Show pkg=" + record.pkg + " callback=" + record.callback);
2009            try {
2010                record.callback.show();
2011                scheduleTimeoutLocked(record);
2012                return;
2013            } catch (RemoteException e) {
2014                Slog.w(TAG, "Object died trying to show notification " + record.callback
2015                        + " in package " + record.pkg);
2016                // remove it from the list and let the process die
2017                int index = mToastQueue.indexOf(record);
2018                if (index >= 0) {
2019                    mToastQueue.remove(index);
2020                }
2021                keepProcessAliveLocked(record.pid);
2022                if (mToastQueue.size() > 0) {
2023                    record = mToastQueue.get(0);
2024                } else {
2025                    record = null;
2026                }
2027            }
2028        }
2029    }
2030
2031    void cancelToastLocked(int index) {
2032        ToastRecord record = mToastQueue.get(index);
2033        try {
2034            record.callback.hide();
2035        } catch (RemoteException e) {
2036            Slog.w(TAG, "Object died trying to hide notification " + record.callback
2037                    + " in package " + record.pkg);
2038            // don't worry about this, we're about to remove it from
2039            // the list anyway
2040        }
2041        mToastQueue.remove(index);
2042        keepProcessAliveLocked(record.pid);
2043        if (mToastQueue.size() > 0) {
2044            // Show the next one. If the callback fails, this will remove
2045            // it from the list, so don't assume that the list hasn't changed
2046            // after this point.
2047            showNextToastLocked();
2048        }
2049    }
2050
2051    private void scheduleTimeoutLocked(ToastRecord r)
2052    {
2053        mHandler.removeCallbacksAndMessages(r);
2054        Message m = Message.obtain(mHandler, MESSAGE_TIMEOUT, r);
2055        long delay = r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY;
2056        mHandler.sendMessageDelayed(m, delay);
2057    }
2058
2059    private void handleTimeout(ToastRecord record)
2060    {
2061        if (DBG) Slog.d(TAG, "Timeout pkg=" + record.pkg + " callback=" + record.callback);
2062        synchronized (mToastQueue) {
2063            int index = indexOfToastLocked(record.pkg, record.callback);
2064            if (index >= 0) {
2065                cancelToastLocked(index);
2066            }
2067        }
2068    }
2069
2070    // lock on mToastQueue
2071    int indexOfToastLocked(String pkg, ITransientNotification callback)
2072    {
2073        IBinder cbak = callback.asBinder();
2074        ArrayList<ToastRecord> list = mToastQueue;
2075        int len = list.size();
2076        for (int i=0; i<len; i++) {
2077            ToastRecord r = list.get(i);
2078            if (r.pkg.equals(pkg) && r.callback.asBinder() == cbak) {
2079                return i;
2080            }
2081        }
2082        return -1;
2083    }
2084
2085    // lock on mToastQueue
2086    void keepProcessAliveLocked(int pid)
2087    {
2088        int toastCount = 0; // toasts from this pid
2089        ArrayList<ToastRecord> list = mToastQueue;
2090        int N = list.size();
2091        for (int i=0; i<N; i++) {
2092            ToastRecord r = list.get(i);
2093            if (r.pid == pid) {
2094                toastCount++;
2095            }
2096        }
2097        try {
2098            mAm.setProcessForeground(mForegroundToken, pid, toastCount > 0);
2099        } catch (RemoteException e) {
2100            // Shouldn't happen.
2101        }
2102    }
2103
2104    private final class WorkerHandler extends Handler
2105    {
2106        @Override
2107        public void handleMessage(Message msg)
2108        {
2109            switch (msg.what)
2110            {
2111                case MESSAGE_TIMEOUT:
2112                    handleTimeout((ToastRecord)msg.obj);
2113                    break;
2114            }
2115        }
2116    }
2117
2118
2119    // Notifications
2120    // ============================================================================
2121    static int clamp(int x, int low, int high) {
2122        return (x < low) ? low : ((x > high) ? high : x);
2123    }
2124
2125    void sendAccessibilityEvent(Notification notification, CharSequence packageName) {
2126        AccessibilityManager manager = AccessibilityManager.getInstance(getContext());
2127        if (!manager.isEnabled()) {
2128            return;
2129        }
2130
2131        AccessibilityEvent event =
2132            AccessibilityEvent.obtain(AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED);
2133        event.setPackageName(packageName);
2134        event.setClassName(Notification.class.getName());
2135        event.setParcelableData(notification);
2136        CharSequence tickerText = notification.tickerText;
2137        if (!TextUtils.isEmpty(tickerText)) {
2138            event.getText().add(tickerText);
2139        }
2140
2141        manager.sendAccessibilityEvent(event);
2142    }
2143
2144    private void cancelNotificationLocked(NotificationRecord r, boolean sendDelete) {
2145        // tell the app
2146        if (sendDelete) {
2147            if (r.getNotification().deleteIntent != null) {
2148                try {
2149                    r.getNotification().deleteIntent.send();
2150                } catch (PendingIntent.CanceledException ex) {
2151                    // do nothing - there's no relevant way to recover, and
2152                    //     no reason to let this propagate
2153                    Slog.w(TAG, "canceled PendingIntent for " + r.sbn.getPackageName(), ex);
2154                }
2155            }
2156        }
2157
2158        // status bar
2159        if (r.getNotification().icon != 0) {
2160            final long identity = Binder.clearCallingIdentity();
2161            try {
2162                mStatusBar.removeNotification(r.statusBarKey);
2163            } finally {
2164                Binder.restoreCallingIdentity(identity);
2165            }
2166            r.statusBarKey = null;
2167            notifyRemovedLocked(r);
2168        }
2169
2170        // sound
2171        if (mSoundNotification == r) {
2172            mSoundNotification = null;
2173            final long identity = Binder.clearCallingIdentity();
2174            try {
2175                final IRingtonePlayer player = mAudioManager.getRingtonePlayer();
2176                if (player != null) {
2177                    player.stopAsync();
2178                }
2179            } catch (RemoteException e) {
2180            } finally {
2181                Binder.restoreCallingIdentity(identity);
2182            }
2183        }
2184
2185        // vibrate
2186        if (mVibrateNotification == r) {
2187            mVibrateNotification = null;
2188            long identity = Binder.clearCallingIdentity();
2189            try {
2190                mVibrator.cancel();
2191            }
2192            finally {
2193                Binder.restoreCallingIdentity(identity);
2194            }
2195        }
2196
2197        // light
2198        mLights.remove(r);
2199        if (mLedNotification == r) {
2200            mLedNotification = null;
2201        }
2202
2203        // Save it for users of getHistoricalNotifications()
2204        mArchive.record(r.sbn);
2205    }
2206
2207    /**
2208     * Cancels a notification ONLY if it has all of the {@code mustHaveFlags}
2209     * and none of the {@code mustNotHaveFlags}.
2210     */
2211    void cancelNotification(final String pkg, final String tag, final int id,
2212            final int mustHaveFlags, final int mustNotHaveFlags, final boolean sendDelete,
2213            final int userId) {
2214        // In enqueueNotificationInternal notifications are added by scheduling the
2215        // work on the worker handler. Hence, we also schedule the cancel on this
2216        // handler to avoid a scenario where an add notification call followed by a
2217        // remove notification call ends up in not removing the notification.
2218        mHandler.post(new Runnable() {
2219            @Override
2220            public void run() {
2221                EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL, pkg, id, tag, userId,
2222                        mustHaveFlags, mustNotHaveFlags);
2223
2224                synchronized (mNotificationList) {
2225                    int index = indexOfNotificationLocked(pkg, tag, id, userId);
2226                    if (index >= 0) {
2227                        NotificationRecord r = mNotificationList.get(index);
2228
2229                        if ((r.getNotification().flags & mustHaveFlags) != mustHaveFlags) {
2230                            return;
2231                        }
2232                        if ((r.getNotification().flags & mustNotHaveFlags) != 0) {
2233                            return;
2234                        }
2235
2236                        mNotificationList.remove(index);
2237
2238                        cancelNotificationLocked(r, sendDelete);
2239                        updateLightsLocked();
2240                    }
2241                }
2242            }
2243        });
2244    }
2245
2246    /**
2247     * Determine whether the userId applies to the notification in question, either because
2248     * they match exactly, or one of them is USER_ALL (which is treated as a wildcard).
2249     */
2250    private boolean notificationMatchesUserId(NotificationRecord r, int userId) {
2251        return
2252                // looking for USER_ALL notifications? match everything
2253                   userId == UserHandle.USER_ALL
2254                // a notification sent to USER_ALL matches any query
2255                || r.getUserId() == UserHandle.USER_ALL
2256                // an exact user match
2257                || r.getUserId() == userId;
2258    }
2259
2260    /**
2261     * Cancels all notifications from a given package that have all of the
2262     * {@code mustHaveFlags}.
2263     */
2264    boolean cancelAllNotificationsInt(String pkg, int mustHaveFlags,
2265            int mustNotHaveFlags, boolean doit, int userId) {
2266        EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL_ALL, pkg, userId,
2267                mustHaveFlags, mustNotHaveFlags);
2268
2269        synchronized (mNotificationList) {
2270            final int N = mNotificationList.size();
2271            boolean canceledSomething = false;
2272            for (int i = N-1; i >= 0; --i) {
2273                NotificationRecord r = mNotificationList.get(i);
2274                if (!notificationMatchesUserId(r, userId)) {
2275                    continue;
2276                }
2277                // Don't remove notifications to all, if there's no package name specified
2278                if (r.getUserId() == UserHandle.USER_ALL && pkg == null) {
2279                    continue;
2280                }
2281                if ((r.getFlags() & mustHaveFlags) != mustHaveFlags) {
2282                    continue;
2283                }
2284                if ((r.getFlags() & mustNotHaveFlags) != 0) {
2285                    continue;
2286                }
2287                if (pkg != null && !r.sbn.getPackageName().equals(pkg)) {
2288                    continue;
2289                }
2290                canceledSomething = true;
2291                if (!doit) {
2292                    return true;
2293                }
2294                mNotificationList.remove(i);
2295                cancelNotificationLocked(r, false);
2296            }
2297            if (canceledSomething) {
2298                updateLightsLocked();
2299            }
2300            return canceledSomething;
2301        }
2302    }
2303
2304
2305
2306    // Return true if the UID is a system or phone UID and therefore should not have
2307    // any notifications or toasts blocked.
2308    boolean isUidSystem(int uid) {
2309        final int appid = UserHandle.getAppId(uid);
2310        return (appid == Process.SYSTEM_UID || appid == Process.PHONE_UID || uid == 0);
2311    }
2312
2313    // same as isUidSystem(int, int) for the Binder caller's UID.
2314    boolean isCallerSystem() {
2315        return isUidSystem(Binder.getCallingUid());
2316    }
2317
2318    void checkCallerIsSystem() {
2319        if (isCallerSystem()) {
2320            return;
2321        }
2322        throw new SecurityException("Disallowed call for uid " + Binder.getCallingUid());
2323    }
2324
2325    void checkCallerIsSystemOrSameApp(String pkg) {
2326        if (isCallerSystem()) {
2327            return;
2328        }
2329        final int uid = Binder.getCallingUid();
2330        try {
2331            ApplicationInfo ai = AppGlobals.getPackageManager().getApplicationInfo(
2332                    pkg, 0, UserHandle.getCallingUserId());
2333            if (!UserHandle.isSameApp(ai.uid, uid)) {
2334                throw new SecurityException("Calling uid " + uid + " gave package"
2335                        + pkg + " which is owned by uid " + ai.uid);
2336            }
2337        } catch (RemoteException re) {
2338            throw new SecurityException("Unknown package " + pkg + "\n" + re);
2339        }
2340    }
2341
2342    void cancelAll(int userId) {
2343        synchronized (mNotificationList) {
2344            final int N = mNotificationList.size();
2345            for (int i=N-1; i>=0; i--) {
2346                NotificationRecord r = mNotificationList.get(i);
2347
2348                if (!notificationMatchesUserId(r, userId)) {
2349                    continue;
2350                }
2351
2352                if ((r.getFlags() & (Notification.FLAG_ONGOING_EVENT
2353                                | Notification.FLAG_NO_CLEAR)) == 0) {
2354                    mNotificationList.remove(i);
2355                    cancelNotificationLocked(r, true);
2356                }
2357            }
2358
2359            updateLightsLocked();
2360        }
2361    }
2362
2363    // lock on mNotificationList
2364    void updateLightsLocked()
2365    {
2366        // handle notification lights
2367        if (mLedNotification == null) {
2368            // get next notification, if any
2369            int n = mLights.size();
2370            if (n > 0) {
2371                mLedNotification = mLights.get(n-1);
2372            }
2373        }
2374
2375        // Don't flash while we are in a call or screen is on
2376        if (mLedNotification == null || mInCall || mScreenOn) {
2377            mNotificationLight.turnOff();
2378        } else {
2379            final Notification ledno = mLedNotification.sbn.getNotification();
2380            int ledARGB = ledno.ledARGB;
2381            int ledOnMS = ledno.ledOnMS;
2382            int ledOffMS = ledno.ledOffMS;
2383            if ((ledno.defaults & Notification.DEFAULT_LIGHTS) != 0) {
2384                ledARGB = mDefaultNotificationColor;
2385                ledOnMS = mDefaultNotificationLedOn;
2386                ledOffMS = mDefaultNotificationLedOff;
2387            }
2388            if (mNotificationPulseEnabled) {
2389                // pulse repeatedly
2390                mNotificationLight.setFlashing(ledARGB, Light.LIGHT_FLASH_TIMED,
2391                        ledOnMS, ledOffMS);
2392            }
2393        }
2394    }
2395
2396    // lock on mNotificationList
2397    int indexOfNotificationLocked(String pkg, String tag, int id, int userId)
2398    {
2399        ArrayList<NotificationRecord> list = mNotificationList;
2400        final int len = list.size();
2401        for (int i=0; i<len; i++) {
2402            NotificationRecord r = list.get(i);
2403            if (!notificationMatchesUserId(r, userId) || r.sbn.getId() != id) {
2404                continue;
2405            }
2406            if (tag == null) {
2407                if (r.sbn.getTag() != null) {
2408                    continue;
2409                }
2410            } else {
2411                if (!tag.equals(r.sbn.getTag())) {
2412                    continue;
2413                }
2414            }
2415            if (r.sbn.getPackageName().equals(pkg)) {
2416                return i;
2417            }
2418        }
2419        return -1;
2420    }
2421
2422    private void updateNotificationPulse() {
2423        synchronized (mNotificationList) {
2424            updateLightsLocked();
2425        }
2426    }
2427}
2428