blob: 1a2c3dedb41dff979b5bf3adbe761f5573a85ace [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;
Dianne Hackborn1dac2772009-06-26 18:16:48 -070034import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.Context;
36import android.content.Intent;
37import android.content.IntentFilter;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070038import android.content.pm.ApplicationInfo;
Daniel Sandler4a900acd2013-01-30 14:04:10 -050039import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.content.pm.PackageManager;
41import android.content.pm.PackageManager.NameNotFoundException;
42import android.content.res.Resources;
Dianne Hackborn1dac2772009-06-26 18:16:48 -070043import android.database.ContentObserver;
svetoslavganov75986cf2009-05-14 22:28:01 -070044import android.media.AudioManager;
Jeff Sharkey098d5802012-04-26 17:30:34 -070045import android.media.IAudioService;
46import android.media.IRingtonePlayer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.os.Binder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.os.IBinder;
51import android.os.Message;
Daniel Sandlerfde19b12013-01-17 00:21:05 -050052import android.os.Parcel;
53import android.os.Parcelable;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070054import android.os.Process;
svetoslavganov75986cf2009-05-14 22:28:01 -070055import android.os.RemoteException;
Jeff Sharkey098d5802012-04-26 17:30:34 -070056import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070057import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.os.Vibrator;
59import android.provider.Settings;
Daniel Sandlere96ffb12010-03-11 13:38:06 -050060import android.telephony.TelephonyManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070061import android.text.TextUtils;
Dianne Hackborn39606a02012-07-31 17:54:35 -070062import android.util.AtomicFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.util.EventLog;
64import android.util.Log;
Andy Stadler110988c2010-12-03 14:29:16 -080065import android.util.Slog;
Daniel Sandler0da673f2012-04-11 12:33:16 -040066import android.util.Xml;
svetoslavganov75986cf2009-05-14 22:28:01 -070067import android.view.accessibility.AccessibilityEvent;
68import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.widget.Toast;
70
Jeff Sharkey098d5802012-04-26 17:30:34 -070071import com.android.internal.statusbar.StatusBarNotification;
Jeff Sharkey098d5802012-04-26 17:30:34 -070072
73import org.xmlpull.v1.XmlPullParser;
74import org.xmlpull.v1.XmlPullParserException;
Jeff Sharkey098d5802012-04-26 17:30:34 -070075
Daniel Sandler0da673f2012-04-11 12:33:16 -040076import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import java.io.FileDescriptor;
Daniel Sandler0da673f2012-04-11 12:33:16 -040078import java.io.FileInputStream;
79import java.io.FileNotFoundException;
Daniel Sandler0da673f2012-04-11 12:33:16 -040080import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import java.io.PrintWriter;
Daniel Sandlerfde19b12013-01-17 00:21:05 -050082import java.util.ArrayDeque;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import java.util.ArrayList;
84import java.util.Arrays;
Daniel Sandler0da673f2012-04-11 12:33:16 -040085import java.util.HashSet;
Daniel Sandlerfde19b12013-01-17 00:21:05 -050086import java.util.Iterator;
87import java.util.NoSuchElementException;
Daniel Sandler0da673f2012-04-11 12:33:16 -040088
89import libcore.io.IoUtils;
90
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091
Daniel Sandlerd0a2f862010-08-03 15:29:31 -040092/** {@hide} */
93public class NotificationManagerService extends INotificationManager.Stub
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094{
95 private static final String TAG = "NotificationService";
96 private static final boolean DBG = false;
97
Joe Onoratobd73d012010-06-04 11:44:54 -070098 private static final int MAX_PACKAGE_NOTIFICATIONS = 50;
99
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 // message codes
101 private static final int MESSAGE_TIMEOUT = 2;
102
103 private static final int LONG_DELAY = 3500; // 3.5 seconds
104 private static final int SHORT_DELAY = 2000; // 2 seconds
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800105
106 private static final long[] DEFAULT_VIBRATE_PATTERN = {0, 250, 250, 250};
Daniel Sandleredbb3802012-11-13 20:49:47 -0800107 private static final int VIBRATE_PATTERN_MAXLEN = 8 * 2 + 1; // up to eight bumps
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108
109 private static final int DEFAULT_STREAM_TYPE = AudioManager.STREAM_NOTIFICATION;
Daniel Sandler49a2ad12012-03-28 15:46:39 -0400110 private static final boolean SCORE_ONGOING_HIGHER = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111
Daniel Sandler0da673f2012-04-11 12:33:16 -0400112 private static final int JUNK_SCORE = -1000;
113 private static final int NOTIFICATION_PRIORITY_MULTIPLIER = 10;
114 private static final int SCORE_DISPLAY_THRESHOLD = Notification.PRIORITY_MIN * NOTIFICATION_PRIORITY_MULTIPLIER;
115
Daniel Sandler526fa0e2012-12-04 14:51:50 -0500116 // Notifications with scores below this will not interrupt the user, either via LED or
117 // sound or vibration
118 private static final int SCORE_INTERRUPTION_THRESHOLD =
119 Notification.PRIORITY_LOW * NOTIFICATION_PRIORITY_MULTIPLIER;
120
Daniel Sandler0da673f2012-04-11 12:33:16 -0400121 private static final boolean ENABLE_BLOCKED_NOTIFICATIONS = true;
122 private static final boolean ENABLE_BLOCKED_TOASTS = true;
123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124 final Context mContext;
125 final IActivityManager mAm;
126 final IBinder mForegroundToken = new Binder();
127
128 private WorkerHandler mHandler;
Joe Onorato089de882010-04-12 08:18:45 -0700129 private StatusBarManagerService mStatusBar;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500130 private LightsService.Light mNotificationLight;
131 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132
Mike Lockwood670f9322010-01-20 12:13:36 -0500133 private int mDefaultNotificationColor;
134 private int mDefaultNotificationLedOn;
135 private int mDefaultNotificationLedOff;
136
Daniel Sandleredbb3802012-11-13 20:49:47 -0800137 private long[] mDefaultVibrationPattern;
138 private long[] mFallbackVibrationPattern;
139
Joe Onorato30275482009-07-08 17:09:14 -0700140 private boolean mSystemReady;
Joe Onorato39f5b6a2009-07-23 12:29:19 -0400141 private int mDisabledNotifications;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142
Jeff Sharkey098d5802012-04-26 17:30:34 -0700143 private NotificationRecord mSoundNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144 private NotificationRecord mVibrateNotification;
Jeff Sharkey098d5802012-04-26 17:30:34 -0700145
146 private IAudioService mAudioService;
Jeff Brownc2346132012-04-13 01:55:38 -0700147 private Vibrator mVibrator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148
Mike Lockwoodc22404a2009-12-02 11:15:02 -0500149 // for enabling and disabling notification pulse behavior
Mike Lockwood63b5ad92011-08-30 09:55:30 -0400150 private boolean mScreenOn = true;
Daniel Sandlere96ffb12010-03-11 13:38:06 -0500151 private boolean mInCall = false;
Mike Lockwoodc22404a2009-12-02 11:15:02 -0500152 private boolean mNotificationPulseEnabled;
153
Fred Quintana6ecaff12009-09-25 14:23:13 -0700154 private final ArrayList<NotificationRecord> mNotificationList =
155 new ArrayList<NotificationRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
157 private ArrayList<ToastRecord> mToastQueue;
158
159 private ArrayList<NotificationRecord> mLights = new ArrayList<NotificationRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 private NotificationRecord mLedNotification;
svetoslavganov75986cf2009-05-14 22:28:01 -0700161
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500162 private final AppOpsManager mAppOps;
163
Daniel Sandler0da673f2012-04-11 12:33:16 -0400164 // Notification control database. For now just contains disabled packages.
165 private AtomicFile mPolicyFile;
166 private HashSet<String> mBlockedPackages = new HashSet<String>();
167
168 private static final int DB_VERSION = 1;
169
170 private static final String TAG_BODY = "notification-policy";
171 private static final String ATTR_VERSION = "version";
172
173 private static final String TAG_BLOCKED_PKGS = "blocked-packages";
174 private static final String TAG_PACKAGE = "package";
175 private static final String ATTR_NAME = "name";
176
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500177 private static class Archive {
178 static final int BUFFER_SIZE = 1000;
179 ArrayDeque<StatusBarNotification> mBuffer = new ArrayDeque<StatusBarNotification>(BUFFER_SIZE);
180
181 public Archive() {
182
183 }
184 public void record(StatusBarNotification nr) {
185 if (mBuffer.size() == BUFFER_SIZE) {
186 mBuffer.removeFirst();
187 }
188 mBuffer.addLast(nr);
189 }
190
191 public void clear() {
192 mBuffer.clear();
193 }
194
195 public Iterator<StatusBarNotification> descendingIterator() {
196 return mBuffer.descendingIterator();
197 }
198 public Iterator<StatusBarNotification> ascendingIterator() {
199 return mBuffer.iterator();
200 }
201 public Iterator<StatusBarNotification> filter(
202 final Iterator<StatusBarNotification> iter, final String pkg, final int userId) {
203 return new Iterator<StatusBarNotification>() {
204 StatusBarNotification mNext = findNext();
205
206 private StatusBarNotification findNext() {
207 while (iter.hasNext()) {
208 StatusBarNotification nr = iter.next();
209 if ((pkg == null || nr.pkg == pkg)
210 && (userId == UserHandle.USER_ALL || nr.getUserId() == userId)) {
211 return nr;
212 }
213 }
214 return null;
215 }
216
217 @Override
218 public boolean hasNext() {
219 return mNext == null;
220 }
221
222 @Override
223 public StatusBarNotification next() {
224 StatusBarNotification next = mNext;
225 if (next == null) {
226 throw new NoSuchElementException();
227 }
228 mNext = findNext();
229 return next;
230 }
231
232 @Override
233 public void remove() {
234 iter.remove();
235 }
236 };
237 }
238 }
239
240 Archive mArchive = new Archive();
241
Daniel Sandler0da673f2012-04-11 12:33:16 -0400242 private void loadBlockDb() {
243 synchronized(mBlockedPackages) {
244 if (mPolicyFile == null) {
245 File dir = new File("/data/system");
246 mPolicyFile = new AtomicFile(new File(dir, "notification_policy.xml"));
247
248 mBlockedPackages.clear();
249
250 FileInputStream infile = null;
251 try {
252 infile = mPolicyFile.openRead();
253 final XmlPullParser parser = Xml.newPullParser();
254 parser.setInput(infile, null);
255
256 int type;
257 String tag;
258 int version = DB_VERSION;
259 while ((type = parser.next()) != END_DOCUMENT) {
260 tag = parser.getName();
261 if (type == START_TAG) {
262 if (TAG_BODY.equals(tag)) {
263 version = Integer.parseInt(parser.getAttributeValue(null, ATTR_VERSION));
264 } else if (TAG_BLOCKED_PKGS.equals(tag)) {
265 while ((type = parser.next()) != END_DOCUMENT) {
266 tag = parser.getName();
267 if (TAG_PACKAGE.equals(tag)) {
268 mBlockedPackages.add(parser.getAttributeValue(null, ATTR_NAME));
269 } else if (TAG_BLOCKED_PKGS.equals(tag) && type == END_TAG) {
270 break;
271 }
272 }
273 }
274 }
275 }
276 } catch (FileNotFoundException e) {
277 // No data yet
278 } catch (IOException e) {
279 Log.wtf(TAG, "Unable to read blocked notifications database", e);
280 } catch (NumberFormatException e) {
281 Log.wtf(TAG, "Unable to parse blocked notifications database", e);
282 } catch (XmlPullParserException e) {
283 Log.wtf(TAG, "Unable to parse blocked notifications database", e);
284 } finally {
285 IoUtils.closeQuietly(infile);
286 }
287 }
288 }
289 }
290
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500291 /**
292 * Use this when you just want to know if notifications are OK for this package.
293 */
294 public boolean areNotificationsEnabledForPackage(String pkg, int uid) {
Daniel Sandler0da673f2012-04-11 12:33:16 -0400295 checkCallerIsSystem();
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500296 return (mAppOps.checkOpNoThrow(AppOpsManager.OP_POST_NOTIFICATION, uid, pkg)
297 == AppOpsManager.MODE_ALLOWED);
Daniel Sandler0da673f2012-04-11 12:33:16 -0400298 }
299
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500300 /** Use this when you actually want to post a notification or toast.
301 *
302 * Unchecked. Not exposed via Binder, but can be called in the course of enqueue*().
303 */
304 private boolean noteNotificationOp(String pkg, int uid) {
305 if (mAppOps.noteOpNoThrow(AppOpsManager.OP_POST_NOTIFICATION, uid, pkg)
306 != AppOpsManager.MODE_ALLOWED) {
307 Slog.v(TAG, "notifications are disabled by AppOps for " + pkg);
308 return false;
Daniel Sandler0da673f2012-04-11 12:33:16 -0400309 }
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500310 return true;
Daniel Sandler0da673f2012-04-11 12:33:16 -0400311 }
312
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500313 public void setNotificationsEnabledForPackage(String pkg, int uid, boolean enabled) {
Daniel Sandler0da673f2012-04-11 12:33:16 -0400314 checkCallerIsSystem();
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500315 if (true||DBG) {
Daniel Sandler0da673f2012-04-11 12:33:16 -0400316 Slog.v(TAG, (enabled?"en":"dis") + "abling notifications for " + pkg);
317 }
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500318 mAppOps.setMode(AppOpsManager.OP_POST_NOTIFICATION, uid, pkg,
319 enabled ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
Daniel Sandler0da673f2012-04-11 12:33:16 -0400320 }
321
322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 private static String idDebugString(Context baseContext, String packageName, int id) {
324 Context c = null;
325
326 if (packageName != null) {
327 try {
328 c = baseContext.createPackageContext(packageName, 0);
329 } catch (NameNotFoundException e) {
330 c = baseContext;
331 }
332 } else {
333 c = baseContext;
334 }
335
336 String pkg;
337 String type;
338 String name;
339
340 Resources r = c.getResources();
341 try {
342 return r.getResourceName(id);
343 } catch (Resources.NotFoundException e) {
344 return "<name unknown>";
345 }
346 }
347
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500348 public StatusBarNotification[] getActiveNotifications(String callingPkg) {
349 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_NOTIFICATIONS,
350 "NotificationManagerService");
351
352 StatusBarNotification[] tmp = null;
353 int userId = UserHandle.getCallingUserId();
354 int uid = Binder.getCallingUid();
355
356 if (mAppOps.noteOpNoThrow(AppOpsManager.OP_ACCESS_NOTIFICATIONS, uid, callingPkg)
357 == AppOpsManager.MODE_ALLOWED) {
358 synchronized (mNotificationList) {
359 tmp = new StatusBarNotification[mNotificationList.size()];
360 final int N = mNotificationList.size();
361 for (int i=0; i<N; i++) {
362 tmp[i] = mNotificationList.get(i).sbn;
363 }
364 }
365 }
366 return tmp;
367 }
368
369 public static final class NotificationRecord
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370 {
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500371 final StatusBarNotification sbn;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800372 IBinder statusBarKey;
373
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500374 NotificationRecord(StatusBarNotification sbn)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 {
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500376 this.sbn = sbn;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800377 }
Fred Quintana6ecaff12009-09-25 14:23:13 -0700378
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500379 public Notification getNotification() { return sbn.notification; }
380 public int getFlags() { return sbn.notification.flags; }
381 public int getUserId() { return sbn.getUserId(); }
382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 void dump(PrintWriter pw, String prefix, Context baseContext) {
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500384 final Notification notification = sbn.notification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 pw.println(prefix + this);
386 pw.println(prefix + " icon=0x" + Integer.toHexString(notification.icon)
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500387 + " / " + idDebugString(baseContext, this.sbn.pkg, notification.icon));
Daniel Sandler2561b0b2012-02-13 21:04:12 -0500388 pw.println(prefix + " pri=" + notification.priority);
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500389 pw.println(prefix + " score=" + this.sbn.score);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800390 pw.println(prefix + " contentIntent=" + notification.contentIntent);
391 pw.println(prefix + " deleteIntent=" + notification.deleteIntent);
392 pw.println(prefix + " tickerText=" + notification.tickerText);
393 pw.println(prefix + " contentView=" + notification.contentView);
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500394 pw.println(prefix + " uid=" + this.sbn.uid + " userId=" + this.sbn.getUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800395 pw.println(prefix + " defaults=0x" + Integer.toHexString(notification.defaults));
396 pw.println(prefix + " flags=0x" + Integer.toHexString(notification.flags));
397 pw.println(prefix + " sound=" + notification.sound);
398 pw.println(prefix + " vibrate=" + Arrays.toString(notification.vibrate));
399 pw.println(prefix + " ledARGB=0x" + Integer.toHexString(notification.ledARGB)
400 + " ledOnMS=" + notification.ledOnMS
401 + " ledOffMS=" + notification.ledOffMS);
402 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 @Override
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500405 public final String toString() {
406 return String.format(
407 "NotificationRecord(0x%08x: pkg=%s user=%s id=%d tag=%s score=%d: %s)",
408 System.identityHashCode(this),
409 this.sbn.pkg, this.sbn.user, this.sbn.id, this.sbn.tag,
410 this.sbn.score, this.sbn.notification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 }
412 }
413
414 private static final class ToastRecord
415 {
416 final int pid;
417 final String pkg;
418 final ITransientNotification callback;
419 int duration;
420
421 ToastRecord(int pid, String pkg, ITransientNotification callback, int duration)
422 {
423 this.pid = pid;
424 this.pkg = pkg;
425 this.callback = callback;
426 this.duration = duration;
427 }
428
429 void update(int duration) {
430 this.duration = duration;
431 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800433 void dump(PrintWriter pw, String prefix) {
434 pw.println(prefix + this);
435 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 @Override
438 public final String toString()
439 {
440 return "ToastRecord{"
441 + Integer.toHexString(System.identityHashCode(this))
442 + " pkg=" + pkg
443 + " callback=" + callback
444 + " duration=" + duration;
445 }
446 }
447
Joe Onorato089de882010-04-12 08:18:45 -0700448 private StatusBarManagerService.NotificationCallbacks mNotificationCallbacks
449 = new StatusBarManagerService.NotificationCallbacks() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800450
451 public void onSetDisabled(int status) {
452 synchronized (mNotificationList) {
453 mDisabledNotifications = status;
454 if ((mDisabledNotifications & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) {
455 // cancel whatever's going on
456 long identity = Binder.clearCallingIdentity();
457 try {
Jeff Sharkey098d5802012-04-26 17:30:34 -0700458 final IRingtonePlayer player = mAudioService.getRingtonePlayer();
459 if (player != null) {
460 player.stopAsync();
461 }
462 } catch (RemoteException e) {
463 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800464 Binder.restoreCallingIdentity(identity);
465 }
466
467 identity = Binder.clearCallingIdentity();
468 try {
469 mVibrator.cancel();
Jeff Sharkey098d5802012-04-26 17:30:34 -0700470 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 Binder.restoreCallingIdentity(identity);
472 }
473 }
474 }
475 }
476
477 public void onClearAll() {
Dianne Hackborn41203752012-08-31 14:05:51 -0700478 // XXX to be totally correct, the caller should tell us which user
479 // this is for.
480 cancelAll(ActivityManager.getCurrentUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800481 }
482
Fred Quintana6ecaff12009-09-25 14:23:13 -0700483 public void onNotificationClick(String pkg, String tag, int id) {
Dianne Hackborn41203752012-08-31 14:05:51 -0700484 // XXX to be totally correct, the caller should tell us which user
485 // this is for.
Fred Quintana6ecaff12009-09-25 14:23:13 -0700486 cancelNotification(pkg, tag, id, Notification.FLAG_AUTO_CANCEL,
Dianne Hackborn41203752012-08-31 14:05:51 -0700487 Notification.FLAG_FOREGROUND_SERVICE, false,
488 ActivityManager.getCurrentUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 }
490
Daniel Sandler0f0b11c2010-08-04 15:54:58 -0400491 public void onNotificationClear(String pkg, String tag, int id) {
Dianne Hackborn41203752012-08-31 14:05:51 -0700492 // XXX to be totally correct, the caller should tell us which user
493 // this is for.
Joe Onorato46439ce2010-11-19 13:56:21 -0800494 cancelNotification(pkg, tag, id, 0,
495 Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE,
Dianne Hackborn41203752012-08-31 14:05:51 -0700496 true, ActivityManager.getCurrentUser());
Daniel Sandler0f0b11c2010-08-04 15:54:58 -0400497 }
498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 public void onPanelRevealed() {
500 synchronized (mNotificationList) {
501 // sound
502 mSoundNotification = null;
Jeff Sharkey098d5802012-04-26 17:30:34 -0700503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 long identity = Binder.clearCallingIdentity();
505 try {
Jeff Sharkey098d5802012-04-26 17:30:34 -0700506 final IRingtonePlayer player = mAudioService.getRingtonePlayer();
507 if (player != null) {
508 player.stopAsync();
509 }
510 } catch (RemoteException e) {
511 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 Binder.restoreCallingIdentity(identity);
513 }
514
515 // vibrate
516 mVibrateNotification = null;
517 identity = Binder.clearCallingIdentity();
518 try {
519 mVibrator.cancel();
Jeff Sharkey098d5802012-04-26 17:30:34 -0700520 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 Binder.restoreCallingIdentity(identity);
522 }
523
524 // light
525 mLights.clear();
526 mLedNotification = null;
527 updateLightsLocked();
528 }
529 }
Joe Onorato005847b2010-06-04 16:08:02 -0400530
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700531 public void onNotificationError(String pkg, String tag, int id,
532 int uid, int initialPid, String message) {
Daniel Sandlerd0a2f862010-08-03 15:29:31 -0400533 Slog.d(TAG, "onNotification error pkg=" + pkg + " tag=" + tag + " id=" + id
534 + "; will crashApplication(uid=" + uid + ", pid=" + initialPid + ")");
Dianne Hackborn41203752012-08-31 14:05:51 -0700535 // XXX to be totally correct, the caller should tell us which user
536 // this is for.
537 cancelNotification(pkg, tag, id, 0, 0, false, UserHandle.getUserId(uid));
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700538 long ident = Binder.clearCallingIdentity();
539 try {
540 ActivityManagerNative.getDefault().crashApplication(uid, initialPid, pkg,
541 "Bad notification posted from package " + pkg
542 + ": " + message);
543 } catch (RemoteException e) {
544 }
545 Binder.restoreCallingIdentity(ident);
Joe Onorato005847b2010-06-04 16:08:02 -0400546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 };
548
549 private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
550 @Override
551 public void onReceive(Context context, Intent intent) {
552 String action = intent.getAction();
553
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800554 boolean queryRestart = false;
Daniel Sandler26ece572012-06-01 15:38:46 -0400555 boolean packageChanged = false;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800556
Mike Lockwood541c9942011-06-12 19:35:45 -0400557 if (action.equals(Intent.ACTION_PACKAGE_REMOVED)
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800558 || action.equals(Intent.ACTION_PACKAGE_RESTARTED)
Daniel Sandler26ece572012-06-01 15:38:46 -0400559 || (packageChanged=action.equals(Intent.ACTION_PACKAGE_CHANGED))
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800560 || (queryRestart=action.equals(Intent.ACTION_QUERY_PACKAGE_RESTART))
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800561 || action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800562 String pkgList[] = null;
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800563 if (action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800564 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800565 } else if (queryRestart) {
566 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800567 } else {
568 Uri uri = intent.getData();
569 if (uri == null) {
570 return;
571 }
572 String pkgName = uri.getSchemeSpecificPart();
573 if (pkgName == null) {
574 return;
575 }
Daniel Sandler26ece572012-06-01 15:38:46 -0400576 if (packageChanged) {
577 // We cancel notifications for packages which have just been disabled
578 final int enabled = mContext.getPackageManager()
579 .getApplicationEnabledSetting(pkgName);
580 if (enabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
581 || enabled == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
582 return;
583 }
584 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800585 pkgList = new String[]{pkgName};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800587 if (pkgList != null && (pkgList.length > 0)) {
588 for (String pkgName : pkgList) {
Dianne Hackborn41203752012-08-31 14:05:51 -0700589 cancelAllNotificationsInt(pkgName, 0, 0, !queryRestart,
590 UserHandle.USER_ALL);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800591 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800592 }
Mike Lockwood63b5ad92011-08-30 09:55:30 -0400593 } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
594 // Keep track of screen on/off state, but do not turn off the notification light
595 // until user passes through the lock screen or views the notification.
596 mScreenOn = true;
597 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
598 mScreenOn = false;
Daniel Sandlere96ffb12010-03-11 13:38:06 -0500599 } else if (action.equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
Mike Lockwood63b5ad92011-08-30 09:55:30 -0400600 mInCall = (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
601 TelephonyManager.EXTRA_STATE_OFFHOOK));
Daniel Sandlere96ffb12010-03-11 13:38:06 -0500602 updateNotificationPulse();
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700603 } else if (action.equals(Intent.ACTION_USER_STOPPED)) {
604 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
605 if (userHandle >= 0) {
Dianne Hackborn41203752012-08-31 14:05:51 -0700606 cancelAllNotificationsInt(null, 0, 0, true, userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700607 }
Mike Lockwood63b5ad92011-08-30 09:55:30 -0400608 } else if (action.equals(Intent.ACTION_USER_PRESENT)) {
609 // turn off LED when user passes through lock screen
610 mNotificationLight.turnOff();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800611 }
612 }
613 };
614
Dianne Hackborn1dac2772009-06-26 18:16:48 -0700615 class SettingsObserver extends ContentObserver {
616 SettingsObserver(Handler handler) {
617 super(handler);
618 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800619
Dianne Hackborn1dac2772009-06-26 18:16:48 -0700620 void observe() {
621 ContentResolver resolver = mContext.getContentResolver();
Mike Lockwoodc22404a2009-12-02 11:15:02 -0500622 resolver.registerContentObserver(Settings.System.getUriFor(
623 Settings.System.NOTIFICATION_LIGHT_PULSE), false, this);
Dianne Hackborn1dac2772009-06-26 18:16:48 -0700624 update();
625 }
626
627 @Override public void onChange(boolean selfChange) {
628 update();
629 }
630
631 public void update() {
632 ContentResolver resolver = mContext.getContentResolver();
Mike Lockwoodc22404a2009-12-02 11:15:02 -0500633 boolean pulseEnabled = Settings.System.getInt(resolver,
634 Settings.System.NOTIFICATION_LIGHT_PULSE, 0) != 0;
635 if (mNotificationPulseEnabled != pulseEnabled) {
636 mNotificationPulseEnabled = pulseEnabled;
637 updateNotificationPulse();
638 }
Dianne Hackborn1dac2772009-06-26 18:16:48 -0700639 }
640 }
Mike Lockwoodc22404a2009-12-02 11:15:02 -0500641
Daniel Sandleredbb3802012-11-13 20:49:47 -0800642 static long[] getLongArray(Resources r, int resid, int maxlen, long[] def) {
643 int[] ar = r.getIntArray(resid);
644 if (ar == null) {
645 return def;
646 }
647 final int len = ar.length > maxlen ? maxlen : ar.length;
648 long[] out = new long[len];
649 for (int i=0; i<len; i++) {
650 out[i] = ar[i];
651 }
652 return out;
653 }
654
Joe Onorato089de882010-04-12 08:18:45 -0700655 NotificationManagerService(Context context, StatusBarManagerService statusBar,
Mike Lockwood3a322132009-11-24 00:30:52 -0500656 LightsService lights)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 {
658 super();
659 mContext = context;
Jeff Brownc2346132012-04-13 01:55:38 -0700660 mVibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800661 mAm = ActivityManagerNative.getDefault();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 mToastQueue = new ArrayList<ToastRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 mHandler = new WorkerHandler();
San Mehat3ee13172010-02-04 20:54:43 -0800664
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500665 mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
666
667 importOldBlockDb();
Daniel Sandler0da673f2012-04-11 12:33:16 -0400668
Joe Onorato089de882010-04-12 08:18:45 -0700669 mStatusBar = statusBar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800670 statusBar.setNotificationCallbacks(mNotificationCallbacks);
671
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500672 mNotificationLight = lights.getLight(LightsService.LIGHT_ID_NOTIFICATIONS);
673 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
674
Mike Lockwood670f9322010-01-20 12:13:36 -0500675 Resources resources = mContext.getResources();
676 mDefaultNotificationColor = resources.getColor(
677 com.android.internal.R.color.config_defaultNotificationColor);
678 mDefaultNotificationLedOn = resources.getInteger(
679 com.android.internal.R.integer.config_defaultNotificationLedOn);
680 mDefaultNotificationLedOff = resources.getInteger(
681 com.android.internal.R.integer.config_defaultNotificationLedOff);
682
Daniel Sandleredbb3802012-11-13 20:49:47 -0800683 mDefaultVibrationPattern = getLongArray(resources,
684 com.android.internal.R.array.config_defaultNotificationVibePattern,
685 VIBRATE_PATTERN_MAXLEN,
686 DEFAULT_VIBRATE_PATTERN);
687
688 mFallbackVibrationPattern = getLongArray(resources,
689 com.android.internal.R.array.config_notificationFallbackVibePattern,
690 VIBRATE_PATTERN_MAXLEN,
691 DEFAULT_VIBRATE_PATTERN);
692
Joe Onorato39f5b6a2009-07-23 12:29:19 -0400693 // Don't start allowing notifications until the setup wizard has run once.
694 // After that, including subsequent boots, init with notifications turned on.
695 // This works on the first boot because the setup wizard will toggle this
696 // flag at least once and we'll go back to 0 after that.
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700697 if (0 == Settings.Global.getInt(mContext.getContentResolver(),
698 Settings.Global.DEVICE_PROVISIONED, 0)) {
Joe Onorato39f5b6a2009-07-23 12:29:19 -0400699 mDisabledNotifications = StatusBarManager.DISABLE_NOTIFICATION_ALERTS;
700 }
701
Mike Lockwood35e16bf2010-11-30 19:53:36 -0500702 // register for various Intents
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 IntentFilter filter = new IntentFilter();
Mike Lockwoodc22404a2009-12-02 11:15:02 -0500704 filter.addAction(Intent.ACTION_SCREEN_ON);
705 filter.addAction(Intent.ACTION_SCREEN_OFF);
Daniel Sandlere96ffb12010-03-11 13:38:06 -0500706 filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
Mike Lockwood63b5ad92011-08-30 09:55:30 -0400707 filter.addAction(Intent.ACTION_USER_PRESENT);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700708 filter.addAction(Intent.ACTION_USER_STOPPED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 mContext.registerReceiver(mIntentReceiver, filter);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800710 IntentFilter pkgFilter = new IntentFilter();
711 pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
Daniel Sandleraac0eb02011-08-06 22:51:56 -0400712 pkgFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800713 pkgFilter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
714 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
715 pkgFilter.addDataScheme("package");
716 mContext.registerReceiver(mIntentReceiver, pkgFilter);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800717 IntentFilter sdFilter = new IntentFilter(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800718 mContext.registerReceiver(mIntentReceiver, sdFilter);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800719
Mike Lockwoodc22404a2009-12-02 11:15:02 -0500720 SettingsObserver observer = new SettingsObserver(mHandler);
721 observer.observe();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 }
723
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500724 /**
725 * Read the old XML-based app block database and import those blockages into the AppOps system.
726 */
727 private void importOldBlockDb() {
728 loadBlockDb();
729
730 PackageManager pm = mContext.getPackageManager();
731 for (String pkg : mBlockedPackages) {
732 PackageInfo info = null;
733 try {
734 info = pm.getPackageInfo(pkg, 0);
735 setNotificationsEnabledForPackage(pkg, info.applicationInfo.uid, false);
736 } catch (NameNotFoundException e) {
737 // forget you
738 }
739 }
740 mBlockedPackages.clear();
741 if (mPolicyFile != null) {
742 mPolicyFile.delete();
743 }
744 }
745
Joe Onorato30275482009-07-08 17:09:14 -0700746 void systemReady() {
Jeff Sharkey098d5802012-04-26 17:30:34 -0700747 mAudioService = IAudioService.Stub.asInterface(
748 ServiceManager.getService(Context.AUDIO_SERVICE));
749
Joe Onorato30275482009-07-08 17:09:14 -0700750 // no beeping until we're basically done booting
751 mSystemReady = true;
752 }
753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 // Toasts
755 // ============================================================================
756 public void enqueueToast(String pkg, ITransientNotification callback, int duration)
757 {
Daniel Sandlera7035902010-03-30 15:45:31 -0400758 if (DBG) Slog.i(TAG, "enqueueToast pkg=" + pkg + " callback=" + callback + " duration=" + duration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759
760 if (pkg == null || callback == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800761 Slog.e(TAG, "Not doing toast. pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 return ;
763 }
764
Daniel Sandler0da673f2012-04-11 12:33:16 -0400765 final boolean isSystemToast = ("android".equals(pkg));
766
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500767 if (ENABLE_BLOCKED_TOASTS && !noteNotificationOp(pkg, Binder.getCallingUid())) {
768 if (!isSystemToast) {
769 Slog.e(TAG, "Suppressing toast from package " + pkg + " by user request.");
770 return;
771 }
Daniel Sandler0da673f2012-04-11 12:33:16 -0400772 }
773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 synchronized (mToastQueue) {
775 int callingPid = Binder.getCallingPid();
776 long callingId = Binder.clearCallingIdentity();
777 try {
778 ToastRecord record;
779 int index = indexOfToastLocked(pkg, callback);
780 // If it's already in the queue, we update it in place, we don't
781 // move it to the end of the queue.
782 if (index >= 0) {
783 record = mToastQueue.get(index);
784 record.update(duration);
785 } else {
Vairavan Srinivasanf9eb06c2011-01-21 18:08:36 -0800786 // Limit the number of toasts that any given package except the android
787 // package can enqueue. Prevents DOS attacks and deals with leaks.
Daniel Sandler0da673f2012-04-11 12:33:16 -0400788 if (!isSystemToast) {
Vairavan Srinivasanf9eb06c2011-01-21 18:08:36 -0800789 int count = 0;
790 final int N = mToastQueue.size();
791 for (int i=0; i<N; i++) {
792 final ToastRecord r = mToastQueue.get(i);
793 if (r.pkg.equals(pkg)) {
794 count++;
795 if (count >= MAX_PACKAGE_NOTIFICATIONS) {
796 Slog.e(TAG, "Package has already posted " + count
797 + " toasts. Not showing more. Package=" + pkg);
798 return;
799 }
800 }
801 }
802 }
803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800804 record = new ToastRecord(callingPid, pkg, callback, duration);
805 mToastQueue.add(record);
806 index = mToastQueue.size() - 1;
807 keepProcessAliveLocked(callingPid);
808 }
809 // If it's at index 0, it's the current toast. It doesn't matter if it's
810 // new or just been updated. Call back and tell it to show itself.
811 // If the callback fails, this will remove it from the list, so don't
812 // assume that it's valid after this.
813 if (index == 0) {
814 showNextToastLocked();
815 }
816 } finally {
817 Binder.restoreCallingIdentity(callingId);
818 }
819 }
820 }
821
822 public void cancelToast(String pkg, ITransientNotification callback) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800823 Slog.i(TAG, "cancelToast pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824
825 if (pkg == null || callback == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800826 Slog.e(TAG, "Not cancelling notification. pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 return ;
828 }
829
830 synchronized (mToastQueue) {
831 long callingId = Binder.clearCallingIdentity();
832 try {
833 int index = indexOfToastLocked(pkg, callback);
834 if (index >= 0) {
835 cancelToastLocked(index);
836 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800837 Slog.w(TAG, "Toast already cancelled. pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 }
839 } finally {
840 Binder.restoreCallingIdentity(callingId);
841 }
842 }
843 }
844
845 private void showNextToastLocked() {
846 ToastRecord record = mToastQueue.get(0);
847 while (record != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800848 if (DBG) Slog.d(TAG, "Show pkg=" + record.pkg + " callback=" + record.callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 try {
850 record.callback.show();
851 scheduleTimeoutLocked(record, false);
852 return;
853 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800854 Slog.w(TAG, "Object died trying to show notification " + record.callback
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 + " in package " + record.pkg);
856 // remove it from the list and let the process die
857 int index = mToastQueue.indexOf(record);
858 if (index >= 0) {
859 mToastQueue.remove(index);
860 }
861 keepProcessAliveLocked(record.pid);
862 if (mToastQueue.size() > 0) {
863 record = mToastQueue.get(0);
864 } else {
865 record = null;
866 }
867 }
868 }
869 }
870
871 private void cancelToastLocked(int index) {
872 ToastRecord record = mToastQueue.get(index);
873 try {
874 record.callback.hide();
875 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800876 Slog.w(TAG, "Object died trying to hide notification " + record.callback
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 + " in package " + record.pkg);
878 // don't worry about this, we're about to remove it from
879 // the list anyway
880 }
881 mToastQueue.remove(index);
882 keepProcessAliveLocked(record.pid);
883 if (mToastQueue.size() > 0) {
884 // Show the next one. If the callback fails, this will remove
885 // it from the list, so don't assume that the list hasn't changed
886 // after this point.
887 showNextToastLocked();
888 }
889 }
890
891 private void scheduleTimeoutLocked(ToastRecord r, boolean immediate)
892 {
893 Message m = Message.obtain(mHandler, MESSAGE_TIMEOUT, r);
894 long delay = immediate ? 0 : (r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY);
895 mHandler.removeCallbacksAndMessages(r);
896 mHandler.sendMessageDelayed(m, delay);
897 }
898
899 private void handleTimeout(ToastRecord record)
900 {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800901 if (DBG) Slog.d(TAG, "Timeout pkg=" + record.pkg + " callback=" + record.callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 synchronized (mToastQueue) {
903 int index = indexOfToastLocked(record.pkg, record.callback);
904 if (index >= 0) {
905 cancelToastLocked(index);
906 }
907 }
908 }
909
910 // lock on mToastQueue
911 private int indexOfToastLocked(String pkg, ITransientNotification callback)
912 {
913 IBinder cbak = callback.asBinder();
914 ArrayList<ToastRecord> list = mToastQueue;
915 int len = list.size();
916 for (int i=0; i<len; i++) {
917 ToastRecord r = list.get(i);
918 if (r.pkg.equals(pkg) && r.callback.asBinder() == cbak) {
919 return i;
920 }
921 }
922 return -1;
923 }
924
925 // lock on mToastQueue
926 private void keepProcessAliveLocked(int pid)
927 {
928 int toastCount = 0; // toasts from this pid
929 ArrayList<ToastRecord> list = mToastQueue;
930 int N = list.size();
931 for (int i=0; i<N; i++) {
932 ToastRecord r = list.get(i);
933 if (r.pid == pid) {
934 toastCount++;
935 }
936 }
937 try {
938 mAm.setProcessForeground(mForegroundToken, pid, toastCount > 0);
939 } catch (RemoteException e) {
940 // Shouldn't happen.
941 }
942 }
943
944 private final class WorkerHandler extends Handler
945 {
946 @Override
947 public void handleMessage(Message msg)
948 {
949 switch (msg.what)
950 {
951 case MESSAGE_TIMEOUT:
952 handleTimeout((ToastRecord)msg.obj);
953 break;
954 }
955 }
956 }
957
958
959 // Notifications
960 // ============================================================================
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800961 public void enqueueNotificationWithTag(String pkg, String basePkg, String tag, int id,
962 Notification notification, int[] idOut, int userId)
Fred Quintana6ecaff12009-09-25 14:23:13 -0700963 {
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800964 enqueueNotificationInternal(pkg, basePkg, Binder.getCallingUid(), Binder.getCallingPid(),
Dianne Hackborn41203752012-08-31 14:05:51 -0700965 tag, id, notification, idOut, userId);
Daniel Sandlerd0a2f862010-08-03 15:29:31 -0400966 }
Daniel Sandler2561b0b2012-02-13 21:04:12 -0500967
968 private final static int clamp(int x, int low, int high) {
969 return (x < low) ? low : ((x > high) ? high : x);
Daniel Sandlere40451a2011-02-03 14:51:35 -0500970 }
971
Daniel Sandlerd0a2f862010-08-03 15:29:31 -0400972 // Not exposed via Binder; for system use only (otherwise malicious apps could spoof the
973 // uid/pid of another application)
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800974 public void enqueueNotificationInternal(String pkg, String basePkg, int callingUid,
975 int callingPid, String tag, int id, Notification notification, int[] idOut, int userId)
Daniel Sandlerd0a2f862010-08-03 15:29:31 -0400976 {
Daniel Sandler0da673f2012-04-11 12:33:16 -0400977 if (DBG) {
978 Slog.v(TAG, "enqueueNotificationInternal: pkg=" + pkg + " id=" + id + " notification=" + notification);
979 }
980 checkCallerIsSystemOrSameApp(pkg);
981 final boolean isSystemNotification = ("android".equals(pkg));
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800982
Dianne Hackborn41203752012-08-31 14:05:51 -0700983 userId = ActivityManager.handleIncomingUser(callingPid,
Amith Yamasani2c7ebea2012-10-30 15:28:27 -0700984 callingUid, userId, true, false, "enqueueNotification", pkg);
Jeff Sharkey65c4a2b2012-09-25 17:22:27 -0700985 final UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -0700986
Joe Onoratobd73d012010-06-04 11:44:54 -0700987 // Limit the number of notifications that any given package except the android
988 // package can enqueue. Prevents DOS attacks and deals with leaks.
Daniel Sandler0da673f2012-04-11 12:33:16 -0400989 if (!isSystemNotification) {
Joe Onoratobd73d012010-06-04 11:44:54 -0700990 synchronized (mNotificationList) {
991 int count = 0;
992 final int N = mNotificationList.size();
993 for (int i=0; i<N; i++) {
994 final NotificationRecord r = mNotificationList.get(i);
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500995 if (r.sbn.pkg.equals(pkg) && r.sbn.getUserId() == userId) {
Joe Onoratobd73d012010-06-04 11:44:54 -0700996 count++;
997 if (count >= MAX_PACKAGE_NOTIFICATIONS) {
998 Slog.e(TAG, "Package has already posted " + count
999 + " notifications. Not showing more. package=" + pkg);
1000 return;
1001 }
1002 }
1003 }
1004 }
1005 }
1006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 // This conditional is a dirty hack to limit the logging done on
1008 // behalf of the download manager without affecting other apps.
1009 if (!pkg.equals("com.android.providers.downloads")
1010 || Log.isLoggable("DownloadManager", Log.VERBOSE)) {
Daniel Sandler321e9c52012-10-12 10:59:26 -07001011 EventLog.writeEvent(EventLogTags.NOTIFICATION_ENQUEUE, pkg, id, tag, userId,
Daniel Sandlerb64cb882011-11-29 23:48:29 -05001012 notification.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 }
1014
1015 if (pkg == null || notification == null) {
1016 throw new IllegalArgumentException("null not allowed: pkg=" + pkg
1017 + " id=" + id + " notification=" + notification);
1018 }
1019 if (notification.icon != 0) {
1020 if (notification.contentView == null) {
1021 throw new IllegalArgumentException("contentView required: pkg=" + pkg
1022 + " id=" + id + " notification=" + notification);
1023 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 }
1025
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001026 // === Scoring ===
Daniel Sandler0da673f2012-04-11 12:33:16 -04001027
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001028 // 0. Sanitize inputs
1029 notification.priority = clamp(notification.priority, Notification.PRIORITY_MIN, Notification.PRIORITY_MAX);
1030 // Migrate notification flags to scores
1031 if (0 != (notification.flags & Notification.FLAG_HIGH_PRIORITY)) {
1032 if (notification.priority < Notification.PRIORITY_MAX) notification.priority = Notification.PRIORITY_MAX;
Daniel Sandler49a2ad12012-03-28 15:46:39 -04001033 } else if (SCORE_ONGOING_HIGHER && 0 != (notification.flags & Notification.FLAG_ONGOING_EVENT)) {
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001034 if (notification.priority < Notification.PRIORITY_HIGH) notification.priority = Notification.PRIORITY_HIGH;
1035 }
Daniel Sandler0da673f2012-04-11 12:33:16 -04001036
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001037 // 1. initial score: buckets of 10, around the app
Daniel Sandler0da673f2012-04-11 12:33:16 -04001038 int score = notification.priority * NOTIFICATION_PRIORITY_MULTIPLIER; //[-20..20]
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001039
Daniel Sandler0da673f2012-04-11 12:33:16 -04001040 // 2. Consult external heuristics (TBD)
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001041
Daniel Sandler0da673f2012-04-11 12:33:16 -04001042 // 3. Apply local rules
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001043
1044 // blocked apps
Daniel Sandler4a900acd2013-01-30 14:04:10 -05001045 if (ENABLE_BLOCKED_NOTIFICATIONS && !noteNotificationOp(pkg, callingUid)) {
1046 if (!isSystemNotification) {
1047 score = JUNK_SCORE;
1048 Slog.e(TAG, "Suppressing notification from package " + pkg + " by user request.");
1049 }
Daniel Sandler0da673f2012-04-11 12:33:16 -04001050 }
1051
1052 if (DBG) {
1053 Slog.v(TAG, "Assigned score=" + score + " to " + notification);
1054 }
1055
1056 if (score < SCORE_DISPLAY_THRESHOLD) {
1057 // Notification will be blocked because the score is too low.
1058 return;
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001059 }
1060
Daniel Sandler526fa0e2012-12-04 14:51:50 -05001061 // Should this notification make noise, vibe, or use the LED?
1062 final boolean canInterrupt = (score >= SCORE_INTERRUPTION_THRESHOLD);
1063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 synchronized (mNotificationList) {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001065 final StatusBarNotification n = new StatusBarNotification(
1066 pkg, id, tag, callingUid, callingPid, score, notification, user);
1067 NotificationRecord r = new NotificationRecord(n);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 NotificationRecord old = null;
1069
Dianne Hackborn41203752012-08-31 14:05:51 -07001070 int index = indexOfNotificationLocked(pkg, tag, id, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 if (index < 0) {
1072 mNotificationList.add(r);
1073 } else {
1074 old = mNotificationList.remove(index);
1075 mNotificationList.add(index, r);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001076 // Make sure we don't lose the foreground service state.
1077 if (old != null) {
1078 notification.flags |=
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001079 old.getNotification().flags&Notification.FLAG_FOREGROUND_SERVICE;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001082
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001083 // Ensure if this is a foreground service that the proper additional
1084 // flags are set.
1085 if ((notification.flags&Notification.FLAG_FOREGROUND_SERVICE) != 0) {
1086 notification.flags |= Notification.FLAG_ONGOING_EVENT
1087 | Notification.FLAG_NO_CLEAR;
1088 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001089
Svetoslav Ganovc31ed392012-10-10 14:58:28 -07001090 final int currentUser;
1091 final long token = Binder.clearCallingIdentity();
1092 try {
1093 currentUser = ActivityManager.getCurrentUser();
1094 } finally {
1095 Binder.restoreCallingIdentity(token);
1096 }
1097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 if (notification.icon != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 if (old != null && old.statusBarKey != null) {
1100 r.statusBarKey = old.statusBarKey;
1101 long identity = Binder.clearCallingIdentity();
1102 try {
Joe Onorato18e69df2010-05-17 22:26:12 -07001103 mStatusBar.updateNotification(r.statusBarKey, n);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 }
1105 finally {
1106 Binder.restoreCallingIdentity(identity);
1107 }
1108 } else {
1109 long identity = Binder.clearCallingIdentity();
1110 try {
Joe Onorato18e69df2010-05-17 22:26:12 -07001111 r.statusBarKey = mStatusBar.addNotification(n);
Daniel Sandler526fa0e2012-12-04 14:51:50 -05001112 if ((n.notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0
1113 && canInterrupt) {
Mike Lockwoodece18ef2012-02-13 20:42:19 -08001114 mAttentionLight.pulse();
1115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 }
1117 finally {
1118 Binder.restoreCallingIdentity(identity);
1119 }
1120 }
Svetoslav Ganovc31ed392012-10-10 14:58:28 -07001121 // Send accessibility events only for the current user.
1122 if (currentUser == userId) {
1123 sendAccessibilityEvent(notification, pkg);
1124 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001125
1126 // finally, keep some of this information around for later use
1127 mArchive.record(n);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 } else {
Daniel Sandlere40451a2011-02-03 14:51:35 -05001129 Slog.e(TAG, "Ignoring notification with icon==0: " + notification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 if (old != null && old.statusBarKey != null) {
1131 long identity = Binder.clearCallingIdentity();
1132 try {
Joe Onorato0cbda992010-05-02 16:28:15 -07001133 mStatusBar.removeNotification(old.statusBarKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 }
1135 finally {
1136 Binder.restoreCallingIdentity(identity);
1137 }
1138 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001139 return; // do not play sounds, show lights, etc. for invalid notifications
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001140 }
1141
1142 // If we're not supposed to beep, vibrate, etc. then don't.
1143 if (((mDisabledNotifications & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) == 0)
1144 && (!(old != null
Joe Onorato30275482009-07-08 17:09:14 -07001145 && (notification.flags & Notification.FLAG_ONLY_ALERT_ONCE) != 0 ))
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001146 && (r.getUserId() == UserHandle.USER_ALL ||
1147 (r.getUserId() == userId && r.getUserId() == currentUser))
Daniel Sandler526fa0e2012-12-04 14:51:50 -05001148 && canInterrupt
Joe Onorato30275482009-07-08 17:09:14 -07001149 && mSystemReady) {
Eric Laurent524dc042009-11-27 05:07:55 -08001150
1151 final AudioManager audioManager = (AudioManager) mContext
1152 .getSystemService(Context.AUDIO_SERVICE);
Daniel Sandlerd4d2de22012-11-14 11:25:46 -08001153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 // sound
1155 final boolean useDefaultSound =
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001156 (notification.defaults & Notification.DEFAULT_SOUND) != 0;
Daniel Sandlerd4d2de22012-11-14 11:25:46 -08001157
1158 Uri soundUri = null;
1159 boolean hasValidSound = false;
1160
1161 if (useDefaultSound) {
1162 soundUri = Settings.System.DEFAULT_NOTIFICATION_URI;
1163
1164 // check to see if the default notification sound is silent
1165 ContentResolver resolver = mContext.getContentResolver();
1166 hasValidSound = Settings.System.getString(resolver,
1167 Settings.System.NOTIFICATION_SOUND) != null;
1168 } else if (notification.sound != null) {
1169 soundUri = notification.sound;
1170 hasValidSound = (soundUri != null);
1171 }
1172
1173 if (hasValidSound) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 boolean looping = (notification.flags & Notification.FLAG_INSISTENT) != 0;
1175 int audioStreamType;
1176 if (notification.audioStreamType >= 0) {
1177 audioStreamType = notification.audioStreamType;
1178 } else {
1179 audioStreamType = DEFAULT_STREAM_TYPE;
1180 }
1181 mSoundNotification = r;
Eric Laurent524dc042009-11-27 05:07:55 -08001182 // do not play notifications if stream volume is 0
Jean-Michel Trivid6770542012-10-10 12:03:41 -07001183 // (typically because ringer mode is silent) or if speech recognition is active.
1184 if ((audioManager.getStreamVolume(audioStreamType) != 0)
1185 && !audioManager.isSpeechRecognitionActive()) {
Jeff Sharkey098d5802012-04-26 17:30:34 -07001186 final long identity = Binder.clearCallingIdentity();
Eric Laurent524dc042009-11-27 05:07:55 -08001187 try {
Jeff Sharkey098d5802012-04-26 17:30:34 -07001188 final IRingtonePlayer player = mAudioService.getRingtonePlayer();
1189 if (player != null) {
Daniel Sandlerd4d2de22012-11-14 11:25:46 -08001190 player.playAsync(soundUri, user, looping, audioStreamType);
Jeff Sharkey098d5802012-04-26 17:30:34 -07001191 }
1192 } catch (RemoteException e) {
1193 } finally {
Eric Laurent524dc042009-11-27 05:07:55 -08001194 Binder.restoreCallingIdentity(identity);
1195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 }
1197 }
1198
1199 // vibrate
Daniel Sandleredbb3802012-11-13 20:49:47 -08001200 // Does the notification want to specify its own vibration?
1201 final boolean hasCustomVibrate = notification.vibrate != null;
1202
David Agnew71789e12012-11-09 23:03:26 -05001203 // 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 -05001204 // and no other vibration is specified, we fall back to vibration
David Agnew71789e12012-11-09 23:03:26 -05001205 final boolean convertSoundToVibration =
Daniel Sandleredbb3802012-11-13 20:49:47 -08001206 !hasCustomVibrate
Daniel Sandlerd4d2de22012-11-14 11:25:46 -08001207 && hasValidSound
David Agnew71789e12012-11-09 23:03:26 -05001208 && (audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE);
1209
Daniel Sandler4a7a9b92012-11-20 12:59:41 -05001210 // The DEFAULT_VIBRATE flag trumps any custom vibration AND the fallback.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 final boolean useDefaultVibrate =
Daniel Sandleredbb3802012-11-13 20:49:47 -08001212 (notification.defaults & Notification.DEFAULT_VIBRATE) != 0;
David Agnew71789e12012-11-09 23:03:26 -05001213
Daniel Sandleredbb3802012-11-13 20:49:47 -08001214 if ((useDefaultVibrate || convertSoundToVibration || hasCustomVibrate)
Eric Laurentbffc3d12012-05-07 17:43:49 -07001215 && !(audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 mVibrateNotification = r;
1217
Daniel Sandleredbb3802012-11-13 20:49:47 -08001218 if (useDefaultVibrate || convertSoundToVibration) {
1219 // Escalate privileges so we can use the vibrator even if the notifying app
1220 // does not have the VIBRATE permission.
1221 long identity = Binder.clearCallingIdentity();
1222 try {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001223 mVibrator.vibrate(r.sbn.uid, r.sbn.basePkg,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001224 useDefaultVibrate ? mDefaultVibrationPattern
1225 : mFallbackVibrationPattern,
Daniel Sandleredbb3802012-11-13 20:49:47 -08001226 ((notification.flags & Notification.FLAG_INSISTENT) != 0) ? 0: -1);
1227 } finally {
1228 Binder.restoreCallingIdentity(identity);
1229 }
1230 } else if (notification.vibrate.length > 1) {
1231 // If you want your own vibration pattern, you need the VIBRATE permission
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001232 mVibrator.vibrate(r.sbn.uid, r.sbn.basePkg, notification.vibrate,
Daniel Sandleredbb3802012-11-13 20:49:47 -08001233 ((notification.flags & Notification.FLAG_INSISTENT) != 0) ? 0: -1);
1234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 }
1236 }
1237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 // light
1239 // the most recent thing gets the light
1240 mLights.remove(old);
1241 if (mLedNotification == old) {
1242 mLedNotification = null;
1243 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001244 //Slog.i(TAG, "notification.lights="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 // + ((old.notification.lights.flags & Notification.FLAG_SHOW_LIGHTS) != 0));
Daniel Sandler526fa0e2012-12-04 14:51:50 -05001246 if ((notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0
1247 && canInterrupt) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 mLights.add(r);
1249 updateLightsLocked();
1250 } else {
1251 if (old != null
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001252 && ((old.getFlags() & Notification.FLAG_SHOW_LIGHTS) != 0)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 updateLightsLocked();
1254 }
1255 }
1256 }
1257
1258 idOut[0] = id;
1259 }
1260
Joe Onorato30275482009-07-08 17:09:14 -07001261 private void sendAccessibilityEvent(Notification notification, CharSequence packageName) {
svetoslavganov75986cf2009-05-14 22:28:01 -07001262 AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
1263 if (!manager.isEnabled()) {
1264 return;
1265 }
1266
1267 AccessibilityEvent event =
1268 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED);
1269 event.setPackageName(packageName);
1270 event.setClassName(Notification.class.getName());
1271 event.setParcelableData(notification);
1272 CharSequence tickerText = notification.tickerText;
1273 if (!TextUtils.isEmpty(tickerText)) {
1274 event.getText().add(tickerText);
1275 }
1276
1277 manager.sendAccessibilityEvent(event);
1278 }
1279
Joe Onorato46439ce2010-11-19 13:56:21 -08001280 private void cancelNotificationLocked(NotificationRecord r, boolean sendDelete) {
1281 // tell the app
1282 if (sendDelete) {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001283 if (r.getNotification().deleteIntent != null) {
Joe Onorato46439ce2010-11-19 13:56:21 -08001284 try {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001285 r.getNotification().deleteIntent.send();
Joe Onorato46439ce2010-11-19 13:56:21 -08001286 } catch (PendingIntent.CanceledException ex) {
1287 // do nothing - there's no relevant way to recover, and
1288 // no reason to let this propagate
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001289 Slog.w(TAG, "canceled PendingIntent for " + r.sbn.pkg, ex);
Joe Onorato46439ce2010-11-19 13:56:21 -08001290 }
1291 }
1292 }
1293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 // status bar
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001295 if (r.getNotification().icon != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 long identity = Binder.clearCallingIdentity();
1297 try {
Joe Onorato0cbda992010-05-02 16:28:15 -07001298 mStatusBar.removeNotification(r.statusBarKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 }
1300 finally {
1301 Binder.restoreCallingIdentity(identity);
1302 }
1303 r.statusBarKey = null;
1304 }
1305
1306 // sound
1307 if (mSoundNotification == r) {
1308 mSoundNotification = null;
Jeff Sharkey098d5802012-04-26 17:30:34 -07001309 final long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 try {
Jeff Sharkey098d5802012-04-26 17:30:34 -07001311 final IRingtonePlayer player = mAudioService.getRingtonePlayer();
1312 if (player != null) {
1313 player.stopAsync();
1314 }
1315 } catch (RemoteException e) {
1316 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 Binder.restoreCallingIdentity(identity);
1318 }
1319 }
1320
1321 // vibrate
1322 if (mVibrateNotification == r) {
1323 mVibrateNotification = null;
1324 long identity = Binder.clearCallingIdentity();
1325 try {
1326 mVibrator.cancel();
1327 }
1328 finally {
1329 Binder.restoreCallingIdentity(identity);
1330 }
1331 }
1332
1333 // light
1334 mLights.remove(r);
1335 if (mLedNotification == r) {
1336 mLedNotification = null;
1337 }
1338 }
1339
1340 /**
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001341 * Cancels a notification ONLY if it has all of the {@code mustHaveFlags}
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001342 * and none of the {@code mustNotHaveFlags}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 */
Fred Quintana6ecaff12009-09-25 14:23:13 -07001344 private void cancelNotification(String pkg, String tag, int id, int mustHaveFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07001345 int mustNotHaveFlags, boolean sendDelete, int userId) {
Daniel Sandler321e9c52012-10-12 10:59:26 -07001346 EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL, pkg, id, tag, userId,
Daniel Sandlerb64cb882011-11-29 23:48:29 -05001347 mustHaveFlags, mustNotHaveFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348
1349 synchronized (mNotificationList) {
Dianne Hackborn41203752012-08-31 14:05:51 -07001350 int index = indexOfNotificationLocked(pkg, tag, id, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 if (index >= 0) {
Fred Quintana6ecaff12009-09-25 14:23:13 -07001352 NotificationRecord r = mNotificationList.get(index);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001353
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001354 if ((r.getNotification().flags & mustHaveFlags) != mustHaveFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 return;
1356 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001357 if ((r.getNotification().flags & mustNotHaveFlags) != 0) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001358 return;
1359 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 mNotificationList.remove(index);
1362
Joe Onorato46439ce2010-11-19 13:56:21 -08001363 cancelNotificationLocked(r, sendDelete);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 updateLightsLocked();
1365 }
1366 }
1367 }
1368
1369 /**
Daniel Sandler321e9c52012-10-12 10:59:26 -07001370 * Determine whether the userId applies to the notification in question, either because
1371 * they match exactly, or one of them is USER_ALL (which is treated as a wildcard).
1372 */
1373 private boolean notificationMatchesUserId(NotificationRecord r, int userId) {
1374 return
1375 // looking for USER_ALL notifications? match everything
1376 userId == UserHandle.USER_ALL
1377 // a notification sent to USER_ALL matches any query
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001378 || r.getUserId() == UserHandle.USER_ALL
Daniel Sandler321e9c52012-10-12 10:59:26 -07001379 // an exact user match
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001380 || r.getUserId() == userId;
Daniel Sandler321e9c52012-10-12 10:59:26 -07001381 }
1382
1383 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 * Cancels all notifications from a given package that have all of the
1385 * {@code mustHaveFlags}.
1386 */
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001387 boolean cancelAllNotificationsInt(String pkg, int mustHaveFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07001388 int mustNotHaveFlags, boolean doit, int userId) {
Daniel Sandler321e9c52012-10-12 10:59:26 -07001389 EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL_ALL, pkg, userId,
1390 mustHaveFlags, mustNotHaveFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391
1392 synchronized (mNotificationList) {
1393 final int N = mNotificationList.size();
1394 boolean canceledSomething = false;
1395 for (int i = N-1; i >= 0; --i) {
1396 NotificationRecord r = mNotificationList.get(i);
Daniel Sandler321e9c52012-10-12 10:59:26 -07001397 if (!notificationMatchesUserId(r, userId)) {
Dianne Hackborn41203752012-08-31 14:05:51 -07001398 continue;
1399 }
Amith Yamasani5ec00e92012-11-07 16:58:30 -08001400 // Don't remove notifications to all, if there's no package name specified
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001401 if (r.getUserId() == UserHandle.USER_ALL && pkg == null) {
Amith Yamasani5ec00e92012-11-07 16:58:30 -08001402 continue;
1403 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001404 if ((r.getFlags() & mustHaveFlags) != mustHaveFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 continue;
1406 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001407 if ((r.getFlags() & mustNotHaveFlags) != 0) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001408 continue;
1409 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001410 if (pkg != null && !r.sbn.pkg.equals(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 continue;
1412 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001413 canceledSomething = true;
1414 if (!doit) {
1415 return true;
1416 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 mNotificationList.remove(i);
Joe Onorato46439ce2010-11-19 13:56:21 -08001418 cancelNotificationLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 }
1420 if (canceledSomething) {
1421 updateLightsLocked();
1422 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001423 return canceledSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 }
1425 }
1426
Dianne Hackborn41203752012-08-31 14:05:51 -07001427 public void cancelNotificationWithTag(String pkg, String tag, int id, int userId) {
Daniel Sandler0da673f2012-04-11 12:33:16 -04001428 checkCallerIsSystemOrSameApp(pkg);
Dianne Hackborn41203752012-08-31 14:05:51 -07001429 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07001430 Binder.getCallingUid(), userId, true, false, "cancelNotificationWithTag", pkg);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001431 // Don't allow client applications to cancel foreground service notis.
Fred Quintana6ecaff12009-09-25 14:23:13 -07001432 cancelNotification(pkg, tag, id, 0,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001433 Binder.getCallingUid() == Process.SYSTEM_UID
Dianne Hackborn41203752012-08-31 14:05:51 -07001434 ? 0 : Notification.FLAG_FOREGROUND_SERVICE, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 }
1436
Dianne Hackborn41203752012-08-31 14:05:51 -07001437 public void cancelAllNotifications(String pkg, int userId) {
Daniel Sandler0da673f2012-04-11 12:33:16 -04001438 checkCallerIsSystemOrSameApp(pkg);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001439
Dianne Hackborn41203752012-08-31 14:05:51 -07001440 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07001441 Binder.getCallingUid(), userId, true, false, "cancelAllNotifications", pkg);
Dianne Hackborn41203752012-08-31 14:05:51 -07001442
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001443 // Calling from user space, don't allow the canceling of actively
1444 // running foreground services.
Dianne Hackborn41203752012-08-31 14:05:51 -07001445 cancelAllNotificationsInt(pkg, 0, Notification.FLAG_FOREGROUND_SERVICE, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 }
1447
Daniel Sandler0da673f2012-04-11 12:33:16 -04001448 void checkCallerIsSystem() {
1449 int uid = Binder.getCallingUid();
Dianne Hackborn0c380492012-08-20 17:23:30 -07001450 if (UserHandle.getAppId(uid) == Process.SYSTEM_UID || uid == 0) {
Daniel Sandler0da673f2012-04-11 12:33:16 -04001451 return;
1452 }
1453 throw new SecurityException("Disallowed call for uid " + uid);
1454 }
1455
1456 void checkCallerIsSystemOrSameApp(String pkg) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001457 int uid = Binder.getCallingUid();
Dianne Hackborn0c380492012-08-20 17:23:30 -07001458 if (UserHandle.getAppId(uid) == Process.SYSTEM_UID || uid == 0) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001459 return;
1460 }
1461 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07001462 ApplicationInfo ai = AppGlobals.getPackageManager().getApplicationInfo(
1463 pkg, 0, UserHandle.getCallingUserId());
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001464 if (!UserHandle.isSameApp(ai.uid, uid)) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001465 throw new SecurityException("Calling uid " + uid + " gave package"
1466 + pkg + " which is owned by uid " + ai.uid);
1467 }
Amith Yamasanif203aee2012-08-29 18:41:53 -07001468 } catch (RemoteException re) {
1469 throw new SecurityException("Unknown package " + pkg + "\n" + re);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001470 }
1471 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001472
Dianne Hackborn41203752012-08-31 14:05:51 -07001473 void cancelAll(int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 synchronized (mNotificationList) {
1475 final int N = mNotificationList.size();
1476 for (int i=N-1; i>=0; i--) {
1477 NotificationRecord r = mNotificationList.get(i);
1478
Daniel Sandler321e9c52012-10-12 10:59:26 -07001479 if (!notificationMatchesUserId(r, userId)) {
Dianne Hackborn41203752012-08-31 14:05:51 -07001480 continue;
1481 }
1482
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001483 if ((r.getFlags() & (Notification.FLAG_ONGOING_EVENT
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 | Notification.FLAG_NO_CLEAR)) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 mNotificationList.remove(i);
Joe Onorato46439ce2010-11-19 13:56:21 -08001486 cancelNotificationLocked(r, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 }
1488 }
1489
1490 updateLightsLocked();
1491 }
1492 }
1493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 // lock on mNotificationList
1495 private void updateLightsLocked()
1496 {
The Android Open Source Project10592532009-03-18 17:39:46 -07001497 // handle notification lights
1498 if (mLedNotification == null) {
1499 // get next notification, if any
1500 int n = mLights.size();
1501 if (n > 0) {
1502 mLedNotification = mLights.get(n-1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 }
1504 }
Mike Lockwoodc22404a2009-12-02 11:15:02 -05001505
Mike Lockwood63b5ad92011-08-30 09:55:30 -04001506 // Don't flash while we are in a call or screen is on
1507 if (mLedNotification == null || mInCall || mScreenOn) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001508 mNotificationLight.turnOff();
The Android Open Source Project10592532009-03-18 17:39:46 -07001509 } else {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001510 final Notification ledno = mLedNotification.sbn.notification;
1511 int ledARGB = ledno.ledARGB;
1512 int ledOnMS = ledno.ledOnMS;
1513 int ledOffMS = ledno.ledOffMS;
1514 if ((ledno.defaults & Notification.DEFAULT_LIGHTS) != 0) {
Mike Lockwood670f9322010-01-20 12:13:36 -05001515 ledARGB = mDefaultNotificationColor;
1516 ledOnMS = mDefaultNotificationLedOn;
1517 ledOffMS = mDefaultNotificationLedOff;
1518 }
1519 if (mNotificationPulseEnabled) {
1520 // pulse repeatedly
1521 mNotificationLight.setFlashing(ledARGB, LightsService.LIGHT_FLASH_TIMED,
1522 ledOnMS, ledOffMS);
Mike Lockwood670f9322010-01-20 12:13:36 -05001523 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001524 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 }
1526
1527 // lock on mNotificationList
Dianne Hackborn41203752012-08-31 14:05:51 -07001528 private int indexOfNotificationLocked(String pkg, String tag, int id, int userId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 {
1530 ArrayList<NotificationRecord> list = mNotificationList;
1531 final int len = list.size();
1532 for (int i=0; i<len; i++) {
1533 NotificationRecord r = list.get(i);
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001534 if (!notificationMatchesUserId(r, userId) || r.sbn.id != id) {
Dianne Hackborn41203752012-08-31 14:05:51 -07001535 continue;
1536 }
Fred Quintana6ecaff12009-09-25 14:23:13 -07001537 if (tag == null) {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001538 if (r.sbn.tag != null) {
Fred Quintana6ecaff12009-09-25 14:23:13 -07001539 continue;
1540 }
1541 } else {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001542 if (!tag.equals(r.sbn.tag)) {
Fred Quintana6ecaff12009-09-25 14:23:13 -07001543 continue;
1544 }
1545 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001546 if (r.sbn.pkg.equals(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 return i;
1548 }
1549 }
1550 return -1;
1551 }
1552
Mike Lockwoodc22404a2009-12-02 11:15:02 -05001553 private void updateNotificationPulse() {
1554 synchronized (mNotificationList) {
1555 updateLightsLocked();
1556 }
1557 }
1558
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559 // ======================================================================
1560 @Override
1561 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1562 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1563 != PackageManager.PERMISSION_GRANTED) {
1564 pw.println("Permission Denial: can't dump NotificationManager from from pid="
1565 + Binder.getCallingPid()
1566 + ", uid=" + Binder.getCallingUid());
1567 return;
1568 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 pw.println("Current Notification Manager state:");
1571
1572 int N;
1573
1574 synchronized (mToastQueue) {
1575 N = mToastQueue.size();
1576 if (N > 0) {
1577 pw.println(" Toast Queue:");
1578 for (int i=0; i<N; i++) {
1579 mToastQueue.get(i).dump(pw, " ");
1580 }
1581 pw.println(" ");
1582 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 }
1585
1586 synchronized (mNotificationList) {
1587 N = mNotificationList.size();
1588 if (N > 0) {
1589 pw.println(" Notification List:");
1590 for (int i=0; i<N; i++) {
1591 mNotificationList.get(i).dump(pw, " ", mContext);
1592 }
1593 pw.println(" ");
1594 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 N = mLights.size();
1597 if (N > 0) {
1598 pw.println(" Lights List:");
1599 for (int i=0; i<N; i++) {
1600 mLights.get(i).dump(pw, " ", mContext);
1601 }
1602 pw.println(" ");
1603 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 pw.println(" mSoundNotification=" + mSoundNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 pw.println(" mVibrateNotification=" + mVibrateNotification);
Joe Onorato39f5b6a2009-07-23 12:29:19 -04001607 pw.println(" mDisabledNotifications=0x" + Integer.toHexString(mDisabledNotifications));
1608 pw.println(" mSystemReady=" + mSystemReady);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 }
1610 }
1611}