blob: 13bf39f1d477150b17ede4c4bc87af0d0f784628 [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 }
Daniel Sandler78d0d252013-02-12 08:14:52 -0500238
239 public StatusBarNotification[] getArray(int count) {
240 if (count == 0) count = Archive.BUFFER_SIZE;
241 final StatusBarNotification[] a
242 = new StatusBarNotification[Math.min(count, mBuffer.size())];
243 Iterator<StatusBarNotification> iter = descendingIterator();
244 int i=0;
245 while (iter.hasNext() && i < count) {
246 a[i++] = iter.next();
247 }
248 return a;
249 }
250
251 public StatusBarNotification[] getArray(int count, String pkg, int userId) {
252 if (count == 0) count = Archive.BUFFER_SIZE;
253 final StatusBarNotification[] a
254 = new StatusBarNotification[Math.min(count, mBuffer.size())];
255 Iterator<StatusBarNotification> iter = filter(descendingIterator(), pkg, userId);
256 int i=0;
257 while (iter.hasNext() && i < count) {
258 a[i++] = iter.next();
259 }
260 return a;
261 }
262
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500263 }
264
265 Archive mArchive = new Archive();
266
Daniel Sandler0da673f2012-04-11 12:33:16 -0400267 private void loadBlockDb() {
268 synchronized(mBlockedPackages) {
269 if (mPolicyFile == null) {
270 File dir = new File("/data/system");
271 mPolicyFile = new AtomicFile(new File(dir, "notification_policy.xml"));
272
273 mBlockedPackages.clear();
274
275 FileInputStream infile = null;
276 try {
277 infile = mPolicyFile.openRead();
278 final XmlPullParser parser = Xml.newPullParser();
279 parser.setInput(infile, null);
280
281 int type;
282 String tag;
283 int version = DB_VERSION;
284 while ((type = parser.next()) != END_DOCUMENT) {
285 tag = parser.getName();
286 if (type == START_TAG) {
287 if (TAG_BODY.equals(tag)) {
288 version = Integer.parseInt(parser.getAttributeValue(null, ATTR_VERSION));
289 } else if (TAG_BLOCKED_PKGS.equals(tag)) {
290 while ((type = parser.next()) != END_DOCUMENT) {
291 tag = parser.getName();
292 if (TAG_PACKAGE.equals(tag)) {
293 mBlockedPackages.add(parser.getAttributeValue(null, ATTR_NAME));
294 } else if (TAG_BLOCKED_PKGS.equals(tag) && type == END_TAG) {
295 break;
296 }
297 }
298 }
299 }
300 }
301 } catch (FileNotFoundException e) {
302 // No data yet
303 } catch (IOException e) {
304 Log.wtf(TAG, "Unable to read blocked notifications database", e);
305 } catch (NumberFormatException e) {
306 Log.wtf(TAG, "Unable to parse blocked notifications database", e);
307 } catch (XmlPullParserException e) {
308 Log.wtf(TAG, "Unable to parse blocked notifications database", e);
309 } finally {
310 IoUtils.closeQuietly(infile);
311 }
312 }
313 }
314 }
315
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500316 /**
317 * Use this when you just want to know if notifications are OK for this package.
318 */
319 public boolean areNotificationsEnabledForPackage(String pkg, int uid) {
Daniel Sandler0da673f2012-04-11 12:33:16 -0400320 checkCallerIsSystem();
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500321 return (mAppOps.checkOpNoThrow(AppOpsManager.OP_POST_NOTIFICATION, uid, pkg)
322 == AppOpsManager.MODE_ALLOWED);
Daniel Sandler0da673f2012-04-11 12:33:16 -0400323 }
324
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500325 /** Use this when you actually want to post a notification or toast.
326 *
327 * Unchecked. Not exposed via Binder, but can be called in the course of enqueue*().
328 */
329 private boolean noteNotificationOp(String pkg, int uid) {
330 if (mAppOps.noteOpNoThrow(AppOpsManager.OP_POST_NOTIFICATION, uid, pkg)
331 != AppOpsManager.MODE_ALLOWED) {
332 Slog.v(TAG, "notifications are disabled by AppOps for " + pkg);
333 return false;
Daniel Sandler0da673f2012-04-11 12:33:16 -0400334 }
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500335 return true;
Daniel Sandler0da673f2012-04-11 12:33:16 -0400336 }
337
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500338 public void setNotificationsEnabledForPackage(String pkg, int uid, boolean enabled) {
Daniel Sandler0da673f2012-04-11 12:33:16 -0400339 checkCallerIsSystem();
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500340 if (true||DBG) {
Daniel Sandler0da673f2012-04-11 12:33:16 -0400341 Slog.v(TAG, (enabled?"en":"dis") + "abling notifications for " + pkg);
342 }
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500343 mAppOps.setMode(AppOpsManager.OP_POST_NOTIFICATION, uid, pkg,
344 enabled ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
Daniel Sandler0da673f2012-04-11 12:33:16 -0400345 }
346
347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800348 private static String idDebugString(Context baseContext, String packageName, int id) {
349 Context c = null;
350
351 if (packageName != null) {
352 try {
353 c = baseContext.createPackageContext(packageName, 0);
354 } catch (NameNotFoundException e) {
355 c = baseContext;
356 }
357 } else {
358 c = baseContext;
359 }
360
361 String pkg;
362 String type;
363 String name;
364
365 Resources r = c.getResources();
366 try {
367 return r.getResourceName(id);
368 } catch (Resources.NotFoundException e) {
369 return "<name unknown>";
370 }
371 }
372
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500373 public StatusBarNotification[] getActiveNotifications(String callingPkg) {
374 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_NOTIFICATIONS,
Daniel Sandler78d0d252013-02-12 08:14:52 -0500375 "NotificationManagerService.getActiveNotifications");
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500376
377 StatusBarNotification[] tmp = null;
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500378 int uid = Binder.getCallingUid();
379
380 if (mAppOps.noteOpNoThrow(AppOpsManager.OP_ACCESS_NOTIFICATIONS, uid, callingPkg)
381 == AppOpsManager.MODE_ALLOWED) {
382 synchronized (mNotificationList) {
383 tmp = new StatusBarNotification[mNotificationList.size()];
384 final int N = mNotificationList.size();
385 for (int i=0; i<N; i++) {
386 tmp[i] = mNotificationList.get(i).sbn;
387 }
388 }
389 }
390 return tmp;
391 }
392
Daniel Sandler78d0d252013-02-12 08:14:52 -0500393 public StatusBarNotification[] getHistoricalNotifications(String callingPkg, int count) {
394 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_NOTIFICATIONS,
395 "NotificationManagerService.getHistoricalNotifications");
396
397 StatusBarNotification[] tmp = null;
398 int uid = Binder.getCallingUid();
399
400 if (mAppOps.noteOpNoThrow(AppOpsManager.OP_ACCESS_NOTIFICATIONS, uid, callingPkg)
401 == AppOpsManager.MODE_ALLOWED) {
402 synchronized (mArchive) {
403 tmp = mArchive.getArray(count);
404 }
405 }
406 return tmp;
407 }
408
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500409 public static final class NotificationRecord
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800410 {
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500411 final StatusBarNotification sbn;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800412 IBinder statusBarKey;
413
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500414 NotificationRecord(StatusBarNotification sbn)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800415 {
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500416 this.sbn = sbn;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800417 }
Fred Quintana6ecaff12009-09-25 14:23:13 -0700418
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500419 public Notification getNotification() { return sbn.notification; }
420 public int getFlags() { return sbn.notification.flags; }
421 public int getUserId() { return sbn.getUserId(); }
422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 void dump(PrintWriter pw, String prefix, Context baseContext) {
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500424 final Notification notification = sbn.notification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800425 pw.println(prefix + this);
426 pw.println(prefix + " icon=0x" + Integer.toHexString(notification.icon)
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500427 + " / " + idDebugString(baseContext, this.sbn.pkg, notification.icon));
Daniel Sandler2561b0b2012-02-13 21:04:12 -0500428 pw.println(prefix + " pri=" + notification.priority);
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500429 pw.println(prefix + " score=" + this.sbn.score);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 pw.println(prefix + " contentIntent=" + notification.contentIntent);
431 pw.println(prefix + " deleteIntent=" + notification.deleteIntent);
432 pw.println(prefix + " tickerText=" + notification.tickerText);
433 pw.println(prefix + " contentView=" + notification.contentView);
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500434 pw.println(prefix + " uid=" + this.sbn.uid + " userId=" + this.sbn.getUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 pw.println(prefix + " defaults=0x" + Integer.toHexString(notification.defaults));
436 pw.println(prefix + " flags=0x" + Integer.toHexString(notification.flags));
437 pw.println(prefix + " sound=" + notification.sound);
438 pw.println(prefix + " vibrate=" + Arrays.toString(notification.vibrate));
439 pw.println(prefix + " ledARGB=0x" + Integer.toHexString(notification.ledARGB)
440 + " ledOnMS=" + notification.ledOnMS
441 + " ledOffMS=" + notification.ledOffMS);
442 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800444 @Override
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500445 public final String toString() {
446 return String.format(
447 "NotificationRecord(0x%08x: pkg=%s user=%s id=%d tag=%s score=%d: %s)",
448 System.identityHashCode(this),
449 this.sbn.pkg, this.sbn.user, this.sbn.id, this.sbn.tag,
450 this.sbn.score, this.sbn.notification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 }
452 }
453
454 private static final class ToastRecord
455 {
456 final int pid;
457 final String pkg;
458 final ITransientNotification callback;
459 int duration;
460
461 ToastRecord(int pid, String pkg, ITransientNotification callback, int duration)
462 {
463 this.pid = pid;
464 this.pkg = pkg;
465 this.callback = callback;
466 this.duration = duration;
467 }
468
469 void update(int duration) {
470 this.duration = duration;
471 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800473 void dump(PrintWriter pw, String prefix) {
474 pw.println(prefix + this);
475 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477 @Override
478 public final String toString()
479 {
480 return "ToastRecord{"
481 + Integer.toHexString(System.identityHashCode(this))
482 + " pkg=" + pkg
483 + " callback=" + callback
484 + " duration=" + duration;
485 }
486 }
487
Joe Onorato089de882010-04-12 08:18:45 -0700488 private StatusBarManagerService.NotificationCallbacks mNotificationCallbacks
489 = new StatusBarManagerService.NotificationCallbacks() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800490
491 public void onSetDisabled(int status) {
492 synchronized (mNotificationList) {
493 mDisabledNotifications = status;
494 if ((mDisabledNotifications & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) {
495 // cancel whatever's going on
496 long identity = Binder.clearCallingIdentity();
497 try {
Jeff Sharkey098d5802012-04-26 17:30:34 -0700498 final IRingtonePlayer player = mAudioService.getRingtonePlayer();
499 if (player != null) {
500 player.stopAsync();
501 }
502 } catch (RemoteException e) {
503 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800504 Binder.restoreCallingIdentity(identity);
505 }
506
507 identity = Binder.clearCallingIdentity();
508 try {
509 mVibrator.cancel();
Jeff Sharkey098d5802012-04-26 17:30:34 -0700510 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511 Binder.restoreCallingIdentity(identity);
512 }
513 }
514 }
515 }
516
517 public void onClearAll() {
Dianne Hackborn41203752012-08-31 14:05:51 -0700518 // XXX to be totally correct, the caller should tell us which user
519 // this is for.
520 cancelAll(ActivityManager.getCurrentUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 }
522
Fred Quintana6ecaff12009-09-25 14:23:13 -0700523 public void onNotificationClick(String pkg, String tag, int id) {
Dianne Hackborn41203752012-08-31 14:05:51 -0700524 // XXX to be totally correct, the caller should tell us which user
525 // this is for.
Fred Quintana6ecaff12009-09-25 14:23:13 -0700526 cancelNotification(pkg, tag, id, Notification.FLAG_AUTO_CANCEL,
Dianne Hackborn41203752012-08-31 14:05:51 -0700527 Notification.FLAG_FOREGROUND_SERVICE, false,
528 ActivityManager.getCurrentUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800529 }
530
Daniel Sandler0f0b11c2010-08-04 15:54:58 -0400531 public void onNotificationClear(String pkg, String tag, int id) {
Dianne Hackborn41203752012-08-31 14:05:51 -0700532 // XXX to be totally correct, the caller should tell us which user
533 // this is for.
Joe Onorato46439ce2010-11-19 13:56:21 -0800534 cancelNotification(pkg, tag, id, 0,
535 Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE,
Dianne Hackborn41203752012-08-31 14:05:51 -0700536 true, ActivityManager.getCurrentUser());
Daniel Sandler0f0b11c2010-08-04 15:54:58 -0400537 }
538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 public void onPanelRevealed() {
540 synchronized (mNotificationList) {
541 // sound
542 mSoundNotification = null;
Jeff Sharkey098d5802012-04-26 17:30:34 -0700543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544 long identity = Binder.clearCallingIdentity();
545 try {
Jeff Sharkey098d5802012-04-26 17:30:34 -0700546 final IRingtonePlayer player = mAudioService.getRingtonePlayer();
547 if (player != null) {
548 player.stopAsync();
549 }
550 } catch (RemoteException e) {
551 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 Binder.restoreCallingIdentity(identity);
553 }
554
555 // vibrate
556 mVibrateNotification = null;
557 identity = Binder.clearCallingIdentity();
558 try {
559 mVibrator.cancel();
Jeff Sharkey098d5802012-04-26 17:30:34 -0700560 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561 Binder.restoreCallingIdentity(identity);
562 }
563
564 // light
565 mLights.clear();
566 mLedNotification = null;
567 updateLightsLocked();
568 }
569 }
Joe Onorato005847b2010-06-04 16:08:02 -0400570
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700571 public void onNotificationError(String pkg, String tag, int id,
572 int uid, int initialPid, String message) {
Daniel Sandlerd0a2f862010-08-03 15:29:31 -0400573 Slog.d(TAG, "onNotification error pkg=" + pkg + " tag=" + tag + " id=" + id
574 + "; will crashApplication(uid=" + uid + ", pid=" + initialPid + ")");
Dianne Hackborn41203752012-08-31 14:05:51 -0700575 // XXX to be totally correct, the caller should tell us which user
576 // this is for.
577 cancelNotification(pkg, tag, id, 0, 0, false, UserHandle.getUserId(uid));
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700578 long ident = Binder.clearCallingIdentity();
579 try {
580 ActivityManagerNative.getDefault().crashApplication(uid, initialPid, pkg,
581 "Bad notification posted from package " + pkg
582 + ": " + message);
583 } catch (RemoteException e) {
584 }
585 Binder.restoreCallingIdentity(ident);
Joe Onorato005847b2010-06-04 16:08:02 -0400586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587 };
588
589 private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
590 @Override
591 public void onReceive(Context context, Intent intent) {
592 String action = intent.getAction();
593
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800594 boolean queryRestart = false;
Daniel Sandler26ece572012-06-01 15:38:46 -0400595 boolean packageChanged = false;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800596
Mike Lockwood541c9942011-06-12 19:35:45 -0400597 if (action.equals(Intent.ACTION_PACKAGE_REMOVED)
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800598 || action.equals(Intent.ACTION_PACKAGE_RESTARTED)
Daniel Sandler26ece572012-06-01 15:38:46 -0400599 || (packageChanged=action.equals(Intent.ACTION_PACKAGE_CHANGED))
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800600 || (queryRestart=action.equals(Intent.ACTION_QUERY_PACKAGE_RESTART))
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800601 || action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800602 String pkgList[] = null;
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800603 if (action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800604 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800605 } else if (queryRestart) {
606 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800607 } else {
608 Uri uri = intent.getData();
609 if (uri == null) {
610 return;
611 }
612 String pkgName = uri.getSchemeSpecificPart();
613 if (pkgName == null) {
614 return;
615 }
Daniel Sandler26ece572012-06-01 15:38:46 -0400616 if (packageChanged) {
617 // We cancel notifications for packages which have just been disabled
618 final int enabled = mContext.getPackageManager()
619 .getApplicationEnabledSetting(pkgName);
620 if (enabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
621 || enabled == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
622 return;
623 }
624 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800625 pkgList = new String[]{pkgName};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800627 if (pkgList != null && (pkgList.length > 0)) {
628 for (String pkgName : pkgList) {
Dianne Hackborn41203752012-08-31 14:05:51 -0700629 cancelAllNotificationsInt(pkgName, 0, 0, !queryRestart,
630 UserHandle.USER_ALL);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 }
Mike Lockwood63b5ad92011-08-30 09:55:30 -0400633 } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
634 // Keep track of screen on/off state, but do not turn off the notification light
635 // until user passes through the lock screen or views the notification.
636 mScreenOn = true;
637 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
638 mScreenOn = false;
Daniel Sandlere96ffb12010-03-11 13:38:06 -0500639 } else if (action.equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
Mike Lockwood63b5ad92011-08-30 09:55:30 -0400640 mInCall = (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
641 TelephonyManager.EXTRA_STATE_OFFHOOK));
Daniel Sandlere96ffb12010-03-11 13:38:06 -0500642 updateNotificationPulse();
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700643 } else if (action.equals(Intent.ACTION_USER_STOPPED)) {
644 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
645 if (userHandle >= 0) {
Dianne Hackborn41203752012-08-31 14:05:51 -0700646 cancelAllNotificationsInt(null, 0, 0, true, userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700647 }
Mike Lockwood63b5ad92011-08-30 09:55:30 -0400648 } else if (action.equals(Intent.ACTION_USER_PRESENT)) {
649 // turn off LED when user passes through lock screen
650 mNotificationLight.turnOff();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 }
652 }
653 };
654
Dianne Hackborn1dac2772009-06-26 18:16:48 -0700655 class SettingsObserver extends ContentObserver {
656 SettingsObserver(Handler handler) {
657 super(handler);
658 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800659
Dianne Hackborn1dac2772009-06-26 18:16:48 -0700660 void observe() {
661 ContentResolver resolver = mContext.getContentResolver();
Mike Lockwoodc22404a2009-12-02 11:15:02 -0500662 resolver.registerContentObserver(Settings.System.getUriFor(
663 Settings.System.NOTIFICATION_LIGHT_PULSE), false, this);
Dianne Hackborn1dac2772009-06-26 18:16:48 -0700664 update();
665 }
666
667 @Override public void onChange(boolean selfChange) {
668 update();
669 }
670
671 public void update() {
672 ContentResolver resolver = mContext.getContentResolver();
Mike Lockwoodc22404a2009-12-02 11:15:02 -0500673 boolean pulseEnabled = Settings.System.getInt(resolver,
674 Settings.System.NOTIFICATION_LIGHT_PULSE, 0) != 0;
675 if (mNotificationPulseEnabled != pulseEnabled) {
676 mNotificationPulseEnabled = pulseEnabled;
677 updateNotificationPulse();
678 }
Dianne Hackborn1dac2772009-06-26 18:16:48 -0700679 }
680 }
Mike Lockwoodc22404a2009-12-02 11:15:02 -0500681
Daniel Sandleredbb3802012-11-13 20:49:47 -0800682 static long[] getLongArray(Resources r, int resid, int maxlen, long[] def) {
683 int[] ar = r.getIntArray(resid);
684 if (ar == null) {
685 return def;
686 }
687 final int len = ar.length > maxlen ? maxlen : ar.length;
688 long[] out = new long[len];
689 for (int i=0; i<len; i++) {
690 out[i] = ar[i];
691 }
692 return out;
693 }
694
Joe Onorato089de882010-04-12 08:18:45 -0700695 NotificationManagerService(Context context, StatusBarManagerService statusBar,
Mike Lockwood3a322132009-11-24 00:30:52 -0500696 LightsService lights)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 {
698 super();
699 mContext = context;
Jeff Brownc2346132012-04-13 01:55:38 -0700700 mVibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 mAm = ActivityManagerNative.getDefault();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 mToastQueue = new ArrayList<ToastRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 mHandler = new WorkerHandler();
San Mehat3ee13172010-02-04 20:54:43 -0800704
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500705 mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
706
707 importOldBlockDb();
Daniel Sandler0da673f2012-04-11 12:33:16 -0400708
Joe Onorato089de882010-04-12 08:18:45 -0700709 mStatusBar = statusBar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 statusBar.setNotificationCallbacks(mNotificationCallbacks);
711
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500712 mNotificationLight = lights.getLight(LightsService.LIGHT_ID_NOTIFICATIONS);
713 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
714
Mike Lockwood670f9322010-01-20 12:13:36 -0500715 Resources resources = mContext.getResources();
716 mDefaultNotificationColor = resources.getColor(
717 com.android.internal.R.color.config_defaultNotificationColor);
718 mDefaultNotificationLedOn = resources.getInteger(
719 com.android.internal.R.integer.config_defaultNotificationLedOn);
720 mDefaultNotificationLedOff = resources.getInteger(
721 com.android.internal.R.integer.config_defaultNotificationLedOff);
722
Daniel Sandleredbb3802012-11-13 20:49:47 -0800723 mDefaultVibrationPattern = getLongArray(resources,
724 com.android.internal.R.array.config_defaultNotificationVibePattern,
725 VIBRATE_PATTERN_MAXLEN,
726 DEFAULT_VIBRATE_PATTERN);
727
728 mFallbackVibrationPattern = getLongArray(resources,
729 com.android.internal.R.array.config_notificationFallbackVibePattern,
730 VIBRATE_PATTERN_MAXLEN,
731 DEFAULT_VIBRATE_PATTERN);
732
Joe Onorato39f5b6a2009-07-23 12:29:19 -0400733 // Don't start allowing notifications until the setup wizard has run once.
734 // After that, including subsequent boots, init with notifications turned on.
735 // This works on the first boot because the setup wizard will toggle this
736 // flag at least once and we'll go back to 0 after that.
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700737 if (0 == Settings.Global.getInt(mContext.getContentResolver(),
738 Settings.Global.DEVICE_PROVISIONED, 0)) {
Joe Onorato39f5b6a2009-07-23 12:29:19 -0400739 mDisabledNotifications = StatusBarManager.DISABLE_NOTIFICATION_ALERTS;
740 }
741
Mike Lockwood35e16bf2010-11-30 19:53:36 -0500742 // register for various Intents
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 IntentFilter filter = new IntentFilter();
Mike Lockwoodc22404a2009-12-02 11:15:02 -0500744 filter.addAction(Intent.ACTION_SCREEN_ON);
745 filter.addAction(Intent.ACTION_SCREEN_OFF);
Daniel Sandlere96ffb12010-03-11 13:38:06 -0500746 filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
Mike Lockwood63b5ad92011-08-30 09:55:30 -0400747 filter.addAction(Intent.ACTION_USER_PRESENT);
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700748 filter.addAction(Intent.ACTION_USER_STOPPED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749 mContext.registerReceiver(mIntentReceiver, filter);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800750 IntentFilter pkgFilter = new IntentFilter();
751 pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
Daniel Sandleraac0eb02011-08-06 22:51:56 -0400752 pkgFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800753 pkgFilter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
754 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
755 pkgFilter.addDataScheme("package");
756 mContext.registerReceiver(mIntentReceiver, pkgFilter);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800757 IntentFilter sdFilter = new IntentFilter(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800758 mContext.registerReceiver(mIntentReceiver, sdFilter);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800759
Mike Lockwoodc22404a2009-12-02 11:15:02 -0500760 SettingsObserver observer = new SettingsObserver(mHandler);
761 observer.observe();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800762 }
763
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500764 /**
765 * Read the old XML-based app block database and import those blockages into the AppOps system.
766 */
767 private void importOldBlockDb() {
768 loadBlockDb();
769
770 PackageManager pm = mContext.getPackageManager();
771 for (String pkg : mBlockedPackages) {
772 PackageInfo info = null;
773 try {
774 info = pm.getPackageInfo(pkg, 0);
775 setNotificationsEnabledForPackage(pkg, info.applicationInfo.uid, false);
776 } catch (NameNotFoundException e) {
777 // forget you
778 }
779 }
780 mBlockedPackages.clear();
781 if (mPolicyFile != null) {
782 mPolicyFile.delete();
783 }
784 }
785
Joe Onorato30275482009-07-08 17:09:14 -0700786 void systemReady() {
Jeff Sharkey098d5802012-04-26 17:30:34 -0700787 mAudioService = IAudioService.Stub.asInterface(
788 ServiceManager.getService(Context.AUDIO_SERVICE));
789
Joe Onorato30275482009-07-08 17:09:14 -0700790 // no beeping until we're basically done booting
791 mSystemReady = true;
792 }
793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794 // Toasts
795 // ============================================================================
796 public void enqueueToast(String pkg, ITransientNotification callback, int duration)
797 {
Daniel Sandlera7035902010-03-30 15:45:31 -0400798 if (DBG) Slog.i(TAG, "enqueueToast pkg=" + pkg + " callback=" + callback + " duration=" + duration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799
800 if (pkg == null || callback == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800801 Slog.e(TAG, "Not doing toast. pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 return ;
803 }
804
Daniel Sandler0da673f2012-04-11 12:33:16 -0400805 final boolean isSystemToast = ("android".equals(pkg));
806
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500807 if (ENABLE_BLOCKED_TOASTS && !noteNotificationOp(pkg, Binder.getCallingUid())) {
808 if (!isSystemToast) {
809 Slog.e(TAG, "Suppressing toast from package " + pkg + " by user request.");
810 return;
811 }
Daniel Sandler0da673f2012-04-11 12:33:16 -0400812 }
813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 synchronized (mToastQueue) {
815 int callingPid = Binder.getCallingPid();
816 long callingId = Binder.clearCallingIdentity();
817 try {
818 ToastRecord record;
819 int index = indexOfToastLocked(pkg, callback);
820 // If it's already in the queue, we update it in place, we don't
821 // move it to the end of the queue.
822 if (index >= 0) {
823 record = mToastQueue.get(index);
824 record.update(duration);
825 } else {
Vairavan Srinivasanf9eb06c2011-01-21 18:08:36 -0800826 // Limit the number of toasts that any given package except the android
827 // package can enqueue. Prevents DOS attacks and deals with leaks.
Daniel Sandler0da673f2012-04-11 12:33:16 -0400828 if (!isSystemToast) {
Vairavan Srinivasanf9eb06c2011-01-21 18:08:36 -0800829 int count = 0;
830 final int N = mToastQueue.size();
831 for (int i=0; i<N; i++) {
832 final ToastRecord r = mToastQueue.get(i);
833 if (r.pkg.equals(pkg)) {
834 count++;
835 if (count >= MAX_PACKAGE_NOTIFICATIONS) {
836 Slog.e(TAG, "Package has already posted " + count
837 + " toasts. Not showing more. Package=" + pkg);
838 return;
839 }
840 }
841 }
842 }
843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 record = new ToastRecord(callingPid, pkg, callback, duration);
845 mToastQueue.add(record);
846 index = mToastQueue.size() - 1;
847 keepProcessAliveLocked(callingPid);
848 }
849 // If it's at index 0, it's the current toast. It doesn't matter if it's
850 // new or just been updated. Call back and tell it to show itself.
851 // If the callback fails, this will remove it from the list, so don't
852 // assume that it's valid after this.
853 if (index == 0) {
854 showNextToastLocked();
855 }
856 } finally {
857 Binder.restoreCallingIdentity(callingId);
858 }
859 }
860 }
861
862 public void cancelToast(String pkg, ITransientNotification callback) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800863 Slog.i(TAG, "cancelToast pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864
865 if (pkg == null || callback == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800866 Slog.e(TAG, "Not cancelling notification. pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 return ;
868 }
869
870 synchronized (mToastQueue) {
871 long callingId = Binder.clearCallingIdentity();
872 try {
873 int index = indexOfToastLocked(pkg, callback);
874 if (index >= 0) {
875 cancelToastLocked(index);
876 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800877 Slog.w(TAG, "Toast already cancelled. pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 }
879 } finally {
880 Binder.restoreCallingIdentity(callingId);
881 }
882 }
883 }
884
885 private void showNextToastLocked() {
886 ToastRecord record = mToastQueue.get(0);
887 while (record != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800888 if (DBG) Slog.d(TAG, "Show pkg=" + record.pkg + " callback=" + record.callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 try {
890 record.callback.show();
891 scheduleTimeoutLocked(record, false);
892 return;
893 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800894 Slog.w(TAG, "Object died trying to show notification " + record.callback
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 + " in package " + record.pkg);
896 // remove it from the list and let the process die
897 int index = mToastQueue.indexOf(record);
898 if (index >= 0) {
899 mToastQueue.remove(index);
900 }
901 keepProcessAliveLocked(record.pid);
902 if (mToastQueue.size() > 0) {
903 record = mToastQueue.get(0);
904 } else {
905 record = null;
906 }
907 }
908 }
909 }
910
911 private void cancelToastLocked(int index) {
912 ToastRecord record = mToastQueue.get(index);
913 try {
914 record.callback.hide();
915 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800916 Slog.w(TAG, "Object died trying to hide notification " + record.callback
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 + " in package " + record.pkg);
918 // don't worry about this, we're about to remove it from
919 // the list anyway
920 }
921 mToastQueue.remove(index);
922 keepProcessAliveLocked(record.pid);
923 if (mToastQueue.size() > 0) {
924 // Show the next one. If the callback fails, this will remove
925 // it from the list, so don't assume that the list hasn't changed
926 // after this point.
927 showNextToastLocked();
928 }
929 }
930
931 private void scheduleTimeoutLocked(ToastRecord r, boolean immediate)
932 {
933 Message m = Message.obtain(mHandler, MESSAGE_TIMEOUT, r);
934 long delay = immediate ? 0 : (r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY);
935 mHandler.removeCallbacksAndMessages(r);
936 mHandler.sendMessageDelayed(m, delay);
937 }
938
939 private void handleTimeout(ToastRecord record)
940 {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800941 if (DBG) Slog.d(TAG, "Timeout pkg=" + record.pkg + " callback=" + record.callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800942 synchronized (mToastQueue) {
943 int index = indexOfToastLocked(record.pkg, record.callback);
944 if (index >= 0) {
945 cancelToastLocked(index);
946 }
947 }
948 }
949
950 // lock on mToastQueue
951 private int indexOfToastLocked(String pkg, ITransientNotification callback)
952 {
953 IBinder cbak = callback.asBinder();
954 ArrayList<ToastRecord> list = mToastQueue;
955 int len = list.size();
956 for (int i=0; i<len; i++) {
957 ToastRecord r = list.get(i);
958 if (r.pkg.equals(pkg) && r.callback.asBinder() == cbak) {
959 return i;
960 }
961 }
962 return -1;
963 }
964
965 // lock on mToastQueue
966 private void keepProcessAliveLocked(int pid)
967 {
968 int toastCount = 0; // toasts from this pid
969 ArrayList<ToastRecord> list = mToastQueue;
970 int N = list.size();
971 for (int i=0; i<N; i++) {
972 ToastRecord r = list.get(i);
973 if (r.pid == pid) {
974 toastCount++;
975 }
976 }
977 try {
978 mAm.setProcessForeground(mForegroundToken, pid, toastCount > 0);
979 } catch (RemoteException e) {
980 // Shouldn't happen.
981 }
982 }
983
984 private final class WorkerHandler extends Handler
985 {
986 @Override
987 public void handleMessage(Message msg)
988 {
989 switch (msg.what)
990 {
991 case MESSAGE_TIMEOUT:
992 handleTimeout((ToastRecord)msg.obj);
993 break;
994 }
995 }
996 }
997
998
999 // Notifications
1000 // ============================================================================
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001001 public void enqueueNotificationWithTag(String pkg, String basePkg, String tag, int id,
1002 Notification notification, int[] idOut, int userId)
Fred Quintana6ecaff12009-09-25 14:23:13 -07001003 {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001004 enqueueNotificationInternal(pkg, basePkg, Binder.getCallingUid(), Binder.getCallingPid(),
Dianne Hackborn41203752012-08-31 14:05:51 -07001005 tag, id, notification, idOut, userId);
Daniel Sandlerd0a2f862010-08-03 15:29:31 -04001006 }
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001007
1008 private final static int clamp(int x, int low, int high) {
1009 return (x < low) ? low : ((x > high) ? high : x);
Daniel Sandlere40451a2011-02-03 14:51:35 -05001010 }
1011
Daniel Sandlerd0a2f862010-08-03 15:29:31 -04001012 // Not exposed via Binder; for system use only (otherwise malicious apps could spoof the
1013 // uid/pid of another application)
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001014 public void enqueueNotificationInternal(String pkg, String basePkg, int callingUid,
1015 int callingPid, String tag, int id, Notification notification, int[] idOut, int userId)
Daniel Sandlerd0a2f862010-08-03 15:29:31 -04001016 {
Daniel Sandler0da673f2012-04-11 12:33:16 -04001017 if (DBG) {
1018 Slog.v(TAG, "enqueueNotificationInternal: pkg=" + pkg + " id=" + id + " notification=" + notification);
1019 }
1020 checkCallerIsSystemOrSameApp(pkg);
1021 final boolean isSystemNotification = ("android".equals(pkg));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001022
Dianne Hackborn41203752012-08-31 14:05:51 -07001023 userId = ActivityManager.handleIncomingUser(callingPid,
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07001024 callingUid, userId, true, false, "enqueueNotification", pkg);
Jeff Sharkey65c4a2b2012-09-25 17:22:27 -07001025 final UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001026
Joe Onoratobd73d012010-06-04 11:44:54 -07001027 // Limit the number of notifications that any given package except the android
1028 // package can enqueue. Prevents DOS attacks and deals with leaks.
Daniel Sandler0da673f2012-04-11 12:33:16 -04001029 if (!isSystemNotification) {
Joe Onoratobd73d012010-06-04 11:44:54 -07001030 synchronized (mNotificationList) {
1031 int count = 0;
1032 final int N = mNotificationList.size();
1033 for (int i=0; i<N; i++) {
1034 final NotificationRecord r = mNotificationList.get(i);
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001035 if (r.sbn.pkg.equals(pkg) && r.sbn.getUserId() == userId) {
Joe Onoratobd73d012010-06-04 11:44:54 -07001036 count++;
1037 if (count >= MAX_PACKAGE_NOTIFICATIONS) {
1038 Slog.e(TAG, "Package has already posted " + count
1039 + " notifications. Not showing more. package=" + pkg);
1040 return;
1041 }
1042 }
1043 }
1044 }
1045 }
1046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 // This conditional is a dirty hack to limit the logging done on
1048 // behalf of the download manager without affecting other apps.
1049 if (!pkg.equals("com.android.providers.downloads")
1050 || Log.isLoggable("DownloadManager", Log.VERBOSE)) {
Daniel Sandler321e9c52012-10-12 10:59:26 -07001051 EventLog.writeEvent(EventLogTags.NOTIFICATION_ENQUEUE, pkg, id, tag, userId,
Daniel Sandlerb64cb882011-11-29 23:48:29 -05001052 notification.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 }
1054
1055 if (pkg == null || notification == null) {
1056 throw new IllegalArgumentException("null not allowed: pkg=" + pkg
1057 + " id=" + id + " notification=" + notification);
1058 }
1059 if (notification.icon != 0) {
1060 if (notification.contentView == null) {
1061 throw new IllegalArgumentException("contentView required: pkg=" + pkg
1062 + " id=" + id + " notification=" + notification);
1063 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 }
1065
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001066 // === Scoring ===
Daniel Sandler0da673f2012-04-11 12:33:16 -04001067
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001068 // 0. Sanitize inputs
1069 notification.priority = clamp(notification.priority, Notification.PRIORITY_MIN, Notification.PRIORITY_MAX);
1070 // Migrate notification flags to scores
1071 if (0 != (notification.flags & Notification.FLAG_HIGH_PRIORITY)) {
1072 if (notification.priority < Notification.PRIORITY_MAX) notification.priority = Notification.PRIORITY_MAX;
Daniel Sandler49a2ad12012-03-28 15:46:39 -04001073 } else if (SCORE_ONGOING_HIGHER && 0 != (notification.flags & Notification.FLAG_ONGOING_EVENT)) {
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001074 if (notification.priority < Notification.PRIORITY_HIGH) notification.priority = Notification.PRIORITY_HIGH;
1075 }
Daniel Sandler0da673f2012-04-11 12:33:16 -04001076
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001077 // 1. initial score: buckets of 10, around the app
Daniel Sandler0da673f2012-04-11 12:33:16 -04001078 int score = notification.priority * NOTIFICATION_PRIORITY_MULTIPLIER; //[-20..20]
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001079
Daniel Sandler0da673f2012-04-11 12:33:16 -04001080 // 2. Consult external heuristics (TBD)
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001081
Daniel Sandler0da673f2012-04-11 12:33:16 -04001082 // 3. Apply local rules
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001083
1084 // blocked apps
Daniel Sandler4a900acd2013-01-30 14:04:10 -05001085 if (ENABLE_BLOCKED_NOTIFICATIONS && !noteNotificationOp(pkg, callingUid)) {
1086 if (!isSystemNotification) {
1087 score = JUNK_SCORE;
1088 Slog.e(TAG, "Suppressing notification from package " + pkg + " by user request.");
1089 }
Daniel Sandler0da673f2012-04-11 12:33:16 -04001090 }
1091
1092 if (DBG) {
1093 Slog.v(TAG, "Assigned score=" + score + " to " + notification);
1094 }
1095
1096 if (score < SCORE_DISPLAY_THRESHOLD) {
1097 // Notification will be blocked because the score is too low.
1098 return;
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001099 }
1100
Daniel Sandler526fa0e2012-12-04 14:51:50 -05001101 // Should this notification make noise, vibe, or use the LED?
1102 final boolean canInterrupt = (score >= SCORE_INTERRUPTION_THRESHOLD);
1103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 synchronized (mNotificationList) {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001105 final StatusBarNotification n = new StatusBarNotification(
1106 pkg, id, tag, callingUid, callingPid, score, notification, user);
1107 NotificationRecord r = new NotificationRecord(n);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 NotificationRecord old = null;
1109
Dianne Hackborn41203752012-08-31 14:05:51 -07001110 int index = indexOfNotificationLocked(pkg, tag, id, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 if (index < 0) {
1112 mNotificationList.add(r);
1113 } else {
1114 old = mNotificationList.remove(index);
1115 mNotificationList.add(index, r);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001116 // Make sure we don't lose the foreground service state.
1117 if (old != null) {
1118 notification.flags |=
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001119 old.getNotification().flags&Notification.FLAG_FOREGROUND_SERVICE;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001120 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001122
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001123 // Ensure if this is a foreground service that the proper additional
1124 // flags are set.
1125 if ((notification.flags&Notification.FLAG_FOREGROUND_SERVICE) != 0) {
1126 notification.flags |= Notification.FLAG_ONGOING_EVENT
1127 | Notification.FLAG_NO_CLEAR;
1128 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001129
Svetoslav Ganovc31ed392012-10-10 14:58:28 -07001130 final int currentUser;
1131 final long token = Binder.clearCallingIdentity();
1132 try {
1133 currentUser = ActivityManager.getCurrentUser();
1134 } finally {
1135 Binder.restoreCallingIdentity(token);
1136 }
1137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 if (notification.icon != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 if (old != null && old.statusBarKey != null) {
1140 r.statusBarKey = old.statusBarKey;
1141 long identity = Binder.clearCallingIdentity();
1142 try {
Joe Onorato18e69df2010-05-17 22:26:12 -07001143 mStatusBar.updateNotification(r.statusBarKey, n);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 }
1145 finally {
1146 Binder.restoreCallingIdentity(identity);
1147 }
1148 } else {
1149 long identity = Binder.clearCallingIdentity();
1150 try {
Joe Onorato18e69df2010-05-17 22:26:12 -07001151 r.statusBarKey = mStatusBar.addNotification(n);
Daniel Sandler526fa0e2012-12-04 14:51:50 -05001152 if ((n.notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0
1153 && canInterrupt) {
Mike Lockwoodece18ef2012-02-13 20:42:19 -08001154 mAttentionLight.pulse();
1155 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 }
1157 finally {
1158 Binder.restoreCallingIdentity(identity);
1159 }
1160 }
Svetoslav Ganovc31ed392012-10-10 14:58:28 -07001161 // Send accessibility events only for the current user.
1162 if (currentUser == userId) {
1163 sendAccessibilityEvent(notification, pkg);
1164 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001165
1166 // finally, keep some of this information around for later use
1167 mArchive.record(n);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001168 } else {
Daniel Sandlere40451a2011-02-03 14:51:35 -05001169 Slog.e(TAG, "Ignoring notification with icon==0: " + notification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170 if (old != null && old.statusBarKey != null) {
1171 long identity = Binder.clearCallingIdentity();
1172 try {
Joe Onorato0cbda992010-05-02 16:28:15 -07001173 mStatusBar.removeNotification(old.statusBarKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 }
1175 finally {
1176 Binder.restoreCallingIdentity(identity);
1177 }
1178 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001179 return; // do not play sounds, show lights, etc. for invalid notifications
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180 }
1181
1182 // If we're not supposed to beep, vibrate, etc. then don't.
1183 if (((mDisabledNotifications & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) == 0)
1184 && (!(old != null
Joe Onorato30275482009-07-08 17:09:14 -07001185 && (notification.flags & Notification.FLAG_ONLY_ALERT_ONCE) != 0 ))
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001186 && (r.getUserId() == UserHandle.USER_ALL ||
1187 (r.getUserId() == userId && r.getUserId() == currentUser))
Daniel Sandler526fa0e2012-12-04 14:51:50 -05001188 && canInterrupt
Joe Onorato30275482009-07-08 17:09:14 -07001189 && mSystemReady) {
Eric Laurent524dc042009-11-27 05:07:55 -08001190
1191 final AudioManager audioManager = (AudioManager) mContext
1192 .getSystemService(Context.AUDIO_SERVICE);
Daniel Sandlerd4d2de22012-11-14 11:25:46 -08001193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 // sound
1195 final boolean useDefaultSound =
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001196 (notification.defaults & Notification.DEFAULT_SOUND) != 0;
Daniel Sandlerd4d2de22012-11-14 11:25:46 -08001197
1198 Uri soundUri = null;
1199 boolean hasValidSound = false;
1200
1201 if (useDefaultSound) {
1202 soundUri = Settings.System.DEFAULT_NOTIFICATION_URI;
1203
1204 // check to see if the default notification sound is silent
1205 ContentResolver resolver = mContext.getContentResolver();
1206 hasValidSound = Settings.System.getString(resolver,
1207 Settings.System.NOTIFICATION_SOUND) != null;
1208 } else if (notification.sound != null) {
1209 soundUri = notification.sound;
1210 hasValidSound = (soundUri != null);
1211 }
1212
1213 if (hasValidSound) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 boolean looping = (notification.flags & Notification.FLAG_INSISTENT) != 0;
1215 int audioStreamType;
1216 if (notification.audioStreamType >= 0) {
1217 audioStreamType = notification.audioStreamType;
1218 } else {
1219 audioStreamType = DEFAULT_STREAM_TYPE;
1220 }
1221 mSoundNotification = r;
Eric Laurent524dc042009-11-27 05:07:55 -08001222 // do not play notifications if stream volume is 0
Jean-Michel Trivid6770542012-10-10 12:03:41 -07001223 // (typically because ringer mode is silent) or if speech recognition is active.
1224 if ((audioManager.getStreamVolume(audioStreamType) != 0)
1225 && !audioManager.isSpeechRecognitionActive()) {
Jeff Sharkey098d5802012-04-26 17:30:34 -07001226 final long identity = Binder.clearCallingIdentity();
Eric Laurent524dc042009-11-27 05:07:55 -08001227 try {
Jeff Sharkey098d5802012-04-26 17:30:34 -07001228 final IRingtonePlayer player = mAudioService.getRingtonePlayer();
1229 if (player != null) {
Daniel Sandlerd4d2de22012-11-14 11:25:46 -08001230 player.playAsync(soundUri, user, looping, audioStreamType);
Jeff Sharkey098d5802012-04-26 17:30:34 -07001231 }
1232 } catch (RemoteException e) {
1233 } finally {
Eric Laurent524dc042009-11-27 05:07:55 -08001234 Binder.restoreCallingIdentity(identity);
1235 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236 }
1237 }
1238
1239 // vibrate
Daniel Sandleredbb3802012-11-13 20:49:47 -08001240 // Does the notification want to specify its own vibration?
1241 final boolean hasCustomVibrate = notification.vibrate != null;
1242
David Agnew71789e12012-11-09 23:03:26 -05001243 // 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 -05001244 // and no other vibration is specified, we fall back to vibration
David Agnew71789e12012-11-09 23:03:26 -05001245 final boolean convertSoundToVibration =
Daniel Sandleredbb3802012-11-13 20:49:47 -08001246 !hasCustomVibrate
Daniel Sandlerd4d2de22012-11-14 11:25:46 -08001247 && hasValidSound
David Agnew71789e12012-11-09 23:03:26 -05001248 && (audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE);
1249
Daniel Sandler4a7a9b92012-11-20 12:59:41 -05001250 // The DEFAULT_VIBRATE flag trumps any custom vibration AND the fallback.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251 final boolean useDefaultVibrate =
Daniel Sandleredbb3802012-11-13 20:49:47 -08001252 (notification.defaults & Notification.DEFAULT_VIBRATE) != 0;
David Agnew71789e12012-11-09 23:03:26 -05001253
Daniel Sandleredbb3802012-11-13 20:49:47 -08001254 if ((useDefaultVibrate || convertSoundToVibration || hasCustomVibrate)
Eric Laurentbffc3d12012-05-07 17:43:49 -07001255 && !(audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 mVibrateNotification = r;
1257
Daniel Sandleredbb3802012-11-13 20:49:47 -08001258 if (useDefaultVibrate || convertSoundToVibration) {
1259 // Escalate privileges so we can use the vibrator even if the notifying app
1260 // does not have the VIBRATE permission.
1261 long identity = Binder.clearCallingIdentity();
1262 try {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001263 mVibrator.vibrate(r.sbn.uid, r.sbn.basePkg,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001264 useDefaultVibrate ? mDefaultVibrationPattern
1265 : mFallbackVibrationPattern,
Daniel Sandleredbb3802012-11-13 20:49:47 -08001266 ((notification.flags & Notification.FLAG_INSISTENT) != 0) ? 0: -1);
1267 } finally {
1268 Binder.restoreCallingIdentity(identity);
1269 }
1270 } else if (notification.vibrate.length > 1) {
1271 // If you want your own vibration pattern, you need the VIBRATE permission
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001272 mVibrator.vibrate(r.sbn.uid, r.sbn.basePkg, notification.vibrate,
Daniel Sandleredbb3802012-11-13 20:49:47 -08001273 ((notification.flags & Notification.FLAG_INSISTENT) != 0) ? 0: -1);
1274 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 }
1276 }
1277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 // light
1279 // the most recent thing gets the light
1280 mLights.remove(old);
1281 if (mLedNotification == old) {
1282 mLedNotification = null;
1283 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001284 //Slog.i(TAG, "notification.lights="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 // + ((old.notification.lights.flags & Notification.FLAG_SHOW_LIGHTS) != 0));
Daniel Sandler526fa0e2012-12-04 14:51:50 -05001286 if ((notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0
1287 && canInterrupt) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 mLights.add(r);
1289 updateLightsLocked();
1290 } else {
1291 if (old != null
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001292 && ((old.getFlags() & Notification.FLAG_SHOW_LIGHTS) != 0)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 updateLightsLocked();
1294 }
1295 }
1296 }
1297
1298 idOut[0] = id;
1299 }
1300
Joe Onorato30275482009-07-08 17:09:14 -07001301 private void sendAccessibilityEvent(Notification notification, CharSequence packageName) {
svetoslavganov75986cf2009-05-14 22:28:01 -07001302 AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
1303 if (!manager.isEnabled()) {
1304 return;
1305 }
1306
1307 AccessibilityEvent event =
1308 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED);
1309 event.setPackageName(packageName);
1310 event.setClassName(Notification.class.getName());
1311 event.setParcelableData(notification);
1312 CharSequence tickerText = notification.tickerText;
1313 if (!TextUtils.isEmpty(tickerText)) {
1314 event.getText().add(tickerText);
1315 }
1316
1317 manager.sendAccessibilityEvent(event);
1318 }
1319
Joe Onorato46439ce2010-11-19 13:56:21 -08001320 private void cancelNotificationLocked(NotificationRecord r, boolean sendDelete) {
1321 // tell the app
1322 if (sendDelete) {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001323 if (r.getNotification().deleteIntent != null) {
Joe Onorato46439ce2010-11-19 13:56:21 -08001324 try {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001325 r.getNotification().deleteIntent.send();
Joe Onorato46439ce2010-11-19 13:56:21 -08001326 } catch (PendingIntent.CanceledException ex) {
1327 // do nothing - there's no relevant way to recover, and
1328 // no reason to let this propagate
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001329 Slog.w(TAG, "canceled PendingIntent for " + r.sbn.pkg, ex);
Joe Onorato46439ce2010-11-19 13:56:21 -08001330 }
1331 }
1332 }
1333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001334 // status bar
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001335 if (r.getNotification().icon != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 long identity = Binder.clearCallingIdentity();
1337 try {
Joe Onorato0cbda992010-05-02 16:28:15 -07001338 mStatusBar.removeNotification(r.statusBarKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 }
1340 finally {
1341 Binder.restoreCallingIdentity(identity);
1342 }
1343 r.statusBarKey = null;
1344 }
1345
1346 // sound
1347 if (mSoundNotification == r) {
1348 mSoundNotification = null;
Jeff Sharkey098d5802012-04-26 17:30:34 -07001349 final long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 try {
Jeff Sharkey098d5802012-04-26 17:30:34 -07001351 final IRingtonePlayer player = mAudioService.getRingtonePlayer();
1352 if (player != null) {
1353 player.stopAsync();
1354 }
1355 } catch (RemoteException e) {
1356 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 Binder.restoreCallingIdentity(identity);
1358 }
1359 }
1360
1361 // vibrate
1362 if (mVibrateNotification == r) {
1363 mVibrateNotification = null;
1364 long identity = Binder.clearCallingIdentity();
1365 try {
1366 mVibrator.cancel();
1367 }
1368 finally {
1369 Binder.restoreCallingIdentity(identity);
1370 }
1371 }
1372
1373 // light
1374 mLights.remove(r);
1375 if (mLedNotification == r) {
1376 mLedNotification = null;
1377 }
1378 }
1379
1380 /**
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001381 * Cancels a notification ONLY if it has all of the {@code mustHaveFlags}
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001382 * and none of the {@code mustNotHaveFlags}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 */
Fred Quintana6ecaff12009-09-25 14:23:13 -07001384 private void cancelNotification(String pkg, String tag, int id, int mustHaveFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07001385 int mustNotHaveFlags, boolean sendDelete, int userId) {
Daniel Sandler321e9c52012-10-12 10:59:26 -07001386 EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL, pkg, id, tag, userId,
Daniel Sandlerb64cb882011-11-29 23:48:29 -05001387 mustHaveFlags, mustNotHaveFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388
1389 synchronized (mNotificationList) {
Dianne Hackborn41203752012-08-31 14:05:51 -07001390 int index = indexOfNotificationLocked(pkg, tag, id, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 if (index >= 0) {
Fred Quintana6ecaff12009-09-25 14:23:13 -07001392 NotificationRecord r = mNotificationList.get(index);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001393
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001394 if ((r.getNotification().flags & mustHaveFlags) != mustHaveFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 return;
1396 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001397 if ((r.getNotification().flags & mustNotHaveFlags) != 0) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001398 return;
1399 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 mNotificationList.remove(index);
1402
Joe Onorato46439ce2010-11-19 13:56:21 -08001403 cancelNotificationLocked(r, sendDelete);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404 updateLightsLocked();
1405 }
1406 }
1407 }
1408
1409 /**
Daniel Sandler321e9c52012-10-12 10:59:26 -07001410 * Determine whether the userId applies to the notification in question, either because
1411 * they match exactly, or one of them is USER_ALL (which is treated as a wildcard).
1412 */
1413 private boolean notificationMatchesUserId(NotificationRecord r, int userId) {
1414 return
1415 // looking for USER_ALL notifications? match everything
1416 userId == UserHandle.USER_ALL
1417 // a notification sent to USER_ALL matches any query
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001418 || r.getUserId() == UserHandle.USER_ALL
Daniel Sandler321e9c52012-10-12 10:59:26 -07001419 // an exact user match
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001420 || r.getUserId() == userId;
Daniel Sandler321e9c52012-10-12 10:59:26 -07001421 }
1422
1423 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 * Cancels all notifications from a given package that have all of the
1425 * {@code mustHaveFlags}.
1426 */
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001427 boolean cancelAllNotificationsInt(String pkg, int mustHaveFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07001428 int mustNotHaveFlags, boolean doit, int userId) {
Daniel Sandler321e9c52012-10-12 10:59:26 -07001429 EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL_ALL, pkg, userId,
1430 mustHaveFlags, mustNotHaveFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431
1432 synchronized (mNotificationList) {
1433 final int N = mNotificationList.size();
1434 boolean canceledSomething = false;
1435 for (int i = N-1; i >= 0; --i) {
1436 NotificationRecord r = mNotificationList.get(i);
Daniel Sandler321e9c52012-10-12 10:59:26 -07001437 if (!notificationMatchesUserId(r, userId)) {
Dianne Hackborn41203752012-08-31 14:05:51 -07001438 continue;
1439 }
Amith Yamasani5ec00e92012-11-07 16:58:30 -08001440 // Don't remove notifications to all, if there's no package name specified
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001441 if (r.getUserId() == UserHandle.USER_ALL && pkg == null) {
Amith Yamasani5ec00e92012-11-07 16:58:30 -08001442 continue;
1443 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001444 if ((r.getFlags() & mustHaveFlags) != mustHaveFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 continue;
1446 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001447 if ((r.getFlags() & mustNotHaveFlags) != 0) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001448 continue;
1449 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001450 if (pkg != null && !r.sbn.pkg.equals(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 continue;
1452 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001453 canceledSomething = true;
1454 if (!doit) {
1455 return true;
1456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 mNotificationList.remove(i);
Joe Onorato46439ce2010-11-19 13:56:21 -08001458 cancelNotificationLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 }
1460 if (canceledSomething) {
1461 updateLightsLocked();
1462 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001463 return canceledSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 }
1465 }
1466
Dianne Hackborn41203752012-08-31 14:05:51 -07001467 public void cancelNotificationWithTag(String pkg, String tag, int id, int userId) {
Daniel Sandler0da673f2012-04-11 12:33:16 -04001468 checkCallerIsSystemOrSameApp(pkg);
Dianne Hackborn41203752012-08-31 14:05:51 -07001469 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07001470 Binder.getCallingUid(), userId, true, false, "cancelNotificationWithTag", pkg);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001471 // Don't allow client applications to cancel foreground service notis.
Fred Quintana6ecaff12009-09-25 14:23:13 -07001472 cancelNotification(pkg, tag, id, 0,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001473 Binder.getCallingUid() == Process.SYSTEM_UID
Dianne Hackborn41203752012-08-31 14:05:51 -07001474 ? 0 : Notification.FLAG_FOREGROUND_SERVICE, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 }
1476
Dianne Hackborn41203752012-08-31 14:05:51 -07001477 public void cancelAllNotifications(String pkg, int userId) {
Daniel Sandler0da673f2012-04-11 12:33:16 -04001478 checkCallerIsSystemOrSameApp(pkg);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001479
Dianne Hackborn41203752012-08-31 14:05:51 -07001480 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07001481 Binder.getCallingUid(), userId, true, false, "cancelAllNotifications", pkg);
Dianne Hackborn41203752012-08-31 14:05:51 -07001482
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001483 // Calling from user space, don't allow the canceling of actively
1484 // running foreground services.
Dianne Hackborn41203752012-08-31 14:05:51 -07001485 cancelAllNotificationsInt(pkg, 0, Notification.FLAG_FOREGROUND_SERVICE, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 }
1487
Daniel Sandler0da673f2012-04-11 12:33:16 -04001488 void checkCallerIsSystem() {
1489 int uid = Binder.getCallingUid();
Dianne Hackborn0c380492012-08-20 17:23:30 -07001490 if (UserHandle.getAppId(uid) == Process.SYSTEM_UID || uid == 0) {
Daniel Sandler0da673f2012-04-11 12:33:16 -04001491 return;
1492 }
1493 throw new SecurityException("Disallowed call for uid " + uid);
1494 }
1495
1496 void checkCallerIsSystemOrSameApp(String pkg) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001497 int uid = Binder.getCallingUid();
Dianne Hackborn0c380492012-08-20 17:23:30 -07001498 if (UserHandle.getAppId(uid) == Process.SYSTEM_UID || uid == 0) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001499 return;
1500 }
1501 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07001502 ApplicationInfo ai = AppGlobals.getPackageManager().getApplicationInfo(
1503 pkg, 0, UserHandle.getCallingUserId());
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001504 if (!UserHandle.isSameApp(ai.uid, uid)) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001505 throw new SecurityException("Calling uid " + uid + " gave package"
1506 + pkg + " which is owned by uid " + ai.uid);
1507 }
Amith Yamasanif203aee2012-08-29 18:41:53 -07001508 } catch (RemoteException re) {
1509 throw new SecurityException("Unknown package " + pkg + "\n" + re);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001510 }
1511 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001512
Dianne Hackborn41203752012-08-31 14:05:51 -07001513 void cancelAll(int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 synchronized (mNotificationList) {
1515 final int N = mNotificationList.size();
1516 for (int i=N-1; i>=0; i--) {
1517 NotificationRecord r = mNotificationList.get(i);
1518
Daniel Sandler321e9c52012-10-12 10:59:26 -07001519 if (!notificationMatchesUserId(r, userId)) {
Dianne Hackborn41203752012-08-31 14:05:51 -07001520 continue;
1521 }
1522
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001523 if ((r.getFlags() & (Notification.FLAG_ONGOING_EVENT
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 | Notification.FLAG_NO_CLEAR)) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 mNotificationList.remove(i);
Joe Onorato46439ce2010-11-19 13:56:21 -08001526 cancelNotificationLocked(r, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 }
1528 }
1529
1530 updateLightsLocked();
1531 }
1532 }
1533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 // lock on mNotificationList
1535 private void updateLightsLocked()
1536 {
The Android Open Source Project10592532009-03-18 17:39:46 -07001537 // handle notification lights
1538 if (mLedNotification == null) {
1539 // get next notification, if any
1540 int n = mLights.size();
1541 if (n > 0) {
1542 mLedNotification = mLights.get(n-1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 }
1544 }
Mike Lockwoodc22404a2009-12-02 11:15:02 -05001545
Mike Lockwood63b5ad92011-08-30 09:55:30 -04001546 // Don't flash while we are in a call or screen is on
1547 if (mLedNotification == null || mInCall || mScreenOn) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001548 mNotificationLight.turnOff();
The Android Open Source Project10592532009-03-18 17:39:46 -07001549 } else {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001550 final Notification ledno = mLedNotification.sbn.notification;
1551 int ledARGB = ledno.ledARGB;
1552 int ledOnMS = ledno.ledOnMS;
1553 int ledOffMS = ledno.ledOffMS;
1554 if ((ledno.defaults & Notification.DEFAULT_LIGHTS) != 0) {
Mike Lockwood670f9322010-01-20 12:13:36 -05001555 ledARGB = mDefaultNotificationColor;
1556 ledOnMS = mDefaultNotificationLedOn;
1557 ledOffMS = mDefaultNotificationLedOff;
1558 }
1559 if (mNotificationPulseEnabled) {
1560 // pulse repeatedly
1561 mNotificationLight.setFlashing(ledARGB, LightsService.LIGHT_FLASH_TIMED,
1562 ledOnMS, ledOffMS);
Mike Lockwood670f9322010-01-20 12:13:36 -05001563 }
The Android Open Source Project10592532009-03-18 17:39:46 -07001564 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565 }
1566
1567 // lock on mNotificationList
Dianne Hackborn41203752012-08-31 14:05:51 -07001568 private int indexOfNotificationLocked(String pkg, String tag, int id, int userId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 {
1570 ArrayList<NotificationRecord> list = mNotificationList;
1571 final int len = list.size();
1572 for (int i=0; i<len; i++) {
1573 NotificationRecord r = list.get(i);
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001574 if (!notificationMatchesUserId(r, userId) || r.sbn.id != id) {
Dianne Hackborn41203752012-08-31 14:05:51 -07001575 continue;
1576 }
Fred Quintana6ecaff12009-09-25 14:23:13 -07001577 if (tag == null) {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001578 if (r.sbn.tag != null) {
Fred Quintana6ecaff12009-09-25 14:23:13 -07001579 continue;
1580 }
1581 } else {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001582 if (!tag.equals(r.sbn.tag)) {
Fred Quintana6ecaff12009-09-25 14:23:13 -07001583 continue;
1584 }
1585 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001586 if (r.sbn.pkg.equals(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 return i;
1588 }
1589 }
1590 return -1;
1591 }
1592
Mike Lockwoodc22404a2009-12-02 11:15:02 -05001593 private void updateNotificationPulse() {
1594 synchronized (mNotificationList) {
1595 updateLightsLocked();
1596 }
1597 }
1598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 // ======================================================================
1600 @Override
1601 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1602 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1603 != PackageManager.PERMISSION_GRANTED) {
1604 pw.println("Permission Denial: can't dump NotificationManager from from pid="
1605 + Binder.getCallingPid()
1606 + ", uid=" + Binder.getCallingUid());
1607 return;
1608 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 pw.println("Current Notification Manager state:");
1611
1612 int N;
1613
1614 synchronized (mToastQueue) {
1615 N = mToastQueue.size();
1616 if (N > 0) {
1617 pw.println(" Toast Queue:");
1618 for (int i=0; i<N; i++) {
1619 mToastQueue.get(i).dump(pw, " ");
1620 }
1621 pw.println(" ");
1622 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 }
1625
1626 synchronized (mNotificationList) {
1627 N = mNotificationList.size();
1628 if (N > 0) {
1629 pw.println(" Notification List:");
1630 for (int i=0; i<N; i++) {
1631 mNotificationList.get(i).dump(pw, " ", mContext);
1632 }
1633 pw.println(" ");
1634 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 N = mLights.size();
1637 if (N > 0) {
1638 pw.println(" Lights List:");
1639 for (int i=0; i<N; i++) {
1640 mLights.get(i).dump(pw, " ", mContext);
1641 }
1642 pw.println(" ");
1643 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 pw.println(" mSoundNotification=" + mSoundNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 pw.println(" mVibrateNotification=" + mVibrateNotification);
Joe Onorato39f5b6a2009-07-23 12:29:19 -04001647 pw.println(" mDisabledNotifications=0x" + Integer.toHexString(mDisabledNotifications));
1648 pw.println(" mSystemReady=" + mSystemReady);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 }
1650 }
1651}