blob: 868278b0748c7ddac0fbb7694eaff11f391f31ad [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey098d5802012-04-26 17:30:34 -070019import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
20import static org.xmlpull.v1.XmlPullParser.END_TAG;
21import static org.xmlpull.v1.XmlPullParser.START_TAG;
svetoslavganov75986cf2009-05-14 22:28:01 -070022
Dianne Hackborn41203752012-08-31 14:05:51 -070023import android.app.ActivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.app.ActivityManagerNative;
Amith Yamasanif203aee2012-08-29 18:41:53 -070025import android.app.AppGlobals;
Daniel Sandler4a900acd2013-01-30 14:04:10 -050026import android.app.AppOpsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import 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;
Daniel Sandler5feceeb2013-03-22 18:29:23 -070034import android.content.ComponentName;
Dianne Hackborn1dac2772009-06-26 18:16:48 -070035import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.content.Context;
37import android.content.Intent;
38import android.content.IntentFilter;
Daniel Sandler5feceeb2013-03-22 18:29:23 -070039import android.content.ServiceConnection;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070040import android.content.pm.ApplicationInfo;
Daniel Sandler4a900acd2013-01-30 14:04:10 -050041import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.pm.PackageManager;
Chris Wrenae9bb572013-05-15 14:50:28 -040043import android.content.pm.ResolveInfo;
44import android.content.pm.ServiceInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.PackageManager.NameNotFoundException;
46import android.content.res.Resources;
Dianne Hackborn1dac2772009-06-26 18:16:48 -070047import android.database.ContentObserver;
Daniel Sandlerf45564e2013-04-15 15:05:08 -040048import android.graphics.Bitmap;
svetoslavganov75986cf2009-05-14 22:28:01 -070049import android.media.AudioManager;
Jeff Sharkey098d5802012-04-26 17:30:34 -070050import android.media.IAudioService;
51import android.media.IRingtonePlayer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.Binder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.os.IBinder;
56import android.os.Message;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070057import android.os.Process;
svetoslavganov75986cf2009-05-14 22:28:01 -070058import android.os.RemoteException;
Jeff Sharkey098d5802012-04-26 17:30:34 -070059import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070060import android.os.UserHandle;
Daniel Sandler4b749ef2013-03-18 21:53:04 -040061import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.os.Vibrator;
63import android.provider.Settings;
Daniel Sandler5feceeb2013-03-22 18:29:23 -070064import android.service.notification.INotificationListener;
65import android.service.notification.NotificationListenerService;
66import android.service.notification.StatusBarNotification;
Daniel Sandlere96ffb12010-03-11 13:38:06 -050067import android.telephony.TelephonyManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070068import android.text.TextUtils;
Dianne Hackborn39606a02012-07-31 17:54:35 -070069import android.util.AtomicFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.util.EventLog;
71import android.util.Log;
Andy Stadler110988c2010-12-03 14:29:16 -080072import android.util.Slog;
Daniel Sandler0da673f2012-04-11 12:33:16 -040073import android.util.Xml;
svetoslavganov75986cf2009-05-14 22:28:01 -070074import android.view.accessibility.AccessibilityEvent;
75import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.widget.Toast;
77
Jeff Sharkey098d5802012-04-26 17:30:34 -070078import org.xmlpull.v1.XmlPullParser;
79import org.xmlpull.v1.XmlPullParserException;
Jeff Sharkey098d5802012-04-26 17:30:34 -070080
Daniel Sandler0da673f2012-04-11 12:33:16 -040081import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import java.io.FileDescriptor;
Daniel Sandler0da673f2012-04-11 12:33:16 -040083import java.io.FileInputStream;
84import java.io.FileNotFoundException;
Daniel Sandler0da673f2012-04-11 12:33:16 -040085import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import java.io.PrintWriter;
Daniel Sandlerf45564e2013-04-15 15:05:08 -040087import java.lang.reflect.Array;
Daniel Sandlerfde19b12013-01-17 00:21:05 -050088import java.util.ArrayDeque;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import java.util.ArrayList;
90import java.util.Arrays;
Daniel Sandler0da673f2012-04-11 12:33:16 -040091import java.util.HashSet;
Daniel Sandlerfde19b12013-01-17 00:21:05 -050092import java.util.Iterator;
Chris Wrenae9bb572013-05-15 14:50:28 -040093import java.util.List;
Daniel Sandlerfde19b12013-01-17 00:21:05 -050094import java.util.NoSuchElementException;
Chris Wrenae9bb572013-05-15 14:50:28 -040095import java.util.Set;
Daniel Sandler0da673f2012-04-11 12:33:16 -040096
97import libcore.io.IoUtils;
98
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099
Daniel Sandlerd0a2f862010-08-03 15:29:31 -0400100/** {@hide} */
101public class NotificationManagerService extends INotificationManager.Stub
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102{
103 private static final String TAG = "NotificationService";
104 private static final boolean DBG = false;
105
Joe Onoratobd73d012010-06-04 11:44:54 -0700106 private static final int MAX_PACKAGE_NOTIFICATIONS = 50;
107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 // message codes
109 private static final int MESSAGE_TIMEOUT = 2;
110
111 private static final int LONG_DELAY = 3500; // 3.5 seconds
112 private static final int SHORT_DELAY = 2000; // 2 seconds
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800113
114 private static final long[] DEFAULT_VIBRATE_PATTERN = {0, 250, 250, 250};
Daniel Sandleredbb3802012-11-13 20:49:47 -0800115 private static final int VIBRATE_PATTERN_MAXLEN = 8 * 2 + 1; // up to eight bumps
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116
117 private static final int DEFAULT_STREAM_TYPE = AudioManager.STREAM_NOTIFICATION;
Daniel Sandler49a2ad12012-03-28 15:46:39 -0400118 private static final boolean SCORE_ONGOING_HIGHER = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119
Daniel Sandler0da673f2012-04-11 12:33:16 -0400120 private static final int JUNK_SCORE = -1000;
121 private static final int NOTIFICATION_PRIORITY_MULTIPLIER = 10;
122 private static final int SCORE_DISPLAY_THRESHOLD = Notification.PRIORITY_MIN * NOTIFICATION_PRIORITY_MULTIPLIER;
123
Daniel Sandler526fa0e2012-12-04 14:51:50 -0500124 // Notifications with scores below this will not interrupt the user, either via LED or
125 // sound or vibration
126 private static final int SCORE_INTERRUPTION_THRESHOLD =
127 Notification.PRIORITY_LOW * NOTIFICATION_PRIORITY_MULTIPLIER;
128
Daniel Sandler0da673f2012-04-11 12:33:16 -0400129 private static final boolean ENABLE_BLOCKED_NOTIFICATIONS = true;
130 private static final boolean ENABLE_BLOCKED_TOASTS = true;
131
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700132 private static final String ENABLED_NOTIFICATION_LISTENERS_SEPARATOR = ":";
133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134 final Context mContext;
135 final IActivityManager mAm;
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400136 final UserManager mUserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 final IBinder mForegroundToken = new Binder();
138
139 private WorkerHandler mHandler;
Joe Onorato089de882010-04-12 08:18:45 -0700140 private StatusBarManagerService mStatusBar;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500141 private LightsService.Light mNotificationLight;
142 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
Mike Lockwood670f9322010-01-20 12:13:36 -0500144 private int mDefaultNotificationColor;
145 private int mDefaultNotificationLedOn;
146 private int mDefaultNotificationLedOff;
147
Daniel Sandleredbb3802012-11-13 20:49:47 -0800148 private long[] mDefaultVibrationPattern;
149 private long[] mFallbackVibrationPattern;
150
Joe Onorato30275482009-07-08 17:09:14 -0700151 private boolean mSystemReady;
Joe Onorato39f5b6a2009-07-23 12:29:19 -0400152 private int mDisabledNotifications;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153
Jeff Sharkey098d5802012-04-26 17:30:34 -0700154 private NotificationRecord mSoundNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 private NotificationRecord mVibrateNotification;
Jeff Sharkey098d5802012-04-26 17:30:34 -0700156
157 private IAudioService mAudioService;
Jeff Brownc2346132012-04-13 01:55:38 -0700158 private Vibrator mVibrator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
Mike Lockwoodc22404a2009-12-02 11:15:02 -0500160 // for enabling and disabling notification pulse behavior
Mike Lockwood63b5ad92011-08-30 09:55:30 -0400161 private boolean mScreenOn = true;
Daniel Sandlere96ffb12010-03-11 13:38:06 -0500162 private boolean mInCall = false;
Mike Lockwoodc22404a2009-12-02 11:15:02 -0500163 private boolean mNotificationPulseEnabled;
164
Daniel Sandler09a247e2013-02-14 10:24:17 -0500165 // used as a mutex for access to all active notifications & listeners
Fred Quintana6ecaff12009-09-25 14:23:13 -0700166 private final ArrayList<NotificationRecord> mNotificationList =
167 new ArrayList<NotificationRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168
169 private ArrayList<ToastRecord> mToastQueue;
170
171 private ArrayList<NotificationRecord> mLights = new ArrayList<NotificationRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 private NotificationRecord mLedNotification;
svetoslavganov75986cf2009-05-14 22:28:01 -0700173
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500174 private final AppOpsManager mAppOps;
175
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700176 // contains connections to all connected listeners, including app services
177 // and system listeners
178 private ArrayList<NotificationListenerInfo> mListeners
179 = new ArrayList<NotificationListenerInfo>();
180 // things that will be put into mListeners as soon as they're ready
181 private ArrayList<String> mServicesBinding = new ArrayList<String>();
182 // lists the component names of all enabled (and therefore connected) listener
183 // app services for the current user only
184 private HashSet<ComponentName> mEnabledListenersForCurrentUser
185 = new HashSet<ComponentName>();
186 // Just the packages from mEnabledListenersForCurrentUser
187 private HashSet<String> mEnabledListenerPackageNames = new HashSet<String>();
Daniel Sandler09a247e2013-02-14 10:24:17 -0500188
Daniel Sandler0da673f2012-04-11 12:33:16 -0400189 // Notification control database. For now just contains disabled packages.
190 private AtomicFile mPolicyFile;
191 private HashSet<String> mBlockedPackages = new HashSet<String>();
192
193 private static final int DB_VERSION = 1;
194
195 private static final String TAG_BODY = "notification-policy";
196 private static final String ATTR_VERSION = "version";
197
198 private static final String TAG_BLOCKED_PKGS = "blocked-packages";
199 private static final String TAG_PACKAGE = "package";
200 private static final String ATTR_NAME = "name";
201
Daniel Sandler09a247e2013-02-14 10:24:17 -0500202 private class NotificationListenerInfo implements DeathRecipient {
203 INotificationListener listener;
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700204 ComponentName component;
Daniel Sandler09a247e2013-02-14 10:24:17 -0500205 int userid;
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400206 boolean isSystem;
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700207 ServiceConnection connection;
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400208
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700209 public NotificationListenerInfo(INotificationListener listener, ComponentName component,
210 int userid, boolean isSystem) {
Daniel Sandler09a247e2013-02-14 10:24:17 -0500211 this.listener = listener;
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700212 this.component = component;
Daniel Sandler09a247e2013-02-14 10:24:17 -0500213 this.userid = userid;
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400214 this.isSystem = isSystem;
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700215 this.connection = null;
216 }
217
218 public NotificationListenerInfo(INotificationListener listener, ComponentName component,
219 int userid, ServiceConnection connection) {
220 this.listener = listener;
221 this.component = component;
222 this.userid = userid;
223 this.isSystem = false;
224 this.connection = connection;
Daniel Sandler09a247e2013-02-14 10:24:17 -0500225 }
226
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400227 boolean enabledAndUserMatches(StatusBarNotification sbn) {
228 final int nid = sbn.getUserId();
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700229 if (!isEnabledForCurrentUser()) {
230 return false;
231 }
Daniel Sandler21ca44d2013-03-07 13:58:00 -0500232 if (this.userid == UserHandle.USER_ALL) return true;
Daniel Sandler21ca44d2013-03-07 13:58:00 -0500233 return (nid == UserHandle.USER_ALL || nid == this.userid);
234 }
235
Daniel Sandler09a247e2013-02-14 10:24:17 -0500236 public void notifyPostedIfUserMatch(StatusBarNotification sbn) {
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700237 if (!enabledAndUserMatches(sbn)) {
238 return;
239 }
Daniel Sandler09a247e2013-02-14 10:24:17 -0500240 try {
241 listener.onNotificationPosted(sbn);
242 } catch (RemoteException ex) {
Daniel Sandler1a497d32013-04-18 14:52:45 -0400243 Log.e(TAG, "unable to notify listener (posted): " + listener, ex);
Daniel Sandler09a247e2013-02-14 10:24:17 -0500244 }
245 }
246
247 public void notifyRemovedIfUserMatch(StatusBarNotification sbn) {
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400248 if (!enabledAndUserMatches(sbn)) return;
Daniel Sandler09a247e2013-02-14 10:24:17 -0500249 try {
250 listener.onNotificationRemoved(sbn);
251 } catch (RemoteException ex) {
Daniel Sandler1a497d32013-04-18 14:52:45 -0400252 Log.e(TAG, "unable to notify listener (removed): " + listener, ex);
Daniel Sandler09a247e2013-02-14 10:24:17 -0500253 }
254 }
255
256 @Override
257 public void binderDied() {
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700258 if (connection == null) {
259 // This is not a service; it won't be recreated. We can give up this connection.
260 unregisterListener(this.listener, this.userid);
261 }
Daniel Sandler09a247e2013-02-14 10:24:17 -0500262 }
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400263
264 /** convenience method for looking in mEnabledListenersForCurrentUser */
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700265 public boolean isEnabledForCurrentUser() {
266 if (this.isSystem) return true;
267 if (this.connection == null) return false;
268 return mEnabledListenersForCurrentUser.contains(this.component);
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400269 }
Daniel Sandler09a247e2013-02-14 10:24:17 -0500270 }
271
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500272 private static class Archive {
Daniel Sandler5e62e3a2013-04-15 20:57:02 -0400273 static final int BUFFER_SIZE = 250;
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500274 ArrayDeque<StatusBarNotification> mBuffer = new ArrayDeque<StatusBarNotification>(BUFFER_SIZE);
275
276 public Archive() {
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500277 }
Jeff Sharkey0c1baf92013-04-03 13:08:52 -0700278
Daniel Sandler5e62e3a2013-04-15 20:57:02 -0400279 public String toString() {
280 final StringBuilder sb = new StringBuilder();
281 final int N = mBuffer.size();
282 sb.append("Archive (");
283 sb.append(N);
284 sb.append(" notification");
285 sb.append((N==1)?")":"s)");
286 return sb.toString();
287 }
288
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500289 public void record(StatusBarNotification nr) {
290 if (mBuffer.size() == BUFFER_SIZE) {
291 mBuffer.removeFirst();
292 }
Daniel Sandler26b81d52013-05-20 20:56:43 -0400293
294 // We don't want to store the heavy bits of the notification in the archive,
295 // but other clients in the system process might be using the object, so we
296 // store a (lightened) copy.
297 mBuffer.addLast(nr.cloneLight());
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500298 }
299
Daniel Sandler5e62e3a2013-04-15 20:57:02 -0400300
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500301 public void clear() {
302 mBuffer.clear();
303 }
304
305 public Iterator<StatusBarNotification> descendingIterator() {
306 return mBuffer.descendingIterator();
307 }
308 public Iterator<StatusBarNotification> ascendingIterator() {
309 return mBuffer.iterator();
310 }
311 public Iterator<StatusBarNotification> filter(
312 final Iterator<StatusBarNotification> iter, final String pkg, final int userId) {
313 return new Iterator<StatusBarNotification>() {
314 StatusBarNotification mNext = findNext();
315
316 private StatusBarNotification findNext() {
317 while (iter.hasNext()) {
318 StatusBarNotification nr = iter.next();
Daniel Sandler4f91efd2013-04-25 16:38:41 -0400319 if ((pkg == null || nr.getPackageName() == pkg)
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500320 && (userId == UserHandle.USER_ALL || nr.getUserId() == userId)) {
321 return nr;
322 }
323 }
324 return null;
325 }
326
327 @Override
328 public boolean hasNext() {
329 return mNext == null;
330 }
331
332 @Override
333 public StatusBarNotification next() {
334 StatusBarNotification next = mNext;
335 if (next == null) {
336 throw new NoSuchElementException();
337 }
338 mNext = findNext();
339 return next;
340 }
341
342 @Override
343 public void remove() {
344 iter.remove();
345 }
346 };
347 }
Daniel Sandler78d0d252013-02-12 08:14:52 -0500348
349 public StatusBarNotification[] getArray(int count) {
350 if (count == 0) count = Archive.BUFFER_SIZE;
351 final StatusBarNotification[] a
352 = new StatusBarNotification[Math.min(count, mBuffer.size())];
353 Iterator<StatusBarNotification> iter = descendingIterator();
354 int i=0;
355 while (iter.hasNext() && i < count) {
356 a[i++] = iter.next();
357 }
358 return a;
359 }
360
361 public StatusBarNotification[] getArray(int count, String pkg, int userId) {
362 if (count == 0) count = Archive.BUFFER_SIZE;
363 final StatusBarNotification[] a
364 = new StatusBarNotification[Math.min(count, mBuffer.size())];
365 Iterator<StatusBarNotification> iter = filter(descendingIterator(), pkg, userId);
366 int i=0;
367 while (iter.hasNext() && i < count) {
368 a[i++] = iter.next();
369 }
370 return a;
371 }
372
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500373 }
374
375 Archive mArchive = new Archive();
376
Daniel Sandler0da673f2012-04-11 12:33:16 -0400377 private void loadBlockDb() {
378 synchronized(mBlockedPackages) {
379 if (mPolicyFile == null) {
380 File dir = new File("/data/system");
381 mPolicyFile = new AtomicFile(new File(dir, "notification_policy.xml"));
382
383 mBlockedPackages.clear();
384
385 FileInputStream infile = null;
386 try {
387 infile = mPolicyFile.openRead();
388 final XmlPullParser parser = Xml.newPullParser();
389 parser.setInput(infile, null);
390
391 int type;
392 String tag;
393 int version = DB_VERSION;
394 while ((type = parser.next()) != END_DOCUMENT) {
395 tag = parser.getName();
396 if (type == START_TAG) {
397 if (TAG_BODY.equals(tag)) {
398 version = Integer.parseInt(parser.getAttributeValue(null, ATTR_VERSION));
399 } else if (TAG_BLOCKED_PKGS.equals(tag)) {
400 while ((type = parser.next()) != END_DOCUMENT) {
401 tag = parser.getName();
402 if (TAG_PACKAGE.equals(tag)) {
403 mBlockedPackages.add(parser.getAttributeValue(null, ATTR_NAME));
404 } else if (TAG_BLOCKED_PKGS.equals(tag) && type == END_TAG) {
405 break;
406 }
407 }
408 }
409 }
410 }
411 } catch (FileNotFoundException e) {
412 // No data yet
413 } catch (IOException e) {
414 Log.wtf(TAG, "Unable to read blocked notifications database", e);
415 } catch (NumberFormatException e) {
416 Log.wtf(TAG, "Unable to parse blocked notifications database", e);
417 } catch (XmlPullParserException e) {
418 Log.wtf(TAG, "Unable to parse blocked notifications database", e);
419 } finally {
420 IoUtils.closeQuietly(infile);
421 }
422 }
423 }
424 }
425
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500426 /**
427 * Use this when you just want to know if notifications are OK for this package.
428 */
429 public boolean areNotificationsEnabledForPackage(String pkg, int uid) {
Daniel Sandler0da673f2012-04-11 12:33:16 -0400430 checkCallerIsSystem();
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500431 return (mAppOps.checkOpNoThrow(AppOpsManager.OP_POST_NOTIFICATION, uid, pkg)
432 == AppOpsManager.MODE_ALLOWED);
Daniel Sandler0da673f2012-04-11 12:33:16 -0400433 }
434
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500435 /** Use this when you actually want to post a notification or toast.
436 *
437 * Unchecked. Not exposed via Binder, but can be called in the course of enqueue*().
438 */
439 private boolean noteNotificationOp(String pkg, int uid) {
440 if (mAppOps.noteOpNoThrow(AppOpsManager.OP_POST_NOTIFICATION, uid, pkg)
441 != AppOpsManager.MODE_ALLOWED) {
442 Slog.v(TAG, "notifications are disabled by AppOps for " + pkg);
443 return false;
Daniel Sandler0da673f2012-04-11 12:33:16 -0400444 }
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500445 return true;
Daniel Sandler0da673f2012-04-11 12:33:16 -0400446 }
447
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500448 public void setNotificationsEnabledForPackage(String pkg, int uid, boolean enabled) {
Daniel Sandler0da673f2012-04-11 12:33:16 -0400449 checkCallerIsSystem();
Daniel Sandler32e698b2013-04-18 10:51:35 -0400450
451 Slog.v(TAG, (enabled?"en":"dis") + "abling notifications for " + pkg);
452
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500453 mAppOps.setMode(AppOpsManager.OP_POST_NOTIFICATION, uid, pkg,
454 enabled ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
Daniel Sandler32e698b2013-04-18 10:51:35 -0400455
456 // Now, cancel any outstanding notifications that are part of a just-disabled app
457 if (ENABLE_BLOCKED_NOTIFICATIONS && !enabled) {
458 cancelAllNotificationsInt(pkg, 0, 0, true, UserHandle.getUserId(uid));
459 }
Daniel Sandler0da673f2012-04-11 12:33:16 -0400460 }
461
462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 private static String idDebugString(Context baseContext, String packageName, int id) {
464 Context c = null;
465
466 if (packageName != null) {
467 try {
468 c = baseContext.createPackageContext(packageName, 0);
469 } catch (NameNotFoundException e) {
470 c = baseContext;
471 }
472 } else {
473 c = baseContext;
474 }
475
476 String pkg;
477 String type;
478 String name;
479
480 Resources r = c.getResources();
481 try {
482 return r.getResourceName(id);
483 } catch (Resources.NotFoundException e) {
484 return "<name unknown>";
485 }
486 }
487
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700488 /**
489 * System-only API for getting a list of current (i.e. not cleared) notifications.
490 *
491 * Requires ACCESS_NOTIFICATIONS which is signature|system.
492 */
493 @Override
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500494 public StatusBarNotification[] getActiveNotifications(String callingPkg) {
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400495 // enforce() will ensure the calling uid has the correct permission
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500496 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_NOTIFICATIONS,
Daniel Sandler78d0d252013-02-12 08:14:52 -0500497 "NotificationManagerService.getActiveNotifications");
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500498
499 StatusBarNotification[] tmp = null;
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500500 int uid = Binder.getCallingUid();
501
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400502 // noteOp will check to make sure the callingPkg matches the uid
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500503 if (mAppOps.noteOpNoThrow(AppOpsManager.OP_ACCESS_NOTIFICATIONS, uid, callingPkg)
504 == AppOpsManager.MODE_ALLOWED) {
505 synchronized (mNotificationList) {
506 tmp = new StatusBarNotification[mNotificationList.size()];
507 final int N = mNotificationList.size();
508 for (int i=0; i<N; i++) {
509 tmp[i] = mNotificationList.get(i).sbn;
510 }
511 }
512 }
513 return tmp;
514 }
515
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700516 /**
517 * System-only API for getting a list of recent (cleared, no longer shown) notifications.
518 *
519 * Requires ACCESS_NOTIFICATIONS which is signature|system.
520 */
521 @Override
Daniel Sandler78d0d252013-02-12 08:14:52 -0500522 public StatusBarNotification[] getHistoricalNotifications(String callingPkg, int count) {
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400523 // enforce() will ensure the calling uid has the correct permission
Daniel Sandler78d0d252013-02-12 08:14:52 -0500524 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_NOTIFICATIONS,
525 "NotificationManagerService.getHistoricalNotifications");
526
527 StatusBarNotification[] tmp = null;
528 int uid = Binder.getCallingUid();
529
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400530 // noteOp will check to make sure the callingPkg matches the uid
Daniel Sandler78d0d252013-02-12 08:14:52 -0500531 if (mAppOps.noteOpNoThrow(AppOpsManager.OP_ACCESS_NOTIFICATIONS, uid, callingPkg)
532 == AppOpsManager.MODE_ALLOWED) {
533 synchronized (mArchive) {
534 tmp = mArchive.getArray(count);
535 }
536 }
537 return tmp;
538 }
539
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700540 /**
Chris Wrenae9bb572013-05-15 14:50:28 -0400541 * Remove notification access for any services that no longer exist.
542 */
543 void disableNonexistentListeners() {
544 int currentUser = ActivityManager.getCurrentUser();
545 String flatIn = Settings.Secure.getStringForUser(
546 mContext.getContentResolver(),
547 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
548 currentUser);
549 if (!TextUtils.isEmpty(flatIn)) {
550 if (DBG) Slog.v(TAG, "flat before: " + flatIn);
551 PackageManager pm = mContext.getPackageManager();
552 List<ResolveInfo> installedServices = pm.queryIntentServicesAsUser(
553 new Intent(NotificationListenerService.SERVICE_INTERFACE),
554 PackageManager.GET_SERVICES | PackageManager.GET_META_DATA,
555 currentUser);
556
557 Set<ComponentName> installed = new HashSet<ComponentName>();
558 for (int i = 0, count = installedServices.size(); i < count; i++) {
559 ResolveInfo resolveInfo = installedServices.get(i);
560 ServiceInfo info = resolveInfo.serviceInfo;
561
562 if (!android.Manifest.permission.BIND_NOTIFICATION_LISTENER_SERVICE.equals(
563 info.permission)) {
564 Slog.w(TAG, "Skipping notification listener service "
565 + info.packageName + "/" + info.name
566 + ": it does not require the permission "
567 + android.Manifest.permission.BIND_NOTIFICATION_LISTENER_SERVICE);
568 continue;
569 }
570 installed.add(new ComponentName(info.packageName, info.name));
571 }
572
573 String flatOut = "";
574 if (!installed.isEmpty()) {
575 String[] enabled = flatIn.split(ENABLED_NOTIFICATION_LISTENERS_SEPARATOR);
576 ArrayList<String> remaining = new ArrayList<String>(enabled.length);
577 for (int i = 0; i < enabled.length; i++) {
578 ComponentName enabledComponent = ComponentName.unflattenFromString(enabled[i]);
579 if (installed.contains(enabledComponent)) {
580 remaining.add(enabled[i]);
581 }
582 }
583 flatOut = TextUtils.join(ENABLED_NOTIFICATION_LISTENERS_SEPARATOR, remaining);
584 }
585 if (DBG) Slog.v(TAG, "flat after: " + flatOut);
586 if (!flatIn.equals(flatOut)) {
587 Settings.Secure.putStringForUser(mContext.getContentResolver(),
588 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
589 flatOut, currentUser);
590 }
591 }
592 }
593
594 /**
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700595 * Called whenever packages change, the user switches, or ENABLED_NOTIFICATION_LISTENERS
596 * is altered. (For example in response to USER_SWITCHED in our broadcast receiver)
597 */
598 void rebindListenerServices() {
John Spurlock3ec4e702013-05-16 13:42:38 -0400599 final int currentUser = ActivityManager.getCurrentUser();
600 String flat = Settings.Secure.getStringForUser(
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700601 mContext.getContentResolver(),
John Spurlock3ec4e702013-05-16 13:42:38 -0400602 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
603 currentUser);
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700604
605 NotificationListenerInfo[] toRemove = new NotificationListenerInfo[mListeners.size()];
606 final ArrayList<ComponentName> toAdd;
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700607
608 synchronized (mNotificationList) {
609 // unbind and remove all existing listeners
610 toRemove = mListeners.toArray(toRemove);
611
612 toAdd = new ArrayList<ComponentName>();
613 final HashSet<ComponentName> newEnabled = new HashSet<ComponentName>();
614 final HashSet<String> newPackages = new HashSet<String>();
615
616 // decode the list of components
617 if (flat != null) {
618 String[] components = flat.split(ENABLED_NOTIFICATION_LISTENERS_SEPARATOR);
619 for (int i=0; i<components.length; i++) {
620 final ComponentName component
621 = ComponentName.unflattenFromString(components[i]);
622 if (component != null) {
623 newEnabled.add(component);
624 toAdd.add(component);
625 newPackages.add(component.getPackageName());
626 }
627 }
628
629 mEnabledListenersForCurrentUser = newEnabled;
630 mEnabledListenerPackageNames = newPackages;
631 }
632 }
633
634 for (NotificationListenerInfo info : toRemove) {
635 final ComponentName component = info.component;
636 final int oldUser = info.userid;
637 Slog.v(TAG, "disabling notification listener for user " + oldUser + ": " + component);
638 unregisterListenerService(component, info.userid);
639 }
640
641 final int N = toAdd.size();
642 for (int i=0; i<N; i++) {
643 final ComponentName component = toAdd.get(i);
644 Slog.v(TAG, "enabling notification listener for user " + currentUser + ": "
645 + component);
646 registerListenerService(component, currentUser);
647 }
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400648 }
649
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700650 /**
651 * Register a listener binder directly with the notification manager.
652 *
653 * Only works with system callers. Apps should extend
654 * {@link android.service.notification.NotificationListenerService}.
655 */
Daniel Sandler09a247e2013-02-14 10:24:17 -0500656 @Override
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400657 public void registerListener(final INotificationListener listener,
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700658 final ComponentName component, final int userid) {
659 checkCallerIsSystem();
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400660
Daniel Sandler09a247e2013-02-14 10:24:17 -0500661 synchronized (mNotificationList) {
662 try {
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400663 NotificationListenerInfo info
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700664 = new NotificationListenerInfo(listener, component, userid, true);
Daniel Sandler09a247e2013-02-14 10:24:17 -0500665 listener.asBinder().linkToDeath(info, 0);
666 mListeners.add(info);
667 } catch (RemoteException e) {
668 // already dead
669 }
670 }
671 }
672
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700673 /**
674 * Version of registerListener that takes the name of a
675 * {@link android.service.notification.NotificationListenerService} to bind to.
676 *
677 * This is the mechanism by which third parties may subscribe to notifications.
678 */
679 private void registerListenerService(final ComponentName name, final int userid) {
680 checkCallerIsSystem();
681
682 if (DBG) Slog.v(TAG, "registerListenerService: " + name + " u=" + userid);
683
684 synchronized (mNotificationList) {
685 final String servicesBindingTag = name.toString() + "/" + userid;
686 if (mServicesBinding.contains(servicesBindingTag)) {
687 // stop registering this thing already! we're working on it
688 return;
689 }
690 mServicesBinding.add(servicesBindingTag);
691
692 final int N = mListeners.size();
693 for (int i=N-1; i>=0; i--) {
694 final NotificationListenerInfo info = mListeners.get(i);
695 if (name.equals(info.component)
696 && info.userid == userid) {
697 // cut old connections
698 if (DBG) Slog.v(TAG, " disconnecting old listener: " + info.listener);
699 mListeners.remove(i);
700 if (info.connection != null) {
701 mContext.unbindService(info.connection);
702 }
703 }
704 }
705
706 Intent intent = new Intent(NotificationListenerService.SERVICE_INTERFACE);
707 intent.setComponent(name);
708
709 intent.putExtra(Intent.EXTRA_CLIENT_LABEL,
710 com.android.internal.R.string.notification_listener_binding_label);
711 intent.putExtra(Intent.EXTRA_CLIENT_INTENT, PendingIntent.getActivity(
712 mContext, 0, new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS), 0));
713
714 try {
715 if (DBG) Slog.v(TAG, "binding: " + intent);
716 if (!mContext.bindServiceAsUser(intent,
717 new ServiceConnection() {
718 INotificationListener mListener;
719 @Override
720 public void onServiceConnected(ComponentName name, IBinder service) {
721 synchronized (mNotificationList) {
722 mServicesBinding.remove(servicesBindingTag);
723 try {
724 mListener = INotificationListener.Stub.asInterface(service);
725 NotificationListenerInfo info = new NotificationListenerInfo(
726 mListener, name, userid, this);
727 service.linkToDeath(info, 0);
728 mListeners.add(info);
729 } catch (RemoteException e) {
730 // already dead
731 }
732 }
733 }
734
735 @Override
736 public void onServiceDisconnected(ComponentName name) {
737 Slog.v(TAG, "notification listener connection lost: " + name);
738 }
739 },
740 Context.BIND_AUTO_CREATE,
741 new UserHandle(userid)))
742 {
743 mServicesBinding.remove(servicesBindingTag);
744 Slog.w(TAG, "Unable to bind listener service: " + intent);
745 return;
746 }
747 } catch (SecurityException ex) {
748 Slog.e(TAG, "Unable to bind listener service: " + intent, ex);
749 return;
750 }
751 }
752 }
753
754 /**
755 * Remove a listener binder directly
756 */
Daniel Sandler09a247e2013-02-14 10:24:17 -0500757 @Override
758 public void unregisterListener(INotificationListener listener, int userid) {
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400759 // no need to check permissions; if your listener binder is in the list,
760 // that's proof that you had permission to add it in the first place
761
Daniel Sandler09a247e2013-02-14 10:24:17 -0500762 synchronized (mNotificationList) {
763 final int N = mListeners.size();
764 for (int i=N-1; i>=0; i--) {
765 final NotificationListenerInfo info = mListeners.get(i);
766 if (info.listener == listener && info.userid == userid) {
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700767 mListeners.remove(i);
768 if (info.connection != null) {
769 mContext.unbindService(info.connection);
770 }
Daniel Sandler09a247e2013-02-14 10:24:17 -0500771 }
772 }
773 }
774 }
775
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700776 /**
777 * Remove a listener service for the given user by ComponentName
778 */
779 private void unregisterListenerService(ComponentName name, int userid) {
780 checkCallerIsSystem();
781
782 synchronized (mNotificationList) {
783 final int N = mListeners.size();
784 for (int i=N-1; i>=0; i--) {
785 final NotificationListenerInfo info = mListeners.get(i);
786 if (name.equals(info.component)
787 && info.userid == userid) {
788 mListeners.remove(i);
789 if (info.connection != null) {
Daniel Sandlerc1b49bd2013-05-07 13:53:47 -0400790 try {
791 mContext.unbindService(info.connection);
792 } catch (IllegalArgumentException ex) {
793 // something happened to the service: we think we have a connection
794 // but it's bogus.
795 Slog.e(TAG, "Listener " + name + " could not be unbound: " + ex);
796 }
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700797 }
798 }
799 }
800 }
801 }
802
803 /**
804 * asynchronously notify all listeners about a new notification
805 */
Daniel Sandler09a247e2013-02-14 10:24:17 -0500806 private void notifyPostedLocked(NotificationRecord n) {
Daniel Sandler1a497d32013-04-18 14:52:45 -0400807 // make a copy in case changes are made to the underlying Notification object
808 final StatusBarNotification sbn = n.sbn.clone();
Daniel Sandler09a247e2013-02-14 10:24:17 -0500809 for (final NotificationListenerInfo info : mListeners) {
810 mHandler.post(new Runnable() {
811 @Override
812 public void run() {
813 info.notifyPostedIfUserMatch(sbn);
814 }});
815 }
816 }
817
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700818 /**
819 * asynchronously notify all listeners about a removed notification
820 */
Daniel Sandler09a247e2013-02-14 10:24:17 -0500821 private void notifyRemovedLocked(NotificationRecord n) {
Daniel Sandler1a497d32013-04-18 14:52:45 -0400822 // make a copy in case changes are made to the underlying Notification object
823 // NOTE: this copy is lightweight: it doesn't include heavyweight parts of the notification
824 final StatusBarNotification sbn_light = n.sbn.cloneLight();
825
Daniel Sandler09a247e2013-02-14 10:24:17 -0500826 for (final NotificationListenerInfo info : mListeners) {
827 mHandler.post(new Runnable() {
828 @Override
829 public void run() {
Daniel Sandler1a497d32013-04-18 14:52:45 -0400830 info.notifyRemovedIfUserMatch(sbn_light);
Daniel Sandler09a247e2013-02-14 10:24:17 -0500831 }});
832 }
833 }
834
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700835 // -- APIs to support listeners clicking/clearing notifications --
836
837 private NotificationListenerInfo checkListenerToken(INotificationListener listener) {
838 final IBinder token = listener.asBinder();
839 final int N = mListeners.size();
840 for (int i=0; i<N; i++) {
841 final NotificationListenerInfo info = mListeners.get(i);
842 if (info.listener.asBinder() == token) return info;
843 }
844 throw new SecurityException("Disallowed call from unknown listener: " + listener);
845 }
846
847 /**
848 * Allow an INotificationListener to simulate a "clear all" operation.
849 *
850 * {@see com.android.server.StatusBarManagerService.NotificationCallbacks#onClearAllNotifications}
851 *
852 * @param token The binder for the listener, to check that the caller is allowed
853 */
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400854 public void cancelAllNotificationsFromListener(INotificationListener token) {
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700855 NotificationListenerInfo info = checkListenerToken(token);
856 long identity = Binder.clearCallingIdentity();
857 try {
858 cancelAll(info.userid);
859 } finally {
860 Binder.restoreCallingIdentity(identity);
861 }
862 }
863
864 /**
865 * Allow an INotificationListener to simulate clearing (dismissing) a single notification.
866 *
867 * {@see com.android.server.StatusBarManagerService.NotificationCallbacks#onNotificationClear}
868 *
869 * @param token The binder for the listener, to check that the caller is allowed
870 */
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400871 public void cancelNotificationFromListener(INotificationListener token, String pkg, String tag, int id) {
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700872 NotificationListenerInfo info = checkListenerToken(token);
873 long identity = Binder.clearCallingIdentity();
874 try {
875 cancelNotification(pkg, tag, id, 0,
876 Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE,
877 true,
878 info.userid);
879 } finally {
880 Binder.restoreCallingIdentity(identity);
881 }
882 }
883
Daniel Sandler25cf8ce2013-04-24 15:34:57 -0400884 /**
885 * Allow an INotificationListener to request the list of outstanding notifications seen by
886 * the current user. Useful when starting up, after which point the listener callbacks should
887 * be used.
888 *
889 * @param token The binder for the listener, to check that the caller is allowed
890 */
891 public StatusBarNotification[] getActiveNotificationsFromListener(INotificationListener token) {
892 NotificationListenerInfo info = checkListenerToken(token);
893
894 StatusBarNotification[] result = new StatusBarNotification[0];
895 ArrayList<StatusBarNotification> list = new ArrayList<StatusBarNotification>();
896 synchronized (mNotificationList) {
897 final int N = mNotificationList.size();
898 for (int i=0; i<N; i++) {
899 StatusBarNotification sbn = mNotificationList.get(i).sbn;
900 if (info.enabledAndUserMatches(sbn)) {
901 list.add(sbn);
902 }
903 }
904 }
905 return list.toArray(result);
906 }
907
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700908 // -- end of listener APIs --
909
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500910 public static final class NotificationRecord
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 {
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500912 final StatusBarNotification sbn;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 IBinder statusBarKey;
914
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500915 NotificationRecord(StatusBarNotification sbn)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 {
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500917 this.sbn = sbn;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 }
Fred Quintana6ecaff12009-09-25 14:23:13 -0700919
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400920 public Notification getNotification() { return sbn.getNotification(); }
921 public int getFlags() { return sbn.getNotification().flags; }
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500922 public int getUserId() { return sbn.getUserId(); }
923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 void dump(PrintWriter pw, String prefix, Context baseContext) {
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400925 final Notification notification = sbn.getNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 pw.println(prefix + this);
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400927 pw.println(prefix + " uid=" + sbn.getUid() + " userId=" + sbn.getUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 pw.println(prefix + " icon=0x" + Integer.toHexString(notification.icon)
Daniel Sandler4f91efd2013-04-25 16:38:41 -0400929 + " / " + idDebugString(baseContext, sbn.getPackageName(), notification.icon));
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400930 pw.println(prefix + " pri=" + notification.priority + " score=" + sbn.getScore());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 pw.println(prefix + " contentIntent=" + notification.contentIntent);
932 pw.println(prefix + " deleteIntent=" + notification.deleteIntent);
933 pw.println(prefix + " tickerText=" + notification.tickerText);
934 pw.println(prefix + " contentView=" + notification.contentView);
Daniel Sandlerf45564e2013-04-15 15:05:08 -0400935 pw.println(prefix + String.format(" defaults=0x%08x flags=0x%08x",
936 notification.defaults, notification.flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 pw.println(prefix + " sound=" + notification.sound);
938 pw.println(prefix + " vibrate=" + Arrays.toString(notification.vibrate));
Daniel Sandlerf45564e2013-04-15 15:05:08 -0400939 pw.println(prefix + String.format(" led=0x%08x onMs=%d offMs=%d",
940 notification.ledARGB, notification.ledOnMS, notification.ledOffMS));
941 if (notification.actions != null && notification.actions.length > 0) {
942 pw.println(prefix + " actions={");
943 final int N = notification.actions.length;
944 for (int i=0; i<N; i++) {
945 final Notification.Action action = notification.actions[i];
946 pw.println(String.format("%s [%d] \"%s\" -> %s",
947 prefix,
948 i,
949 action.title,
950 action.actionIntent.toString()
951 ));
952 }
953 pw.println(prefix + " }");
954 }
955 if (notification.extras != null && notification.extras.size() > 0) {
956 pw.println(prefix + " extras={");
957 for (String key : notification.extras.keySet()) {
958 pw.print(prefix + " " + key + "=");
959 Object val = notification.extras.get(key);
960 if (val == null) {
961 pw.println("null");
962 } else {
963 pw.print(val.toString());
964 if (val instanceof Bitmap) {
965 pw.print(String.format(" (%dx%d)",
966 ((Bitmap) val).getWidth(),
967 ((Bitmap) val).getHeight()));
968 } else if (val.getClass().isArray()) {
969 pw.println(" {");
970 final int N = Array.getLength(val);
971 for (int i=0; i<N; i++) {
972 if (i > 0) pw.println(",");
973 pw.print(prefix + " " + Array.get(val, i));
974 }
975 pw.print("\n" + prefix + " }");
976 }
977 pw.println();
978 }
979 }
980 pw.println(prefix + " }");
981 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 @Override
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500985 public final String toString() {
986 return String.format(
987 "NotificationRecord(0x%08x: pkg=%s user=%s id=%d tag=%s score=%d: %s)",
988 System.identityHashCode(this),
Daniel Sandler4f91efd2013-04-25 16:38:41 -0400989 this.sbn.getPackageName(), this.sbn.getUser(), this.sbn.getId(), this.sbn.getTag(),
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400990 this.sbn.getScore(), this.sbn.getNotification());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 }
992 }
993
994 private static final class ToastRecord
995 {
996 final int pid;
997 final String pkg;
998 final ITransientNotification callback;
999 int duration;
1000
1001 ToastRecord(int pid, String pkg, ITransientNotification callback, int duration)
1002 {
1003 this.pid = pid;
1004 this.pkg = pkg;
1005 this.callback = callback;
1006 this.duration = duration;
1007 }
1008
1009 void update(int duration) {
1010 this.duration = duration;
1011 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001012
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 void dump(PrintWriter pw, String prefix) {
1014 pw.println(prefix + this);
1015 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 @Override
1018 public final String toString()
1019 {
1020 return "ToastRecord{"
1021 + Integer.toHexString(System.identityHashCode(this))
1022 + " pkg=" + pkg
1023 + " callback=" + callback
1024 + " duration=" + duration;
1025 }
1026 }
1027
Joe Onorato089de882010-04-12 08:18:45 -07001028 private StatusBarManagerService.NotificationCallbacks mNotificationCallbacks
1029 = new StatusBarManagerService.NotificationCallbacks() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030
1031 public void onSetDisabled(int status) {
1032 synchronized (mNotificationList) {
1033 mDisabledNotifications = status;
1034 if ((mDisabledNotifications & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) {
1035 // cancel whatever's going on
1036 long identity = Binder.clearCallingIdentity();
1037 try {
Jeff Sharkey098d5802012-04-26 17:30:34 -07001038 final IRingtonePlayer player = mAudioService.getRingtonePlayer();
1039 if (player != null) {
1040 player.stopAsync();
1041 }
1042 } catch (RemoteException e) {
1043 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 Binder.restoreCallingIdentity(identity);
1045 }
1046
1047 identity = Binder.clearCallingIdentity();
1048 try {
1049 mVibrator.cancel();
Jeff Sharkey098d5802012-04-26 17:30:34 -07001050 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 Binder.restoreCallingIdentity(identity);
1052 }
1053 }
1054 }
1055 }
1056
1057 public void onClearAll() {
Dianne Hackborn41203752012-08-31 14:05:51 -07001058 // XXX to be totally correct, the caller should tell us which user
1059 // this is for.
1060 cancelAll(ActivityManager.getCurrentUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 }
1062
Fred Quintana6ecaff12009-09-25 14:23:13 -07001063 public void onNotificationClick(String pkg, String tag, int id) {
Dianne Hackborn41203752012-08-31 14:05:51 -07001064 // XXX to be totally correct, the caller should tell us which user
1065 // this is for.
Fred Quintana6ecaff12009-09-25 14:23:13 -07001066 cancelNotification(pkg, tag, id, Notification.FLAG_AUTO_CANCEL,
Dianne Hackborn41203752012-08-31 14:05:51 -07001067 Notification.FLAG_FOREGROUND_SERVICE, false,
1068 ActivityManager.getCurrentUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 }
1070
Daniel Sandler0f0b11c2010-08-04 15:54:58 -04001071 public void onNotificationClear(String pkg, String tag, int id) {
Dianne Hackborn41203752012-08-31 14:05:51 -07001072 // XXX to be totally correct, the caller should tell us which user
1073 // this is for.
Joe Onorato46439ce2010-11-19 13:56:21 -08001074 cancelNotification(pkg, tag, id, 0,
1075 Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE,
Dianne Hackborn41203752012-08-31 14:05:51 -07001076 true, ActivityManager.getCurrentUser());
Daniel Sandler0f0b11c2010-08-04 15:54:58 -04001077 }
1078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 public void onPanelRevealed() {
1080 synchronized (mNotificationList) {
1081 // sound
1082 mSoundNotification = null;
Jeff Sharkey098d5802012-04-26 17:30:34 -07001083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 long identity = Binder.clearCallingIdentity();
1085 try {
Jeff Sharkey098d5802012-04-26 17:30:34 -07001086 final IRingtonePlayer player = mAudioService.getRingtonePlayer();
1087 if (player != null) {
1088 player.stopAsync();
1089 }
1090 } catch (RemoteException e) {
1091 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 Binder.restoreCallingIdentity(identity);
1093 }
1094
1095 // vibrate
1096 mVibrateNotification = null;
1097 identity = Binder.clearCallingIdentity();
1098 try {
1099 mVibrator.cancel();
Jeff Sharkey098d5802012-04-26 17:30:34 -07001100 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 Binder.restoreCallingIdentity(identity);
1102 }
1103
1104 // light
1105 mLights.clear();
1106 mLedNotification = null;
1107 updateLightsLocked();
1108 }
1109 }
Joe Onorato005847b2010-06-04 16:08:02 -04001110
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001111 public void onNotificationError(String pkg, String tag, int id,
1112 int uid, int initialPid, String message) {
Daniel Sandlerd0a2f862010-08-03 15:29:31 -04001113 Slog.d(TAG, "onNotification error pkg=" + pkg + " tag=" + tag + " id=" + id
1114 + "; will crashApplication(uid=" + uid + ", pid=" + initialPid + ")");
Dianne Hackborn41203752012-08-31 14:05:51 -07001115 // XXX to be totally correct, the caller should tell us which user
1116 // this is for.
1117 cancelNotification(pkg, tag, id, 0, 0, false, UserHandle.getUserId(uid));
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001118 long ident = Binder.clearCallingIdentity();
1119 try {
1120 ActivityManagerNative.getDefault().crashApplication(uid, initialPid, pkg,
1121 "Bad notification posted from package " + pkg
1122 + ": " + message);
1123 } catch (RemoteException e) {
1124 }
1125 Binder.restoreCallingIdentity(ident);
Joe Onorato005847b2010-06-04 16:08:02 -04001126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001127 };
1128
1129 private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
1130 @Override
1131 public void onReceive(Context context, Intent intent) {
1132 String action = intent.getAction();
1133
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001134 boolean queryRestart = false;
Chris Wrenae9bb572013-05-15 14:50:28 -04001135 boolean queryRemove = false;
Daniel Sandler26ece572012-06-01 15:38:46 -04001136 boolean packageChanged = false;
John Spurlock79f78922013-05-16 09:10:05 -04001137 boolean cancelNotifications = true;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001138
Chris Wren3da73022013-05-10 14:41:21 -04001139 if (action.equals(Intent.ACTION_PACKAGE_ADDED)
Chris Wrenae9bb572013-05-15 14:50:28 -04001140 || (queryRemove=action.equals(Intent.ACTION_PACKAGE_REMOVED))
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001141 || action.equals(Intent.ACTION_PACKAGE_RESTARTED)
Daniel Sandler26ece572012-06-01 15:38:46 -04001142 || (packageChanged=action.equals(Intent.ACTION_PACKAGE_CHANGED))
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001143 || (queryRestart=action.equals(Intent.ACTION_QUERY_PACKAGE_RESTART))
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001144 || action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001145 String pkgList[] = null;
Chris Wrenae9bb572013-05-15 14:50:28 -04001146 boolean queryReplace = queryRemove &&
1147 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
1148 if (DBG) Slog.i(TAG, "queryReplace=" + queryReplace);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001149 if (action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001150 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001151 } else if (queryRestart) {
1152 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001153 } else {
1154 Uri uri = intent.getData();
1155 if (uri == null) {
1156 return;
1157 }
1158 String pkgName = uri.getSchemeSpecificPart();
1159 if (pkgName == null) {
1160 return;
1161 }
Daniel Sandler26ece572012-06-01 15:38:46 -04001162 if (packageChanged) {
1163 // We cancel notifications for packages which have just been disabled
1164 final int enabled = mContext.getPackageManager()
1165 .getApplicationEnabledSetting(pkgName);
1166 if (enabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
1167 || enabled == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
John Spurlock79f78922013-05-16 09:10:05 -04001168 cancelNotifications = false;
Daniel Sandler26ece572012-06-01 15:38:46 -04001169 }
1170 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001171 pkgList = new String[]{pkgName};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 }
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001173
1174 boolean anyListenersInvolved = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001175 if (pkgList != null && (pkgList.length > 0)) {
1176 for (String pkgName : pkgList) {
John Spurlock79f78922013-05-16 09:10:05 -04001177 if (cancelNotifications) {
1178 cancelAllNotificationsInt(pkgName, 0, 0, !queryRestart,
1179 UserHandle.USER_ALL);
1180 }
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001181 if (mEnabledListenerPackageNames.contains(pkgName)) {
1182 anyListenersInvolved = true;
1183 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 }
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001186
1187 if (anyListenersInvolved) {
Chris Wrenae9bb572013-05-15 14:50:28 -04001188 // if we're not replacing a package, clean up orphaned bits
1189 if (!queryReplace) {
1190 disableNonexistentListeners();
1191 }
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001192 // make sure we're still bound to any of our
1193 // listeners who may have just upgraded
1194 rebindListenerServices();
1195 }
Mike Lockwood63b5ad92011-08-30 09:55:30 -04001196 } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
1197 // Keep track of screen on/off state, but do not turn off the notification light
1198 // until user passes through the lock screen or views the notification.
1199 mScreenOn = true;
1200 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
1201 mScreenOn = false;
Daniel Sandlere96ffb12010-03-11 13:38:06 -05001202 } else if (action.equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
Mike Lockwood63b5ad92011-08-30 09:55:30 -04001203 mInCall = (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
1204 TelephonyManager.EXTRA_STATE_OFFHOOK));
Daniel Sandlere96ffb12010-03-11 13:38:06 -05001205 updateNotificationPulse();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001206 } else if (action.equals(Intent.ACTION_USER_STOPPED)) {
1207 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
1208 if (userHandle >= 0) {
Dianne Hackborn41203752012-08-31 14:05:51 -07001209 cancelAllNotificationsInt(null, 0, 0, true, userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001210 }
Mike Lockwood63b5ad92011-08-30 09:55:30 -04001211 } else if (action.equals(Intent.ACTION_USER_PRESENT)) {
1212 // turn off LED when user passes through lock screen
1213 mNotificationLight.turnOff();
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001214 } else if (action.equals(Intent.ACTION_USER_SWITCHED)) {
1215 // reload per-user settings
1216 mSettingsObserver.update(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217 }
1218 }
1219 };
1220
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001221 class SettingsObserver extends ContentObserver {
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001222 private final Uri NOTIFICATION_LIGHT_PULSE_URI
1223 = Settings.System.getUriFor(Settings.System.NOTIFICATION_LIGHT_PULSE);
1224
1225 private final Uri ENABLED_NOTIFICATION_LISTENERS_URI
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001226 = Settings.Secure.getUriFor(Settings.Secure.ENABLED_NOTIFICATION_LISTENERS);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001227
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001228 SettingsObserver(Handler handler) {
1229 super(handler);
1230 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001231
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001232 void observe() {
1233 ContentResolver resolver = mContext.getContentResolver();
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001234 resolver.registerContentObserver(NOTIFICATION_LIGHT_PULSE_URI,
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001235 false, this, UserHandle.USER_ALL);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001236 resolver.registerContentObserver(ENABLED_NOTIFICATION_LISTENERS_URI,
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001237 false, this, UserHandle.USER_ALL);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001238 update(null);
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001239 }
1240
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001241 @Override public void onChange(boolean selfChange, Uri uri) {
1242 update(uri);
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001243 }
1244
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001245 public void update(Uri uri) {
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001246 ContentResolver resolver = mContext.getContentResolver();
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001247 if (uri == null || NOTIFICATION_LIGHT_PULSE_URI.equals(uri)) {
1248 boolean pulseEnabled = Settings.System.getInt(resolver,
1249 Settings.System.NOTIFICATION_LIGHT_PULSE, 0) != 0;
1250 if (mNotificationPulseEnabled != pulseEnabled) {
1251 mNotificationPulseEnabled = pulseEnabled;
1252 updateNotificationPulse();
1253 }
1254 }
1255 if (uri == null || ENABLED_NOTIFICATION_LISTENERS_URI.equals(uri)) {
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001256 rebindListenerServices();
Mike Lockwoodc22404a2009-12-02 11:15:02 -05001257 }
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001258 }
1259 }
Mike Lockwoodc22404a2009-12-02 11:15:02 -05001260
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001261 private SettingsObserver mSettingsObserver;
1262
Daniel Sandleredbb3802012-11-13 20:49:47 -08001263 static long[] getLongArray(Resources r, int resid, int maxlen, long[] def) {
1264 int[] ar = r.getIntArray(resid);
1265 if (ar == null) {
1266 return def;
1267 }
1268 final int len = ar.length > maxlen ? maxlen : ar.length;
1269 long[] out = new long[len];
1270 for (int i=0; i<len; i++) {
1271 out[i] = ar[i];
1272 }
1273 return out;
1274 }
1275
Joe Onorato089de882010-04-12 08:18:45 -07001276 NotificationManagerService(Context context, StatusBarManagerService statusBar,
Mike Lockwood3a322132009-11-24 00:30:52 -05001277 LightsService lights)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 {
1279 super();
1280 mContext = context;
Jeff Brownc2346132012-04-13 01:55:38 -07001281 mVibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 mAm = ActivityManagerNative.getDefault();
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001283 mUserManager = (UserManager)context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 mToastQueue = new ArrayList<ToastRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 mHandler = new WorkerHandler();
San Mehat3ee13172010-02-04 20:54:43 -08001286
Daniel Sandler4a900acd2013-01-30 14:04:10 -05001287 mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
1288
1289 importOldBlockDb();
Daniel Sandler0da673f2012-04-11 12:33:16 -04001290
Joe Onorato089de882010-04-12 08:18:45 -07001291 mStatusBar = statusBar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 statusBar.setNotificationCallbacks(mNotificationCallbacks);
1293
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001294 mNotificationLight = lights.getLight(LightsService.LIGHT_ID_NOTIFICATIONS);
1295 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
1296
Mike Lockwood670f9322010-01-20 12:13:36 -05001297 Resources resources = mContext.getResources();
1298 mDefaultNotificationColor = resources.getColor(
1299 com.android.internal.R.color.config_defaultNotificationColor);
1300 mDefaultNotificationLedOn = resources.getInteger(
1301 com.android.internal.R.integer.config_defaultNotificationLedOn);
1302 mDefaultNotificationLedOff = resources.getInteger(
1303 com.android.internal.R.integer.config_defaultNotificationLedOff);
1304
Daniel Sandleredbb3802012-11-13 20:49:47 -08001305 mDefaultVibrationPattern = getLongArray(resources,
1306 com.android.internal.R.array.config_defaultNotificationVibePattern,
1307 VIBRATE_PATTERN_MAXLEN,
1308 DEFAULT_VIBRATE_PATTERN);
1309
1310 mFallbackVibrationPattern = getLongArray(resources,
1311 com.android.internal.R.array.config_notificationFallbackVibePattern,
1312 VIBRATE_PATTERN_MAXLEN,
1313 DEFAULT_VIBRATE_PATTERN);
1314
Joe Onorato39f5b6a2009-07-23 12:29:19 -04001315 // Don't start allowing notifications until the setup wizard has run once.
1316 // After that, including subsequent boots, init with notifications turned on.
1317 // This works on the first boot because the setup wizard will toggle this
1318 // flag at least once and we'll go back to 0 after that.
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001319 if (0 == Settings.Global.getInt(mContext.getContentResolver(),
1320 Settings.Global.DEVICE_PROVISIONED, 0)) {
Joe Onorato39f5b6a2009-07-23 12:29:19 -04001321 mDisabledNotifications = StatusBarManager.DISABLE_NOTIFICATION_ALERTS;
1322 }
1323
Mike Lockwood35e16bf2010-11-30 19:53:36 -05001324 // register for various Intents
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 IntentFilter filter = new IntentFilter();
Mike Lockwoodc22404a2009-12-02 11:15:02 -05001326 filter.addAction(Intent.ACTION_SCREEN_ON);
1327 filter.addAction(Intent.ACTION_SCREEN_OFF);
Daniel Sandlere96ffb12010-03-11 13:38:06 -05001328 filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
Mike Lockwood63b5ad92011-08-30 09:55:30 -04001329 filter.addAction(Intent.ACTION_USER_PRESENT);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001330 filter.addAction(Intent.ACTION_USER_STOPPED);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001331 filter.addAction(Intent.ACTION_USER_SWITCHED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 mContext.registerReceiver(mIntentReceiver, filter);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001333 IntentFilter pkgFilter = new IntentFilter();
Chris Wren3da73022013-05-10 14:41:21 -04001334 pkgFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001335 pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
Daniel Sandleraac0eb02011-08-06 22:51:56 -04001336 pkgFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001337 pkgFilter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
1338 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
1339 pkgFilter.addDataScheme("package");
1340 mContext.registerReceiver(mIntentReceiver, pkgFilter);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001341 IntentFilter sdFilter = new IntentFilter(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001342 mContext.registerReceiver(mIntentReceiver, sdFilter);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001343
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001344 mSettingsObserver = new SettingsObserver(mHandler);
1345 mSettingsObserver.observe();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 }
1347
Daniel Sandler4a900acd2013-01-30 14:04:10 -05001348 /**
1349 * Read the old XML-based app block database and import those blockages into the AppOps system.
1350 */
1351 private void importOldBlockDb() {
1352 loadBlockDb();
1353
1354 PackageManager pm = mContext.getPackageManager();
1355 for (String pkg : mBlockedPackages) {
1356 PackageInfo info = null;
1357 try {
1358 info = pm.getPackageInfo(pkg, 0);
1359 setNotificationsEnabledForPackage(pkg, info.applicationInfo.uid, false);
1360 } catch (NameNotFoundException e) {
1361 // forget you
1362 }
1363 }
1364 mBlockedPackages.clear();
1365 if (mPolicyFile != null) {
1366 mPolicyFile.delete();
1367 }
1368 }
1369
Joe Onorato30275482009-07-08 17:09:14 -07001370 void systemReady() {
Jeff Sharkey098d5802012-04-26 17:30:34 -07001371 mAudioService = IAudioService.Stub.asInterface(
1372 ServiceManager.getService(Context.AUDIO_SERVICE));
1373
Joe Onorato30275482009-07-08 17:09:14 -07001374 // no beeping until we're basically done booting
1375 mSystemReady = true;
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001376
1377 // make sure our listener services are properly bound
1378 rebindListenerServices();
Joe Onorato30275482009-07-08 17:09:14 -07001379 }
1380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 // Toasts
1382 // ============================================================================
1383 public void enqueueToast(String pkg, ITransientNotification callback, int duration)
1384 {
Daniel Sandlera7035902010-03-30 15:45:31 -04001385 if (DBG) Slog.i(TAG, "enqueueToast pkg=" + pkg + " callback=" + callback + " duration=" + duration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386
1387 if (pkg == null || callback == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001388 Slog.e(TAG, "Not doing toast. pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 return ;
1390 }
1391
Daniel Sandler0da673f2012-04-11 12:33:16 -04001392 final boolean isSystemToast = ("android".equals(pkg));
1393
Daniel Sandler4a900acd2013-01-30 14:04:10 -05001394 if (ENABLE_BLOCKED_TOASTS && !noteNotificationOp(pkg, Binder.getCallingUid())) {
1395 if (!isSystemToast) {
1396 Slog.e(TAG, "Suppressing toast from package " + pkg + " by user request.");
1397 return;
1398 }
Daniel Sandler0da673f2012-04-11 12:33:16 -04001399 }
1400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 synchronized (mToastQueue) {
1402 int callingPid = Binder.getCallingPid();
1403 long callingId = Binder.clearCallingIdentity();
1404 try {
1405 ToastRecord record;
1406 int index = indexOfToastLocked(pkg, callback);
1407 // If it's already in the queue, we update it in place, we don't
1408 // move it to the end of the queue.
1409 if (index >= 0) {
1410 record = mToastQueue.get(index);
1411 record.update(duration);
1412 } else {
Vairavan Srinivasanf9eb06c2011-01-21 18:08:36 -08001413 // Limit the number of toasts that any given package except the android
1414 // package can enqueue. Prevents DOS attacks and deals with leaks.
Daniel Sandler0da673f2012-04-11 12:33:16 -04001415 if (!isSystemToast) {
Vairavan Srinivasanf9eb06c2011-01-21 18:08:36 -08001416 int count = 0;
1417 final int N = mToastQueue.size();
1418 for (int i=0; i<N; i++) {
1419 final ToastRecord r = mToastQueue.get(i);
1420 if (r.pkg.equals(pkg)) {
1421 count++;
1422 if (count >= MAX_PACKAGE_NOTIFICATIONS) {
1423 Slog.e(TAG, "Package has already posted " + count
1424 + " toasts. Not showing more. Package=" + pkg);
1425 return;
1426 }
1427 }
1428 }
1429 }
1430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 record = new ToastRecord(callingPid, pkg, callback, duration);
1432 mToastQueue.add(record);
1433 index = mToastQueue.size() - 1;
1434 keepProcessAliveLocked(callingPid);
1435 }
1436 // If it's at index 0, it's the current toast. It doesn't matter if it's
1437 // new or just been updated. Call back and tell it to show itself.
1438 // If the callback fails, this will remove it from the list, so don't
1439 // assume that it's valid after this.
1440 if (index == 0) {
1441 showNextToastLocked();
1442 }
1443 } finally {
1444 Binder.restoreCallingIdentity(callingId);
1445 }
1446 }
1447 }
1448
1449 public void cancelToast(String pkg, ITransientNotification callback) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001450 Slog.i(TAG, "cancelToast pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451
1452 if (pkg == null || callback == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001453 Slog.e(TAG, "Not cancelling notification. pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 return ;
1455 }
1456
1457 synchronized (mToastQueue) {
1458 long callingId = Binder.clearCallingIdentity();
1459 try {
1460 int index = indexOfToastLocked(pkg, callback);
1461 if (index >= 0) {
1462 cancelToastLocked(index);
1463 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001464 Slog.w(TAG, "Toast already cancelled. pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 }
1466 } finally {
1467 Binder.restoreCallingIdentity(callingId);
1468 }
1469 }
1470 }
1471
1472 private void showNextToastLocked() {
1473 ToastRecord record = mToastQueue.get(0);
1474 while (record != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001475 if (DBG) Slog.d(TAG, "Show pkg=" + record.pkg + " callback=" + record.callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 try {
1477 record.callback.show();
1478 scheduleTimeoutLocked(record, false);
1479 return;
1480 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001481 Slog.w(TAG, "Object died trying to show notification " + record.callback
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 + " in package " + record.pkg);
1483 // remove it from the list and let the process die
1484 int index = mToastQueue.indexOf(record);
1485 if (index >= 0) {
1486 mToastQueue.remove(index);
1487 }
1488 keepProcessAliveLocked(record.pid);
1489 if (mToastQueue.size() > 0) {
1490 record = mToastQueue.get(0);
1491 } else {
1492 record = null;
1493 }
1494 }
1495 }
1496 }
1497
1498 private void cancelToastLocked(int index) {
1499 ToastRecord record = mToastQueue.get(index);
1500 try {
1501 record.callback.hide();
1502 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001503 Slog.w(TAG, "Object died trying to hide notification " + record.callback
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001504 + " in package " + record.pkg);
1505 // don't worry about this, we're about to remove it from
1506 // the list anyway
1507 }
1508 mToastQueue.remove(index);
1509 keepProcessAliveLocked(record.pid);
1510 if (mToastQueue.size() > 0) {
1511 // Show the next one. If the callback fails, this will remove
1512 // it from the list, so don't assume that the list hasn't changed
1513 // after this point.
1514 showNextToastLocked();
1515 }
1516 }
1517
1518 private void scheduleTimeoutLocked(ToastRecord r, boolean immediate)
1519 {
1520 Message m = Message.obtain(mHandler, MESSAGE_TIMEOUT, r);
1521 long delay = immediate ? 0 : (r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY);
1522 mHandler.removeCallbacksAndMessages(r);
1523 mHandler.sendMessageDelayed(m, delay);
1524 }
1525
1526 private void handleTimeout(ToastRecord record)
1527 {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001528 if (DBG) Slog.d(TAG, "Timeout pkg=" + record.pkg + " callback=" + record.callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 synchronized (mToastQueue) {
1530 int index = indexOfToastLocked(record.pkg, record.callback);
1531 if (index >= 0) {
1532 cancelToastLocked(index);
1533 }
1534 }
1535 }
1536
1537 // lock on mToastQueue
1538 private int indexOfToastLocked(String pkg, ITransientNotification callback)
1539 {
1540 IBinder cbak = callback.asBinder();
1541 ArrayList<ToastRecord> list = mToastQueue;
1542 int len = list.size();
1543 for (int i=0; i<len; i++) {
1544 ToastRecord r = list.get(i);
1545 if (r.pkg.equals(pkg) && r.callback.asBinder() == cbak) {
1546 return i;
1547 }
1548 }
1549 return -1;
1550 }
1551
1552 // lock on mToastQueue
1553 private void keepProcessAliveLocked(int pid)
1554 {
1555 int toastCount = 0; // toasts from this pid
1556 ArrayList<ToastRecord> list = mToastQueue;
1557 int N = list.size();
1558 for (int i=0; i<N; i++) {
1559 ToastRecord r = list.get(i);
1560 if (r.pid == pid) {
1561 toastCount++;
1562 }
1563 }
1564 try {
1565 mAm.setProcessForeground(mForegroundToken, pid, toastCount > 0);
1566 } catch (RemoteException e) {
1567 // Shouldn't happen.
1568 }
1569 }
1570
1571 private final class WorkerHandler extends Handler
1572 {
1573 @Override
1574 public void handleMessage(Message msg)
1575 {
1576 switch (msg.what)
1577 {
1578 case MESSAGE_TIMEOUT:
1579 handleTimeout((ToastRecord)msg.obj);
1580 break;
1581 }
1582 }
1583 }
1584
1585
1586 // Notifications
1587 // ============================================================================
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001588 public void enqueueNotificationWithTag(String pkg, String basePkg, String tag, int id,
1589 Notification notification, int[] idOut, int userId)
Fred Quintana6ecaff12009-09-25 14:23:13 -07001590 {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001591 enqueueNotificationInternal(pkg, basePkg, Binder.getCallingUid(), Binder.getCallingPid(),
Dianne Hackborn41203752012-08-31 14:05:51 -07001592 tag, id, notification, idOut, userId);
Daniel Sandlerd0a2f862010-08-03 15:29:31 -04001593 }
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001594
1595 private final static int clamp(int x, int low, int high) {
1596 return (x < low) ? low : ((x > high) ? high : x);
Daniel Sandlere40451a2011-02-03 14:51:35 -05001597 }
1598
Daniel Sandlerd0a2f862010-08-03 15:29:31 -04001599 // Not exposed via Binder; for system use only (otherwise malicious apps could spoof the
1600 // uid/pid of another application)
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001601 public void enqueueNotificationInternal(String pkg, String basePkg, int callingUid,
1602 int callingPid, String tag, int id, Notification notification, int[] idOut, int userId)
Daniel Sandlerd0a2f862010-08-03 15:29:31 -04001603 {
Daniel Sandler0da673f2012-04-11 12:33:16 -04001604 if (DBG) {
1605 Slog.v(TAG, "enqueueNotificationInternal: pkg=" + pkg + " id=" + id + " notification=" + notification);
1606 }
1607 checkCallerIsSystemOrSameApp(pkg);
1608 final boolean isSystemNotification = ("android".equals(pkg));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001609
Dianne Hackborn41203752012-08-31 14:05:51 -07001610 userId = ActivityManager.handleIncomingUser(callingPid,
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07001611 callingUid, userId, true, false, "enqueueNotification", pkg);
Jeff Sharkey65c4a2b2012-09-25 17:22:27 -07001612 final UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001613
Joe Onoratobd73d012010-06-04 11:44:54 -07001614 // Limit the number of notifications that any given package except the android
1615 // package can enqueue. Prevents DOS attacks and deals with leaks.
Daniel Sandler0da673f2012-04-11 12:33:16 -04001616 if (!isSystemNotification) {
Joe Onoratobd73d012010-06-04 11:44:54 -07001617 synchronized (mNotificationList) {
1618 int count = 0;
1619 final int N = mNotificationList.size();
1620 for (int i=0; i<N; i++) {
1621 final NotificationRecord r = mNotificationList.get(i);
Daniel Sandler4f91efd2013-04-25 16:38:41 -04001622 if (r.sbn.getPackageName().equals(pkg) && r.sbn.getUserId() == userId) {
Joe Onoratobd73d012010-06-04 11:44:54 -07001623 count++;
1624 if (count >= MAX_PACKAGE_NOTIFICATIONS) {
1625 Slog.e(TAG, "Package has already posted " + count
1626 + " notifications. Not showing more. package=" + pkg);
1627 return;
1628 }
1629 }
1630 }
1631 }
1632 }
1633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 // This conditional is a dirty hack to limit the logging done on
1635 // behalf of the download manager without affecting other apps.
1636 if (!pkg.equals("com.android.providers.downloads")
1637 || Log.isLoggable("DownloadManager", Log.VERBOSE)) {
Daniel Sandler321e9c52012-10-12 10:59:26 -07001638 EventLog.writeEvent(EventLogTags.NOTIFICATION_ENQUEUE, pkg, id, tag, userId,
Daniel Sandlerb64cb882011-11-29 23:48:29 -05001639 notification.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 }
1641
1642 if (pkg == null || notification == null) {
1643 throw new IllegalArgumentException("null not allowed: pkg=" + pkg
1644 + " id=" + id + " notification=" + notification);
1645 }
1646 if (notification.icon != 0) {
1647 if (notification.contentView == null) {
1648 throw new IllegalArgumentException("contentView required: pkg=" + pkg
1649 + " id=" + id + " notification=" + notification);
1650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 }
1652
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001653 // === Scoring ===
Daniel Sandler0da673f2012-04-11 12:33:16 -04001654
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001655 // 0. Sanitize inputs
1656 notification.priority = clamp(notification.priority, Notification.PRIORITY_MIN, Notification.PRIORITY_MAX);
1657 // Migrate notification flags to scores
1658 if (0 != (notification.flags & Notification.FLAG_HIGH_PRIORITY)) {
1659 if (notification.priority < Notification.PRIORITY_MAX) notification.priority = Notification.PRIORITY_MAX;
Daniel Sandler49a2ad12012-03-28 15:46:39 -04001660 } else if (SCORE_ONGOING_HIGHER && 0 != (notification.flags & Notification.FLAG_ONGOING_EVENT)) {
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001661 if (notification.priority < Notification.PRIORITY_HIGH) notification.priority = Notification.PRIORITY_HIGH;
1662 }
Daniel Sandler0da673f2012-04-11 12:33:16 -04001663
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001664 // 1. initial score: buckets of 10, around the app
Daniel Sandler0da673f2012-04-11 12:33:16 -04001665 int score = notification.priority * NOTIFICATION_PRIORITY_MULTIPLIER; //[-20..20]
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001666
Daniel Sandler0da673f2012-04-11 12:33:16 -04001667 // 2. Consult external heuristics (TBD)
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001668
Daniel Sandler0da673f2012-04-11 12:33:16 -04001669 // 3. Apply local rules
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001670
1671 // blocked apps
Daniel Sandler4a900acd2013-01-30 14:04:10 -05001672 if (ENABLE_BLOCKED_NOTIFICATIONS && !noteNotificationOp(pkg, callingUid)) {
1673 if (!isSystemNotification) {
1674 score = JUNK_SCORE;
1675 Slog.e(TAG, "Suppressing notification from package " + pkg + " by user request.");
1676 }
Daniel Sandler0da673f2012-04-11 12:33:16 -04001677 }
1678
1679 if (DBG) {
1680 Slog.v(TAG, "Assigned score=" + score + " to " + notification);
1681 }
1682
1683 if (score < SCORE_DISPLAY_THRESHOLD) {
1684 // Notification will be blocked because the score is too low.
1685 return;
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001686 }
1687
Daniel Sandler526fa0e2012-12-04 14:51:50 -05001688 // Should this notification make noise, vibe, or use the LED?
1689 final boolean canInterrupt = (score >= SCORE_INTERRUPTION_THRESHOLD);
1690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 synchronized (mNotificationList) {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001692 final StatusBarNotification n = new StatusBarNotification(
1693 pkg, id, tag, callingUid, callingPid, score, notification, user);
1694 NotificationRecord r = new NotificationRecord(n);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 NotificationRecord old = null;
1696
Dianne Hackborn41203752012-08-31 14:05:51 -07001697 int index = indexOfNotificationLocked(pkg, tag, id, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 if (index < 0) {
1699 mNotificationList.add(r);
1700 } else {
1701 old = mNotificationList.remove(index);
1702 mNotificationList.add(index, r);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001703 // Make sure we don't lose the foreground service state.
1704 if (old != null) {
1705 notification.flags |=
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001706 old.getNotification().flags&Notification.FLAG_FOREGROUND_SERVICE;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001709
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001710 // Ensure if this is a foreground service that the proper additional
1711 // flags are set.
1712 if ((notification.flags&Notification.FLAG_FOREGROUND_SERVICE) != 0) {
1713 notification.flags |= Notification.FLAG_ONGOING_EVENT
1714 | Notification.FLAG_NO_CLEAR;
1715 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001716
Svetoslav Ganovc31ed392012-10-10 14:58:28 -07001717 final int currentUser;
1718 final long token = Binder.clearCallingIdentity();
1719 try {
1720 currentUser = ActivityManager.getCurrentUser();
1721 } finally {
1722 Binder.restoreCallingIdentity(token);
1723 }
1724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 if (notification.icon != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 if (old != null && old.statusBarKey != null) {
1727 r.statusBarKey = old.statusBarKey;
1728 long identity = Binder.clearCallingIdentity();
1729 try {
Joe Onorato18e69df2010-05-17 22:26:12 -07001730 mStatusBar.updateNotification(r.statusBarKey, n);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 }
1732 finally {
1733 Binder.restoreCallingIdentity(identity);
1734 }
1735 } else {
1736 long identity = Binder.clearCallingIdentity();
1737 try {
Joe Onorato18e69df2010-05-17 22:26:12 -07001738 r.statusBarKey = mStatusBar.addNotification(n);
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04001739 if ((n.getNotification().flags & Notification.FLAG_SHOW_LIGHTS) != 0
Daniel Sandler526fa0e2012-12-04 14:51:50 -05001740 && canInterrupt) {
Mike Lockwoodece18ef2012-02-13 20:42:19 -08001741 mAttentionLight.pulse();
1742 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 }
1744 finally {
1745 Binder.restoreCallingIdentity(identity);
1746 }
1747 }
Svetoslav Ganovc31ed392012-10-10 14:58:28 -07001748 // Send accessibility events only for the current user.
1749 if (currentUser == userId) {
1750 sendAccessibilityEvent(notification, pkg);
1751 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001752
Daniel Sandler09a247e2013-02-14 10:24:17 -05001753 notifyPostedLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 } else {
Daniel Sandlere40451a2011-02-03 14:51:35 -05001755 Slog.e(TAG, "Ignoring notification with icon==0: " + notification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 if (old != null && old.statusBarKey != null) {
1757 long identity = Binder.clearCallingIdentity();
1758 try {
Joe Onorato0cbda992010-05-02 16:28:15 -07001759 mStatusBar.removeNotification(old.statusBarKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 }
1761 finally {
1762 Binder.restoreCallingIdentity(identity);
1763 }
Daniel Sandler09a247e2013-02-14 10:24:17 -05001764
1765 notifyRemovedLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001767 return; // do not play sounds, show lights, etc. for invalid notifications
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 }
1769
1770 // If we're not supposed to beep, vibrate, etc. then don't.
1771 if (((mDisabledNotifications & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) == 0)
1772 && (!(old != null
Joe Onorato30275482009-07-08 17:09:14 -07001773 && (notification.flags & Notification.FLAG_ONLY_ALERT_ONCE) != 0 ))
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001774 && (r.getUserId() == UserHandle.USER_ALL ||
1775 (r.getUserId() == userId && r.getUserId() == currentUser))
Daniel Sandler526fa0e2012-12-04 14:51:50 -05001776 && canInterrupt
Joe Onorato30275482009-07-08 17:09:14 -07001777 && mSystemReady) {
Eric Laurent524dc042009-11-27 05:07:55 -08001778
1779 final AudioManager audioManager = (AudioManager) mContext
1780 .getSystemService(Context.AUDIO_SERVICE);
Daniel Sandlerd4d2de22012-11-14 11:25:46 -08001781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 // sound
Daniel Sandler31475232013-04-17 00:17:22 -04001783
1784 // should we use the default notification sound? (indicated either by DEFAULT_SOUND
1785 // or because notification.sound is pointing at Settings.System.NOTIFICATION_SOUND)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 final boolean useDefaultSound =
Daniel Sandler31475232013-04-17 00:17:22 -04001787 (notification.defaults & Notification.DEFAULT_SOUND) != 0
1788 || Settings.System.DEFAULT_NOTIFICATION_URI.equals(notification.sound);
Daniel Sandlerd4d2de22012-11-14 11:25:46 -08001789
1790 Uri soundUri = null;
1791 boolean hasValidSound = false;
1792
1793 if (useDefaultSound) {
1794 soundUri = Settings.System.DEFAULT_NOTIFICATION_URI;
1795
1796 // check to see if the default notification sound is silent
1797 ContentResolver resolver = mContext.getContentResolver();
1798 hasValidSound = Settings.System.getString(resolver,
1799 Settings.System.NOTIFICATION_SOUND) != null;
1800 } else if (notification.sound != null) {
1801 soundUri = notification.sound;
1802 hasValidSound = (soundUri != null);
1803 }
1804
1805 if (hasValidSound) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 boolean looping = (notification.flags & Notification.FLAG_INSISTENT) != 0;
1807 int audioStreamType;
1808 if (notification.audioStreamType >= 0) {
1809 audioStreamType = notification.audioStreamType;
1810 } else {
1811 audioStreamType = DEFAULT_STREAM_TYPE;
1812 }
1813 mSoundNotification = r;
Eric Laurent524dc042009-11-27 05:07:55 -08001814 // do not play notifications if stream volume is 0
Jean-Michel Trivid6770542012-10-10 12:03:41 -07001815 // (typically because ringer mode is silent) or if speech recognition is active.
1816 if ((audioManager.getStreamVolume(audioStreamType) != 0)
1817 && !audioManager.isSpeechRecognitionActive()) {
Jeff Sharkey098d5802012-04-26 17:30:34 -07001818 final long identity = Binder.clearCallingIdentity();
Eric Laurent524dc042009-11-27 05:07:55 -08001819 try {
Jeff Sharkey098d5802012-04-26 17:30:34 -07001820 final IRingtonePlayer player = mAudioService.getRingtonePlayer();
1821 if (player != null) {
Daniel Sandlerd4d2de22012-11-14 11:25:46 -08001822 player.playAsync(soundUri, user, looping, audioStreamType);
Jeff Sharkey098d5802012-04-26 17:30:34 -07001823 }
1824 } catch (RemoteException e) {
1825 } finally {
Eric Laurent524dc042009-11-27 05:07:55 -08001826 Binder.restoreCallingIdentity(identity);
1827 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 }
1829 }
1830
1831 // vibrate
Daniel Sandleredbb3802012-11-13 20:49:47 -08001832 // Does the notification want to specify its own vibration?
1833 final boolean hasCustomVibrate = notification.vibrate != null;
1834
David Agnew71789e12012-11-09 23:03:26 -05001835 // new in 4.2: if there was supposed to be a sound and we're in vibrate mode,
Daniel Sandler4a7a9b92012-11-20 12:59:41 -05001836 // and no other vibration is specified, we fall back to vibration
David Agnew71789e12012-11-09 23:03:26 -05001837 final boolean convertSoundToVibration =
Daniel Sandleredbb3802012-11-13 20:49:47 -08001838 !hasCustomVibrate
Daniel Sandlerd4d2de22012-11-14 11:25:46 -08001839 && hasValidSound
David Agnew71789e12012-11-09 23:03:26 -05001840 && (audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE);
1841
Daniel Sandler4a7a9b92012-11-20 12:59:41 -05001842 // The DEFAULT_VIBRATE flag trumps any custom vibration AND the fallback.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 final boolean useDefaultVibrate =
Daniel Sandleredbb3802012-11-13 20:49:47 -08001844 (notification.defaults & Notification.DEFAULT_VIBRATE) != 0;
David Agnew71789e12012-11-09 23:03:26 -05001845
Daniel Sandleredbb3802012-11-13 20:49:47 -08001846 if ((useDefaultVibrate || convertSoundToVibration || hasCustomVibrate)
Eric Laurentbffc3d12012-05-07 17:43:49 -07001847 && !(audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 mVibrateNotification = r;
1849
Daniel Sandleredbb3802012-11-13 20:49:47 -08001850 if (useDefaultVibrate || convertSoundToVibration) {
1851 // Escalate privileges so we can use the vibrator even if the notifying app
1852 // does not have the VIBRATE permission.
1853 long identity = Binder.clearCallingIdentity();
1854 try {
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04001855 mVibrator.vibrate(r.sbn.getUid(), r.sbn.getBasePkg(),
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001856 useDefaultVibrate ? mDefaultVibrationPattern
1857 : mFallbackVibrationPattern,
Daniel Sandleredbb3802012-11-13 20:49:47 -08001858 ((notification.flags & Notification.FLAG_INSISTENT) != 0) ? 0: -1);
1859 } finally {
1860 Binder.restoreCallingIdentity(identity);
1861 }
1862 } else if (notification.vibrate.length > 1) {
1863 // If you want your own vibration pattern, you need the VIBRATE permission
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04001864 mVibrator.vibrate(r.sbn.getUid(), r.sbn.getBasePkg(), notification.vibrate,
Daniel Sandleredbb3802012-11-13 20:49:47 -08001865 ((notification.flags & Notification.FLAG_INSISTENT) != 0) ? 0: -1);
1866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 }
1868 }
1869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 // light
1871 // the most recent thing gets the light
1872 mLights.remove(old);
1873 if (mLedNotification == old) {
1874 mLedNotification = null;
1875 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001876 //Slog.i(TAG, "notification.lights="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 // + ((old.notification.lights.flags & Notification.FLAG_SHOW_LIGHTS) != 0));
Daniel Sandler526fa0e2012-12-04 14:51:50 -05001878 if ((notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0
1879 && canInterrupt) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 mLights.add(r);
1881 updateLightsLocked();
1882 } else {
1883 if (old != null
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001884 && ((old.getFlags() & Notification.FLAG_SHOW_LIGHTS) != 0)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 updateLightsLocked();
1886 }
1887 }
1888 }
1889
1890 idOut[0] = id;
1891 }
1892
Joe Onorato30275482009-07-08 17:09:14 -07001893 private void sendAccessibilityEvent(Notification notification, CharSequence packageName) {
svetoslavganov75986cf2009-05-14 22:28:01 -07001894 AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
1895 if (!manager.isEnabled()) {
1896 return;
1897 }
1898
1899 AccessibilityEvent event =
1900 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED);
1901 event.setPackageName(packageName);
1902 event.setClassName(Notification.class.getName());
1903 event.setParcelableData(notification);
1904 CharSequence tickerText = notification.tickerText;
1905 if (!TextUtils.isEmpty(tickerText)) {
1906 event.getText().add(tickerText);
1907 }
1908
1909 manager.sendAccessibilityEvent(event);
1910 }
1911
Joe Onorato46439ce2010-11-19 13:56:21 -08001912 private void cancelNotificationLocked(NotificationRecord r, boolean sendDelete) {
1913 // tell the app
1914 if (sendDelete) {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001915 if (r.getNotification().deleteIntent != null) {
Joe Onorato46439ce2010-11-19 13:56:21 -08001916 try {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001917 r.getNotification().deleteIntent.send();
Joe Onorato46439ce2010-11-19 13:56:21 -08001918 } catch (PendingIntent.CanceledException ex) {
1919 // do nothing - there's no relevant way to recover, and
1920 // no reason to let this propagate
Daniel Sandler4f91efd2013-04-25 16:38:41 -04001921 Slog.w(TAG, "canceled PendingIntent for " + r.sbn.getPackageName(), ex);
Joe Onorato46439ce2010-11-19 13:56:21 -08001922 }
1923 }
1924 }
1925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 // status bar
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001927 if (r.getNotification().icon != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 long identity = Binder.clearCallingIdentity();
1929 try {
Joe Onorato0cbda992010-05-02 16:28:15 -07001930 mStatusBar.removeNotification(r.statusBarKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 }
1932 finally {
1933 Binder.restoreCallingIdentity(identity);
1934 }
1935 r.statusBarKey = null;
Daniel Sandler09a247e2013-02-14 10:24:17 -05001936 notifyRemovedLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 }
1938
1939 // sound
1940 if (mSoundNotification == r) {
1941 mSoundNotification = null;
Jeff Sharkey098d5802012-04-26 17:30:34 -07001942 final long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 try {
Jeff Sharkey098d5802012-04-26 17:30:34 -07001944 final IRingtonePlayer player = mAudioService.getRingtonePlayer();
1945 if (player != null) {
1946 player.stopAsync();
1947 }
1948 } catch (RemoteException e) {
1949 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 Binder.restoreCallingIdentity(identity);
1951 }
1952 }
1953
1954 // vibrate
1955 if (mVibrateNotification == r) {
1956 mVibrateNotification = null;
1957 long identity = Binder.clearCallingIdentity();
1958 try {
1959 mVibrator.cancel();
1960 }
1961 finally {
1962 Binder.restoreCallingIdentity(identity);
1963 }
1964 }
1965
1966 // light
1967 mLights.remove(r);
1968 if (mLedNotification == r) {
1969 mLedNotification = null;
1970 }
Daniel Sandler23d7c702013-03-07 16:32:06 -05001971
1972 // Save it for users of getHistoricalNotifications()
1973 mArchive.record(r.sbn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974 }
1975
1976 /**
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001977 * Cancels a notification ONLY if it has all of the {@code mustHaveFlags}
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001978 * and none of the {@code mustNotHaveFlags}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001979 */
Fred Quintana6ecaff12009-09-25 14:23:13 -07001980 private void cancelNotification(String pkg, String tag, int id, int mustHaveFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07001981 int mustNotHaveFlags, boolean sendDelete, int userId) {
Daniel Sandler321e9c52012-10-12 10:59:26 -07001982 EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL, pkg, id, tag, userId,
Daniel Sandlerb64cb882011-11-29 23:48:29 -05001983 mustHaveFlags, mustNotHaveFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984
1985 synchronized (mNotificationList) {
Dianne Hackborn41203752012-08-31 14:05:51 -07001986 int index = indexOfNotificationLocked(pkg, tag, id, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 if (index >= 0) {
Fred Quintana6ecaff12009-09-25 14:23:13 -07001988 NotificationRecord r = mNotificationList.get(index);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001989
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001990 if ((r.getNotification().flags & mustHaveFlags) != mustHaveFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 return;
1992 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001993 if ((r.getNotification().flags & mustNotHaveFlags) != 0) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001994 return;
1995 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 mNotificationList.remove(index);
1998
Joe Onorato46439ce2010-11-19 13:56:21 -08001999 cancelNotificationLocked(r, sendDelete);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000 updateLightsLocked();
2001 }
2002 }
2003 }
2004
2005 /**
Daniel Sandler321e9c52012-10-12 10:59:26 -07002006 * Determine whether the userId applies to the notification in question, either because
2007 * they match exactly, or one of them is USER_ALL (which is treated as a wildcard).
2008 */
2009 private boolean notificationMatchesUserId(NotificationRecord r, int userId) {
2010 return
2011 // looking for USER_ALL notifications? match everything
2012 userId == UserHandle.USER_ALL
2013 // a notification sent to USER_ALL matches any query
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002014 || r.getUserId() == UserHandle.USER_ALL
Daniel Sandler321e9c52012-10-12 10:59:26 -07002015 // an exact user match
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002016 || r.getUserId() == userId;
Daniel Sandler321e9c52012-10-12 10:59:26 -07002017 }
2018
2019 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 * Cancels all notifications from a given package that have all of the
2021 * {@code mustHaveFlags}.
2022 */
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002023 boolean cancelAllNotificationsInt(String pkg, int mustHaveFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002024 int mustNotHaveFlags, boolean doit, int userId) {
Daniel Sandler321e9c52012-10-12 10:59:26 -07002025 EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL_ALL, pkg, userId,
2026 mustHaveFlags, mustNotHaveFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027
2028 synchronized (mNotificationList) {
2029 final int N = mNotificationList.size();
2030 boolean canceledSomething = false;
2031 for (int i = N-1; i >= 0; --i) {
2032 NotificationRecord r = mNotificationList.get(i);
Daniel Sandler321e9c52012-10-12 10:59:26 -07002033 if (!notificationMatchesUserId(r, userId)) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002034 continue;
2035 }
Amith Yamasani5ec00e92012-11-07 16:58:30 -08002036 // Don't remove notifications to all, if there's no package name specified
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002037 if (r.getUserId() == UserHandle.USER_ALL && pkg == null) {
Amith Yamasani5ec00e92012-11-07 16:58:30 -08002038 continue;
2039 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002040 if ((r.getFlags() & mustHaveFlags) != mustHaveFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 continue;
2042 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002043 if ((r.getFlags() & mustNotHaveFlags) != 0) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002044 continue;
2045 }
Daniel Sandler4f91efd2013-04-25 16:38:41 -04002046 if (pkg != null && !r.sbn.getPackageName().equals(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 continue;
2048 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002049 canceledSomething = true;
2050 if (!doit) {
2051 return true;
2052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 mNotificationList.remove(i);
Joe Onorato46439ce2010-11-19 13:56:21 -08002054 cancelNotificationLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055 }
2056 if (canceledSomething) {
2057 updateLightsLocked();
2058 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002059 return canceledSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 }
2061 }
2062
Dianne Hackborn41203752012-08-31 14:05:51 -07002063 public void cancelNotificationWithTag(String pkg, String tag, int id, int userId) {
Daniel Sandler0da673f2012-04-11 12:33:16 -04002064 checkCallerIsSystemOrSameApp(pkg);
Dianne Hackborn41203752012-08-31 14:05:51 -07002065 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07002066 Binder.getCallingUid(), userId, true, false, "cancelNotificationWithTag", pkg);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002067 // Don't allow client applications to cancel foreground service notis.
Fred Quintana6ecaff12009-09-25 14:23:13 -07002068 cancelNotification(pkg, tag, id, 0,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002069 Binder.getCallingUid() == Process.SYSTEM_UID
Dianne Hackborn41203752012-08-31 14:05:51 -07002070 ? 0 : Notification.FLAG_FOREGROUND_SERVICE, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 }
2072
Dianne Hackborn41203752012-08-31 14:05:51 -07002073 public void cancelAllNotifications(String pkg, int userId) {
Daniel Sandler0da673f2012-04-11 12:33:16 -04002074 checkCallerIsSystemOrSameApp(pkg);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002075
Dianne Hackborn41203752012-08-31 14:05:51 -07002076 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07002077 Binder.getCallingUid(), userId, true, false, "cancelAllNotifications", pkg);
Dianne Hackborn41203752012-08-31 14:05:51 -07002078
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002079 // Calling from user space, don't allow the canceling of actively
2080 // running foreground services.
Dianne Hackborn41203752012-08-31 14:05:51 -07002081 cancelAllNotificationsInt(pkg, 0, Notification.FLAG_FOREGROUND_SERVICE, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002082 }
2083
Daniel Sandler0da673f2012-04-11 12:33:16 -04002084 void checkCallerIsSystem() {
2085 int uid = Binder.getCallingUid();
Dianne Hackborn0c380492012-08-20 17:23:30 -07002086 if (UserHandle.getAppId(uid) == Process.SYSTEM_UID || uid == 0) {
Daniel Sandler0da673f2012-04-11 12:33:16 -04002087 return;
2088 }
2089 throw new SecurityException("Disallowed call for uid " + uid);
2090 }
2091
2092 void checkCallerIsSystemOrSameApp(String pkg) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002093 int uid = Binder.getCallingUid();
Dianne Hackborn0c380492012-08-20 17:23:30 -07002094 if (UserHandle.getAppId(uid) == Process.SYSTEM_UID || uid == 0) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002095 return;
2096 }
2097 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07002098 ApplicationInfo ai = AppGlobals.getPackageManager().getApplicationInfo(
2099 pkg, 0, UserHandle.getCallingUserId());
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002100 if (!UserHandle.isSameApp(ai.uid, uid)) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002101 throw new SecurityException("Calling uid " + uid + " gave package"
2102 + pkg + " which is owned by uid " + ai.uid);
2103 }
Amith Yamasanif203aee2012-08-29 18:41:53 -07002104 } catch (RemoteException re) {
2105 throw new SecurityException("Unknown package " + pkg + "\n" + re);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002106 }
2107 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002108
Dianne Hackborn41203752012-08-31 14:05:51 -07002109 void cancelAll(int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002110 synchronized (mNotificationList) {
2111 final int N = mNotificationList.size();
2112 for (int i=N-1; i>=0; i--) {
2113 NotificationRecord r = mNotificationList.get(i);
2114
Daniel Sandler321e9c52012-10-12 10:59:26 -07002115 if (!notificationMatchesUserId(r, userId)) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002116 continue;
2117 }
2118
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002119 if ((r.getFlags() & (Notification.FLAG_ONGOING_EVENT
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 | Notification.FLAG_NO_CLEAR)) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 mNotificationList.remove(i);
Joe Onorato46439ce2010-11-19 13:56:21 -08002122 cancelNotificationLocked(r, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 }
2124 }
2125
2126 updateLightsLocked();
2127 }
2128 }
2129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 // lock on mNotificationList
2131 private void updateLightsLocked()
2132 {
The Android Open Source Project10592532009-03-18 17:39:46 -07002133 // handle notification lights
2134 if (mLedNotification == null) {
2135 // get next notification, if any
2136 int n = mLights.size();
2137 if (n > 0) {
2138 mLedNotification = mLights.get(n-1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 }
2140 }
Mike Lockwoodc22404a2009-12-02 11:15:02 -05002141
Mike Lockwood63b5ad92011-08-30 09:55:30 -04002142 // Don't flash while we are in a call or screen is on
2143 if (mLedNotification == null || mInCall || mScreenOn) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002144 mNotificationLight.turnOff();
The Android Open Source Project10592532009-03-18 17:39:46 -07002145 } else {
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04002146 final Notification ledno = mLedNotification.sbn.getNotification();
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002147 int ledARGB = ledno.ledARGB;
2148 int ledOnMS = ledno.ledOnMS;
2149 int ledOffMS = ledno.ledOffMS;
2150 if ((ledno.defaults & Notification.DEFAULT_LIGHTS) != 0) {
Mike Lockwood670f9322010-01-20 12:13:36 -05002151 ledARGB = mDefaultNotificationColor;
2152 ledOnMS = mDefaultNotificationLedOn;
2153 ledOffMS = mDefaultNotificationLedOff;
2154 }
2155 if (mNotificationPulseEnabled) {
2156 // pulse repeatedly
2157 mNotificationLight.setFlashing(ledARGB, LightsService.LIGHT_FLASH_TIMED,
2158 ledOnMS, ledOffMS);
Mike Lockwood670f9322010-01-20 12:13:36 -05002159 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002160 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 }
2162
2163 // lock on mNotificationList
Dianne Hackborn41203752012-08-31 14:05:51 -07002164 private int indexOfNotificationLocked(String pkg, String tag, int id, int userId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002165 {
2166 ArrayList<NotificationRecord> list = mNotificationList;
2167 final int len = list.size();
2168 for (int i=0; i<len; i++) {
2169 NotificationRecord r = list.get(i);
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04002170 if (!notificationMatchesUserId(r, userId) || r.sbn.getId() != id) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002171 continue;
2172 }
Fred Quintana6ecaff12009-09-25 14:23:13 -07002173 if (tag == null) {
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04002174 if (r.sbn.getTag() != null) {
Fred Quintana6ecaff12009-09-25 14:23:13 -07002175 continue;
2176 }
2177 } else {
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04002178 if (!tag.equals(r.sbn.getTag())) {
Fred Quintana6ecaff12009-09-25 14:23:13 -07002179 continue;
2180 }
2181 }
Daniel Sandler4f91efd2013-04-25 16:38:41 -04002182 if (r.sbn.getPackageName().equals(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002183 return i;
2184 }
2185 }
2186 return -1;
2187 }
2188
Mike Lockwoodc22404a2009-12-02 11:15:02 -05002189 private void updateNotificationPulse() {
2190 synchronized (mNotificationList) {
2191 updateLightsLocked();
2192 }
2193 }
2194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002195 // ======================================================================
2196 @Override
2197 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2198 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2199 != PackageManager.PERMISSION_GRANTED) {
2200 pw.println("Permission Denial: can't dump NotificationManager from from pid="
2201 + Binder.getCallingPid()
2202 + ", uid=" + Binder.getCallingUid());
2203 return;
2204 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002206 pw.println("Current Notification Manager state:");
2207
Daniel Sandler5feceeb2013-03-22 18:29:23 -07002208 pw.println(" Listeners (" + mEnabledListenersForCurrentUser.size()
2209 + ") enabled for current user:");
2210 for (ComponentName cmpt : mEnabledListenersForCurrentUser) {
2211 pw.println(" " + cmpt);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04002212 }
Daniel Sandler4b749ef2013-03-18 21:53:04 -04002213
Daniel Sandler5feceeb2013-03-22 18:29:23 -07002214 pw.println(" Live listeners (" + mListeners.size() + "):");
Daniel Sandler4b749ef2013-03-18 21:53:04 -04002215 for (NotificationListenerInfo info : mListeners) {
Daniel Sandler5feceeb2013-03-22 18:29:23 -07002216 pw.println(" " + info.component
2217 + " (user " + info.userid + "): " + info.listener
2218 + (info.isSystem?" SYSTEM":""));
Daniel Sandler4b749ef2013-03-18 21:53:04 -04002219 }
2220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002221 int N;
2222
2223 synchronized (mToastQueue) {
2224 N = mToastQueue.size();
2225 if (N > 0) {
2226 pw.println(" Toast Queue:");
2227 for (int i=0; i<N; i++) {
2228 mToastQueue.get(i).dump(pw, " ");
2229 }
2230 pw.println(" ");
2231 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002233 }
2234
2235 synchronized (mNotificationList) {
2236 N = mNotificationList.size();
2237 if (N > 0) {
2238 pw.println(" Notification List:");
2239 for (int i=0; i<N; i++) {
2240 mNotificationList.get(i).dump(pw, " ", mContext);
2241 }
2242 pw.println(" ");
2243 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002245 N = mLights.size();
2246 if (N > 0) {
2247 pw.println(" Lights List:");
2248 for (int i=0; i<N; i++) {
Daniel Sandlerf45564e2013-04-15 15:05:08 -04002249 pw.println(" " + mLights.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 }
2251 pw.println(" ");
2252 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002254 pw.println(" mSoundNotification=" + mSoundNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002255 pw.println(" mVibrateNotification=" + mVibrateNotification);
Joe Onorato39f5b6a2009-07-23 12:29:19 -04002256 pw.println(" mDisabledNotifications=0x" + Integer.toHexString(mDisabledNotifications));
2257 pw.println(" mSystemReady=" + mSystemReady);
Daniel Sandler5e62e3a2013-04-15 20:57:02 -04002258 pw.println(" mArchive=" + mArchive.toString());
2259 Iterator<StatusBarNotification> iter = mArchive.descendingIterator();
2260 int i=0;
2261 while (iter.hasNext()) {
2262 pw.println(" " + iter.next());
2263 if (++i >= 5) {
2264 if (iter.hasNext()) pw.println(" ...");
2265 break;
2266 }
2267 }
2268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 }
2270 }
2271}