blob: b881934879d61dadb65618e2d6a6e55f9795de78 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey098d5802012-04-26 17:30:34 -070019import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
20import static org.xmlpull.v1.XmlPullParser.END_TAG;
21import static org.xmlpull.v1.XmlPullParser.START_TAG;
svetoslavganov75986cf2009-05-14 22:28:01 -070022
Dianne Hackborn41203752012-08-31 14:05:51 -070023import android.app.ActivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.app.ActivityManagerNative;
Amith Yamasanif203aee2012-08-29 18:41:53 -070025import android.app.AppGlobals;
Daniel Sandler4a900acd2013-01-30 14:04:10 -050026import android.app.AppOpsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.app.IActivityManager;
28import android.app.INotificationManager;
29import android.app.ITransientNotification;
30import android.app.Notification;
31import android.app.PendingIntent;
32import android.app.StatusBarManager;
33import android.content.BroadcastReceiver;
Daniel Sandler5feceeb2013-03-22 18:29:23 -070034import android.content.ComponentName;
Dianne Hackborn1dac2772009-06-26 18:16:48 -070035import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.content.Context;
37import android.content.Intent;
38import android.content.IntentFilter;
Daniel Sandler5feceeb2013-03-22 18:29:23 -070039import android.content.ServiceConnection;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070040import android.content.pm.ApplicationInfo;
Daniel Sandler4a900acd2013-01-30 14:04:10 -050041import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.pm.PackageManager;
Chris Wrenae9bb572013-05-15 14:50:28 -040043import android.content.pm.ResolveInfo;
44import android.content.pm.ServiceInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.PackageManager.NameNotFoundException;
46import android.content.res.Resources;
Dianne Hackborn1dac2772009-06-26 18:16:48 -070047import android.database.ContentObserver;
Daniel Sandlerf45564e2013-04-15 15:05:08 -040048import android.graphics.Bitmap;
svetoslavganov75986cf2009-05-14 22:28:01 -070049import android.media.AudioManager;
Jeff Sharkey098d5802012-04-26 17:30:34 -070050import android.media.IAudioService;
51import android.media.IRingtonePlayer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.Binder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.os.IBinder;
56import android.os.Message;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070057import android.os.Process;
svetoslavganov75986cf2009-05-14 22:28:01 -070058import android.os.RemoteException;
Jeff Sharkey098d5802012-04-26 17:30:34 -070059import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070060import android.os.UserHandle;
Daniel Sandler4b749ef2013-03-18 21:53:04 -040061import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.os.Vibrator;
63import android.provider.Settings;
Daniel Sandler5feceeb2013-03-22 18:29:23 -070064import android.service.notification.INotificationListener;
65import android.service.notification.NotificationListenerService;
66import android.service.notification.StatusBarNotification;
Daniel Sandlere96ffb12010-03-11 13:38:06 -050067import android.telephony.TelephonyManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070068import android.text.TextUtils;
Dianne Hackborn39606a02012-07-31 17:54:35 -070069import android.util.AtomicFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.util.EventLog;
71import android.util.Log;
Andy Stadler110988c2010-12-03 14:29:16 -080072import android.util.Slog;
Daniel Sandler0da673f2012-04-11 12:33:16 -040073import android.util.Xml;
svetoslavganov75986cf2009-05-14 22:28:01 -070074import android.view.accessibility.AccessibilityEvent;
75import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.widget.Toast;
77
Scott Greenwald9a05b312013-06-28 00:37:54 -040078import com.android.internal.R;
79
80import com.android.internal.notification.NotificationScorer;
Jeff Sharkey098d5802012-04-26 17:30:34 -070081import org.xmlpull.v1.XmlPullParser;
82import org.xmlpull.v1.XmlPullParserException;
Jeff Sharkey098d5802012-04-26 17:30:34 -070083
Daniel Sandler0da673f2012-04-11 12:33:16 -040084import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import java.io.FileDescriptor;
Daniel Sandler0da673f2012-04-11 12:33:16 -040086import java.io.FileInputStream;
87import java.io.FileNotFoundException;
Daniel Sandler0da673f2012-04-11 12:33:16 -040088import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import java.io.PrintWriter;
Daniel Sandlerf45564e2013-04-15 15:05:08 -040090import java.lang.reflect.Array;
Daniel Sandlerfde19b12013-01-17 00:21:05 -050091import java.util.ArrayDeque;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import java.util.ArrayList;
93import java.util.Arrays;
Daniel Sandler0da673f2012-04-11 12:33:16 -040094import java.util.HashSet;
Daniel Sandlerfde19b12013-01-17 00:21:05 -050095import java.util.Iterator;
Chris Wrenae9bb572013-05-15 14:50:28 -040096import java.util.List;
Daniel Sandlerfde19b12013-01-17 00:21:05 -050097import java.util.NoSuchElementException;
Chris Wrenae9bb572013-05-15 14:50:28 -040098import java.util.Set;
Daniel Sandler0da673f2012-04-11 12:33:16 -040099
100import libcore.io.IoUtils;
101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102
Daniel Sandlerd0a2f862010-08-03 15:29:31 -0400103/** {@hide} */
104public class NotificationManagerService extends INotificationManager.Stub
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105{
106 private static final String TAG = "NotificationService";
107 private static final boolean DBG = false;
108
Joe Onoratobd73d012010-06-04 11:44:54 -0700109 private static final int MAX_PACKAGE_NOTIFICATIONS = 50;
110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111 // message codes
112 private static final int MESSAGE_TIMEOUT = 2;
113
114 private static final int LONG_DELAY = 3500; // 3.5 seconds
115 private static final int SHORT_DELAY = 2000; // 2 seconds
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800116
117 private static final long[] DEFAULT_VIBRATE_PATTERN = {0, 250, 250, 250};
Daniel Sandleredbb3802012-11-13 20:49:47 -0800118 private static final int VIBRATE_PATTERN_MAXLEN = 8 * 2 + 1; // up to eight bumps
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119
120 private static final int DEFAULT_STREAM_TYPE = AudioManager.STREAM_NOTIFICATION;
Daniel Sandler49a2ad12012-03-28 15:46:39 -0400121 private static final boolean SCORE_ONGOING_HIGHER = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122
Daniel Sandler0da673f2012-04-11 12:33:16 -0400123 private static final int JUNK_SCORE = -1000;
124 private static final int NOTIFICATION_PRIORITY_MULTIPLIER = 10;
125 private static final int SCORE_DISPLAY_THRESHOLD = Notification.PRIORITY_MIN * NOTIFICATION_PRIORITY_MULTIPLIER;
126
Daniel Sandler526fa0e2012-12-04 14:51:50 -0500127 // Notifications with scores below this will not interrupt the user, either via LED or
128 // sound or vibration
129 private static final int SCORE_INTERRUPTION_THRESHOLD =
130 Notification.PRIORITY_LOW * NOTIFICATION_PRIORITY_MULTIPLIER;
131
Daniel Sandler0da673f2012-04-11 12:33:16 -0400132 private static final boolean ENABLE_BLOCKED_NOTIFICATIONS = true;
133 private static final boolean ENABLE_BLOCKED_TOASTS = true;
134
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700135 private static final String ENABLED_NOTIFICATION_LISTENERS_SEPARATOR = ":";
136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 final Context mContext;
138 final IActivityManager mAm;
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400139 final UserManager mUserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140 final IBinder mForegroundToken = new Binder();
141
142 private WorkerHandler mHandler;
Joe Onorato089de882010-04-12 08:18:45 -0700143 private StatusBarManagerService mStatusBar;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500144 private LightsService.Light mNotificationLight;
145 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146
Mike Lockwood670f9322010-01-20 12:13:36 -0500147 private int mDefaultNotificationColor;
148 private int mDefaultNotificationLedOn;
149 private int mDefaultNotificationLedOff;
150
Daniel Sandleredbb3802012-11-13 20:49:47 -0800151 private long[] mDefaultVibrationPattern;
152 private long[] mFallbackVibrationPattern;
153
Joe Onorato30275482009-07-08 17:09:14 -0700154 private boolean mSystemReady;
Joe Onorato39f5b6a2009-07-23 12:29:19 -0400155 private int mDisabledNotifications;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
Jeff Sharkey098d5802012-04-26 17:30:34 -0700157 private NotificationRecord mSoundNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 private NotificationRecord mVibrateNotification;
Jeff Sharkey098d5802012-04-26 17:30:34 -0700159
160 private IAudioService mAudioService;
Jeff Brownc2346132012-04-13 01:55:38 -0700161 private Vibrator mVibrator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162
Mike Lockwoodc22404a2009-12-02 11:15:02 -0500163 // for enabling and disabling notification pulse behavior
Mike Lockwood63b5ad92011-08-30 09:55:30 -0400164 private boolean mScreenOn = true;
Daniel Sandlere96ffb12010-03-11 13:38:06 -0500165 private boolean mInCall = false;
Mike Lockwoodc22404a2009-12-02 11:15:02 -0500166 private boolean mNotificationPulseEnabled;
167
Daniel Sandler09a247e2013-02-14 10:24:17 -0500168 // used as a mutex for access to all active notifications & listeners
Fred Quintana6ecaff12009-09-25 14:23:13 -0700169 private final ArrayList<NotificationRecord> mNotificationList =
170 new ArrayList<NotificationRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171
172 private ArrayList<ToastRecord> mToastQueue;
173
174 private ArrayList<NotificationRecord> mLights = new ArrayList<NotificationRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 private NotificationRecord mLedNotification;
svetoslavganov75986cf2009-05-14 22:28:01 -0700176
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500177 private final AppOpsManager mAppOps;
178
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700179 // contains connections to all connected listeners, including app services
180 // and system listeners
181 private ArrayList<NotificationListenerInfo> mListeners
182 = new ArrayList<NotificationListenerInfo>();
183 // things that will be put into mListeners as soon as they're ready
184 private ArrayList<String> mServicesBinding = new ArrayList<String>();
185 // lists the component names of all enabled (and therefore connected) listener
186 // app services for the current user only
187 private HashSet<ComponentName> mEnabledListenersForCurrentUser
188 = new HashSet<ComponentName>();
189 // Just the packages from mEnabledListenersForCurrentUser
190 private HashSet<String> mEnabledListenerPackageNames = new HashSet<String>();
Daniel Sandler09a247e2013-02-14 10:24:17 -0500191
Daniel Sandler0da673f2012-04-11 12:33:16 -0400192 // Notification control database. For now just contains disabled packages.
193 private AtomicFile mPolicyFile;
194 private HashSet<String> mBlockedPackages = new HashSet<String>();
195
196 private static final int DB_VERSION = 1;
197
198 private static final String TAG_BODY = "notification-policy";
199 private static final String ATTR_VERSION = "version";
200
201 private static final String TAG_BLOCKED_PKGS = "blocked-packages";
202 private static final String TAG_PACKAGE = "package";
203 private static final String ATTR_NAME = "name";
204
Scott Greenwald9a05b312013-06-28 00:37:54 -0400205 private final ArrayList<NotificationScorer> mScorers = new ArrayList<NotificationScorer>();
206
Daniel Sandler09a247e2013-02-14 10:24:17 -0500207 private class NotificationListenerInfo implements DeathRecipient {
208 INotificationListener listener;
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700209 ComponentName component;
Daniel Sandler09a247e2013-02-14 10:24:17 -0500210 int userid;
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400211 boolean isSystem;
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700212 ServiceConnection connection;
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400213
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700214 public NotificationListenerInfo(INotificationListener listener, ComponentName component,
215 int userid, boolean isSystem) {
Daniel Sandler09a247e2013-02-14 10:24:17 -0500216 this.listener = listener;
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700217 this.component = component;
Daniel Sandler09a247e2013-02-14 10:24:17 -0500218 this.userid = userid;
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400219 this.isSystem = isSystem;
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700220 this.connection = null;
221 }
222
223 public NotificationListenerInfo(INotificationListener listener, ComponentName component,
224 int userid, ServiceConnection connection) {
225 this.listener = listener;
226 this.component = component;
227 this.userid = userid;
228 this.isSystem = false;
229 this.connection = connection;
Daniel Sandler09a247e2013-02-14 10:24:17 -0500230 }
231
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400232 boolean enabledAndUserMatches(StatusBarNotification sbn) {
233 final int nid = sbn.getUserId();
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700234 if (!isEnabledForCurrentUser()) {
235 return false;
236 }
Daniel Sandler21ca44d2013-03-07 13:58:00 -0500237 if (this.userid == UserHandle.USER_ALL) return true;
Daniel Sandler21ca44d2013-03-07 13:58:00 -0500238 return (nid == UserHandle.USER_ALL || nid == this.userid);
239 }
240
Daniel Sandler09a247e2013-02-14 10:24:17 -0500241 public void notifyPostedIfUserMatch(StatusBarNotification sbn) {
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700242 if (!enabledAndUserMatches(sbn)) {
243 return;
244 }
Daniel Sandler09a247e2013-02-14 10:24:17 -0500245 try {
246 listener.onNotificationPosted(sbn);
247 } catch (RemoteException ex) {
Daniel Sandler1a497d32013-04-18 14:52:45 -0400248 Log.e(TAG, "unable to notify listener (posted): " + listener, ex);
Daniel Sandler09a247e2013-02-14 10:24:17 -0500249 }
250 }
251
252 public void notifyRemovedIfUserMatch(StatusBarNotification sbn) {
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400253 if (!enabledAndUserMatches(sbn)) return;
Daniel Sandler09a247e2013-02-14 10:24:17 -0500254 try {
255 listener.onNotificationRemoved(sbn);
256 } catch (RemoteException ex) {
Daniel Sandler1a497d32013-04-18 14:52:45 -0400257 Log.e(TAG, "unable to notify listener (removed): " + listener, ex);
Daniel Sandler09a247e2013-02-14 10:24:17 -0500258 }
259 }
260
261 @Override
262 public void binderDied() {
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700263 if (connection == null) {
264 // This is not a service; it won't be recreated. We can give up this connection.
265 unregisterListener(this.listener, this.userid);
266 }
Daniel Sandler09a247e2013-02-14 10:24:17 -0500267 }
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400268
269 /** convenience method for looking in mEnabledListenersForCurrentUser */
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700270 public boolean isEnabledForCurrentUser() {
271 if (this.isSystem) return true;
272 if (this.connection == null) return false;
273 return mEnabledListenersForCurrentUser.contains(this.component);
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400274 }
Daniel Sandler09a247e2013-02-14 10:24:17 -0500275 }
276
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500277 private static class Archive {
Daniel Sandler5e62e3a2013-04-15 20:57:02 -0400278 static final int BUFFER_SIZE = 250;
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500279 ArrayDeque<StatusBarNotification> mBuffer = new ArrayDeque<StatusBarNotification>(BUFFER_SIZE);
280
281 public Archive() {
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500282 }
Jeff Sharkey0c1baf92013-04-03 13:08:52 -0700283
Daniel Sandler5e62e3a2013-04-15 20:57:02 -0400284 public String toString() {
285 final StringBuilder sb = new StringBuilder();
286 final int N = mBuffer.size();
287 sb.append("Archive (");
288 sb.append(N);
289 sb.append(" notification");
290 sb.append((N==1)?")":"s)");
291 return sb.toString();
292 }
293
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500294 public void record(StatusBarNotification nr) {
295 if (mBuffer.size() == BUFFER_SIZE) {
296 mBuffer.removeFirst();
297 }
Daniel Sandler26b81d52013-05-20 20:56:43 -0400298
299 // We don't want to store the heavy bits of the notification in the archive,
300 // but other clients in the system process might be using the object, so we
301 // store a (lightened) copy.
302 mBuffer.addLast(nr.cloneLight());
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500303 }
304
Daniel Sandler5e62e3a2013-04-15 20:57:02 -0400305
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500306 public void clear() {
307 mBuffer.clear();
308 }
309
310 public Iterator<StatusBarNotification> descendingIterator() {
311 return mBuffer.descendingIterator();
312 }
313 public Iterator<StatusBarNotification> ascendingIterator() {
314 return mBuffer.iterator();
315 }
316 public Iterator<StatusBarNotification> filter(
317 final Iterator<StatusBarNotification> iter, final String pkg, final int userId) {
318 return new Iterator<StatusBarNotification>() {
319 StatusBarNotification mNext = findNext();
320
321 private StatusBarNotification findNext() {
322 while (iter.hasNext()) {
323 StatusBarNotification nr = iter.next();
Daniel Sandler4f91efd2013-04-25 16:38:41 -0400324 if ((pkg == null || nr.getPackageName() == pkg)
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500325 && (userId == UserHandle.USER_ALL || nr.getUserId() == userId)) {
326 return nr;
327 }
328 }
329 return null;
330 }
331
332 @Override
333 public boolean hasNext() {
334 return mNext == null;
335 }
336
337 @Override
338 public StatusBarNotification next() {
339 StatusBarNotification next = mNext;
340 if (next == null) {
341 throw new NoSuchElementException();
342 }
343 mNext = findNext();
344 return next;
345 }
346
347 @Override
348 public void remove() {
349 iter.remove();
350 }
351 };
352 }
Daniel Sandler78d0d252013-02-12 08:14:52 -0500353
354 public StatusBarNotification[] getArray(int count) {
355 if (count == 0) count = Archive.BUFFER_SIZE;
356 final StatusBarNotification[] a
357 = new StatusBarNotification[Math.min(count, mBuffer.size())];
358 Iterator<StatusBarNotification> iter = descendingIterator();
359 int i=0;
360 while (iter.hasNext() && i < count) {
361 a[i++] = iter.next();
362 }
363 return a;
364 }
365
366 public StatusBarNotification[] getArray(int count, String pkg, int userId) {
367 if (count == 0) count = Archive.BUFFER_SIZE;
368 final StatusBarNotification[] a
369 = new StatusBarNotification[Math.min(count, mBuffer.size())];
370 Iterator<StatusBarNotification> iter = filter(descendingIterator(), pkg, userId);
371 int i=0;
372 while (iter.hasNext() && i < count) {
373 a[i++] = iter.next();
374 }
375 return a;
376 }
377
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500378 }
379
380 Archive mArchive = new Archive();
381
Daniel Sandler0da673f2012-04-11 12:33:16 -0400382 private void loadBlockDb() {
383 synchronized(mBlockedPackages) {
384 if (mPolicyFile == null) {
385 File dir = new File("/data/system");
386 mPolicyFile = new AtomicFile(new File(dir, "notification_policy.xml"));
387
388 mBlockedPackages.clear();
389
390 FileInputStream infile = null;
391 try {
392 infile = mPolicyFile.openRead();
393 final XmlPullParser parser = Xml.newPullParser();
394 parser.setInput(infile, null);
395
396 int type;
397 String tag;
398 int version = DB_VERSION;
399 while ((type = parser.next()) != END_DOCUMENT) {
400 tag = parser.getName();
401 if (type == START_TAG) {
402 if (TAG_BODY.equals(tag)) {
403 version = Integer.parseInt(parser.getAttributeValue(null, ATTR_VERSION));
404 } else if (TAG_BLOCKED_PKGS.equals(tag)) {
405 while ((type = parser.next()) != END_DOCUMENT) {
406 tag = parser.getName();
407 if (TAG_PACKAGE.equals(tag)) {
408 mBlockedPackages.add(parser.getAttributeValue(null, ATTR_NAME));
409 } else if (TAG_BLOCKED_PKGS.equals(tag) && type == END_TAG) {
410 break;
411 }
412 }
413 }
414 }
415 }
416 } catch (FileNotFoundException e) {
417 // No data yet
418 } catch (IOException e) {
419 Log.wtf(TAG, "Unable to read blocked notifications database", e);
420 } catch (NumberFormatException e) {
421 Log.wtf(TAG, "Unable to parse blocked notifications database", e);
422 } catch (XmlPullParserException e) {
423 Log.wtf(TAG, "Unable to parse blocked notifications database", e);
424 } finally {
425 IoUtils.closeQuietly(infile);
426 }
427 }
428 }
429 }
430
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500431 /**
432 * Use this when you just want to know if notifications are OK for this package.
433 */
434 public boolean areNotificationsEnabledForPackage(String pkg, int uid) {
Daniel Sandler0da673f2012-04-11 12:33:16 -0400435 checkCallerIsSystem();
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500436 return (mAppOps.checkOpNoThrow(AppOpsManager.OP_POST_NOTIFICATION, uid, pkg)
437 == AppOpsManager.MODE_ALLOWED);
Daniel Sandler0da673f2012-04-11 12:33:16 -0400438 }
439
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500440 /** Use this when you actually want to post a notification or toast.
441 *
442 * Unchecked. Not exposed via Binder, but can be called in the course of enqueue*().
443 */
444 private boolean noteNotificationOp(String pkg, int uid) {
445 if (mAppOps.noteOpNoThrow(AppOpsManager.OP_POST_NOTIFICATION, uid, pkg)
446 != AppOpsManager.MODE_ALLOWED) {
447 Slog.v(TAG, "notifications are disabled by AppOps for " + pkg);
448 return false;
Daniel Sandler0da673f2012-04-11 12:33:16 -0400449 }
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500450 return true;
Daniel Sandler0da673f2012-04-11 12:33:16 -0400451 }
452
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500453 public void setNotificationsEnabledForPackage(String pkg, int uid, boolean enabled) {
Daniel Sandler0da673f2012-04-11 12:33:16 -0400454 checkCallerIsSystem();
Daniel Sandler32e698b2013-04-18 10:51:35 -0400455
456 Slog.v(TAG, (enabled?"en":"dis") + "abling notifications for " + pkg);
457
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500458 mAppOps.setMode(AppOpsManager.OP_POST_NOTIFICATION, uid, pkg,
459 enabled ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
Daniel Sandler32e698b2013-04-18 10:51:35 -0400460
461 // Now, cancel any outstanding notifications that are part of a just-disabled app
462 if (ENABLE_BLOCKED_NOTIFICATIONS && !enabled) {
463 cancelAllNotificationsInt(pkg, 0, 0, true, UserHandle.getUserId(uid));
464 }
Daniel Sandler0da673f2012-04-11 12:33:16 -0400465 }
466
467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 private static String idDebugString(Context baseContext, String packageName, int id) {
469 Context c = null;
470
471 if (packageName != null) {
472 try {
473 c = baseContext.createPackageContext(packageName, 0);
474 } catch (NameNotFoundException e) {
475 c = baseContext;
476 }
477 } else {
478 c = baseContext;
479 }
480
481 String pkg;
482 String type;
483 String name;
484
485 Resources r = c.getResources();
486 try {
487 return r.getResourceName(id);
488 } catch (Resources.NotFoundException e) {
489 return "<name unknown>";
490 }
491 }
492
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700493 /**
494 * System-only API for getting a list of current (i.e. not cleared) notifications.
495 *
496 * Requires ACCESS_NOTIFICATIONS which is signature|system.
497 */
498 @Override
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500499 public StatusBarNotification[] getActiveNotifications(String callingPkg) {
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400500 // enforce() will ensure the calling uid has the correct permission
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500501 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_NOTIFICATIONS,
Daniel Sandler78d0d252013-02-12 08:14:52 -0500502 "NotificationManagerService.getActiveNotifications");
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500503
504 StatusBarNotification[] tmp = null;
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500505 int uid = Binder.getCallingUid();
506
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400507 // noteOp will check to make sure the callingPkg matches the uid
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500508 if (mAppOps.noteOpNoThrow(AppOpsManager.OP_ACCESS_NOTIFICATIONS, uid, callingPkg)
509 == AppOpsManager.MODE_ALLOWED) {
510 synchronized (mNotificationList) {
511 tmp = new StatusBarNotification[mNotificationList.size()];
512 final int N = mNotificationList.size();
513 for (int i=0; i<N; i++) {
514 tmp[i] = mNotificationList.get(i).sbn;
515 }
516 }
517 }
518 return tmp;
519 }
520
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700521 /**
522 * System-only API for getting a list of recent (cleared, no longer shown) notifications.
523 *
524 * Requires ACCESS_NOTIFICATIONS which is signature|system.
525 */
526 @Override
Daniel Sandler78d0d252013-02-12 08:14:52 -0500527 public StatusBarNotification[] getHistoricalNotifications(String callingPkg, int count) {
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400528 // enforce() will ensure the calling uid has the correct permission
Daniel Sandler78d0d252013-02-12 08:14:52 -0500529 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_NOTIFICATIONS,
530 "NotificationManagerService.getHistoricalNotifications");
531
532 StatusBarNotification[] tmp = null;
533 int uid = Binder.getCallingUid();
534
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400535 // noteOp will check to make sure the callingPkg matches the uid
Daniel Sandler78d0d252013-02-12 08:14:52 -0500536 if (mAppOps.noteOpNoThrow(AppOpsManager.OP_ACCESS_NOTIFICATIONS, uid, callingPkg)
537 == AppOpsManager.MODE_ALLOWED) {
538 synchronized (mArchive) {
539 tmp = mArchive.getArray(count);
540 }
541 }
542 return tmp;
543 }
544
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700545 /**
Chris Wrenae9bb572013-05-15 14:50:28 -0400546 * Remove notification access for any services that no longer exist.
547 */
548 void disableNonexistentListeners() {
549 int currentUser = ActivityManager.getCurrentUser();
550 String flatIn = Settings.Secure.getStringForUser(
551 mContext.getContentResolver(),
552 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
553 currentUser);
554 if (!TextUtils.isEmpty(flatIn)) {
555 if (DBG) Slog.v(TAG, "flat before: " + flatIn);
556 PackageManager pm = mContext.getPackageManager();
557 List<ResolveInfo> installedServices = pm.queryIntentServicesAsUser(
558 new Intent(NotificationListenerService.SERVICE_INTERFACE),
559 PackageManager.GET_SERVICES | PackageManager.GET_META_DATA,
560 currentUser);
561
562 Set<ComponentName> installed = new HashSet<ComponentName>();
563 for (int i = 0, count = installedServices.size(); i < count; i++) {
564 ResolveInfo resolveInfo = installedServices.get(i);
565 ServiceInfo info = resolveInfo.serviceInfo;
566
567 if (!android.Manifest.permission.BIND_NOTIFICATION_LISTENER_SERVICE.equals(
568 info.permission)) {
569 Slog.w(TAG, "Skipping notification listener service "
570 + info.packageName + "/" + info.name
571 + ": it does not require the permission "
572 + android.Manifest.permission.BIND_NOTIFICATION_LISTENER_SERVICE);
573 continue;
574 }
575 installed.add(new ComponentName(info.packageName, info.name));
576 }
577
578 String flatOut = "";
579 if (!installed.isEmpty()) {
580 String[] enabled = flatIn.split(ENABLED_NOTIFICATION_LISTENERS_SEPARATOR);
581 ArrayList<String> remaining = new ArrayList<String>(enabled.length);
582 for (int i = 0; i < enabled.length; i++) {
583 ComponentName enabledComponent = ComponentName.unflattenFromString(enabled[i]);
584 if (installed.contains(enabledComponent)) {
585 remaining.add(enabled[i]);
586 }
587 }
588 flatOut = TextUtils.join(ENABLED_NOTIFICATION_LISTENERS_SEPARATOR, remaining);
589 }
590 if (DBG) Slog.v(TAG, "flat after: " + flatOut);
591 if (!flatIn.equals(flatOut)) {
592 Settings.Secure.putStringForUser(mContext.getContentResolver(),
593 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
594 flatOut, currentUser);
595 }
596 }
597 }
598
599 /**
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700600 * Called whenever packages change, the user switches, or ENABLED_NOTIFICATION_LISTENERS
601 * is altered. (For example in response to USER_SWITCHED in our broadcast receiver)
602 */
603 void rebindListenerServices() {
John Spurlock3ec4e702013-05-16 13:42:38 -0400604 final int currentUser = ActivityManager.getCurrentUser();
605 String flat = Settings.Secure.getStringForUser(
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700606 mContext.getContentResolver(),
John Spurlock3ec4e702013-05-16 13:42:38 -0400607 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
608 currentUser);
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700609
610 NotificationListenerInfo[] toRemove = new NotificationListenerInfo[mListeners.size()];
611 final ArrayList<ComponentName> toAdd;
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700612
613 synchronized (mNotificationList) {
614 // unbind and remove all existing listeners
615 toRemove = mListeners.toArray(toRemove);
616
617 toAdd = new ArrayList<ComponentName>();
618 final HashSet<ComponentName> newEnabled = new HashSet<ComponentName>();
619 final HashSet<String> newPackages = new HashSet<String>();
620
621 // decode the list of components
622 if (flat != null) {
623 String[] components = flat.split(ENABLED_NOTIFICATION_LISTENERS_SEPARATOR);
624 for (int i=0; i<components.length; i++) {
625 final ComponentName component
626 = ComponentName.unflattenFromString(components[i]);
627 if (component != null) {
628 newEnabled.add(component);
629 toAdd.add(component);
630 newPackages.add(component.getPackageName());
631 }
632 }
633
634 mEnabledListenersForCurrentUser = newEnabled;
635 mEnabledListenerPackageNames = newPackages;
636 }
637 }
638
639 for (NotificationListenerInfo info : toRemove) {
640 final ComponentName component = info.component;
641 final int oldUser = info.userid;
642 Slog.v(TAG, "disabling notification listener for user " + oldUser + ": " + component);
643 unregisterListenerService(component, info.userid);
644 }
645
646 final int N = toAdd.size();
647 for (int i=0; i<N; i++) {
648 final ComponentName component = toAdd.get(i);
649 Slog.v(TAG, "enabling notification listener for user " + currentUser + ": "
650 + component);
651 registerListenerService(component, currentUser);
652 }
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400653 }
654
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700655 /**
656 * Register a listener binder directly with the notification manager.
657 *
658 * Only works with system callers. Apps should extend
659 * {@link android.service.notification.NotificationListenerService}.
660 */
Daniel Sandler09a247e2013-02-14 10:24:17 -0500661 @Override
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400662 public void registerListener(final INotificationListener listener,
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700663 final ComponentName component, final int userid) {
664 checkCallerIsSystem();
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400665
Daniel Sandler09a247e2013-02-14 10:24:17 -0500666 synchronized (mNotificationList) {
667 try {
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400668 NotificationListenerInfo info
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700669 = new NotificationListenerInfo(listener, component, userid, true);
Daniel Sandler09a247e2013-02-14 10:24:17 -0500670 listener.asBinder().linkToDeath(info, 0);
671 mListeners.add(info);
672 } catch (RemoteException e) {
673 // already dead
674 }
675 }
676 }
677
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700678 /**
679 * Version of registerListener that takes the name of a
680 * {@link android.service.notification.NotificationListenerService} to bind to.
681 *
682 * This is the mechanism by which third parties may subscribe to notifications.
683 */
684 private void registerListenerService(final ComponentName name, final int userid) {
685 checkCallerIsSystem();
686
687 if (DBG) Slog.v(TAG, "registerListenerService: " + name + " u=" + userid);
688
689 synchronized (mNotificationList) {
690 final String servicesBindingTag = name.toString() + "/" + userid;
691 if (mServicesBinding.contains(servicesBindingTag)) {
692 // stop registering this thing already! we're working on it
693 return;
694 }
695 mServicesBinding.add(servicesBindingTag);
696
697 final int N = mListeners.size();
698 for (int i=N-1; i>=0; i--) {
699 final NotificationListenerInfo info = mListeners.get(i);
700 if (name.equals(info.component)
701 && info.userid == userid) {
702 // cut old connections
703 if (DBG) Slog.v(TAG, " disconnecting old listener: " + info.listener);
704 mListeners.remove(i);
705 if (info.connection != null) {
706 mContext.unbindService(info.connection);
707 }
708 }
709 }
710
711 Intent intent = new Intent(NotificationListenerService.SERVICE_INTERFACE);
712 intent.setComponent(name);
713
714 intent.putExtra(Intent.EXTRA_CLIENT_LABEL,
Scott Greenwald9a05b312013-06-28 00:37:54 -0400715 R.string.notification_listener_binding_label);
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700716 intent.putExtra(Intent.EXTRA_CLIENT_INTENT, PendingIntent.getActivity(
717 mContext, 0, new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS), 0));
718
719 try {
720 if (DBG) Slog.v(TAG, "binding: " + intent);
721 if (!mContext.bindServiceAsUser(intent,
722 new ServiceConnection() {
723 INotificationListener mListener;
724 @Override
725 public void onServiceConnected(ComponentName name, IBinder service) {
726 synchronized (mNotificationList) {
727 mServicesBinding.remove(servicesBindingTag);
728 try {
729 mListener = INotificationListener.Stub.asInterface(service);
730 NotificationListenerInfo info = new NotificationListenerInfo(
731 mListener, name, userid, this);
732 service.linkToDeath(info, 0);
733 mListeners.add(info);
734 } catch (RemoteException e) {
735 // already dead
736 }
737 }
738 }
739
740 @Override
741 public void onServiceDisconnected(ComponentName name) {
742 Slog.v(TAG, "notification listener connection lost: " + name);
743 }
744 },
745 Context.BIND_AUTO_CREATE,
746 new UserHandle(userid)))
747 {
748 mServicesBinding.remove(servicesBindingTag);
749 Slog.w(TAG, "Unable to bind listener service: " + intent);
750 return;
751 }
752 } catch (SecurityException ex) {
753 Slog.e(TAG, "Unable to bind listener service: " + intent, ex);
754 return;
755 }
756 }
757 }
758
759 /**
760 * Remove a listener binder directly
761 */
Daniel Sandler09a247e2013-02-14 10:24:17 -0500762 @Override
763 public void unregisterListener(INotificationListener listener, int userid) {
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400764 // no need to check permissions; if your listener binder is in the list,
765 // that's proof that you had permission to add it in the first place
766
Daniel Sandler09a247e2013-02-14 10:24:17 -0500767 synchronized (mNotificationList) {
768 final int N = mListeners.size();
769 for (int i=N-1; i>=0; i--) {
770 final NotificationListenerInfo info = mListeners.get(i);
Andrew Wilson152942b2013-05-22 09:35:35 -0700771 if (info.listener.asBinder() == listener.asBinder()
772 && info.userid == userid) {
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700773 mListeners.remove(i);
774 if (info.connection != null) {
775 mContext.unbindService(info.connection);
776 }
Daniel Sandler09a247e2013-02-14 10:24:17 -0500777 }
778 }
779 }
780 }
781
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700782 /**
783 * Remove a listener service for the given user by ComponentName
784 */
785 private void unregisterListenerService(ComponentName name, int userid) {
786 checkCallerIsSystem();
787
788 synchronized (mNotificationList) {
789 final int N = mListeners.size();
790 for (int i=N-1; i>=0; i--) {
791 final NotificationListenerInfo info = mListeners.get(i);
792 if (name.equals(info.component)
793 && info.userid == userid) {
794 mListeners.remove(i);
795 if (info.connection != null) {
Daniel Sandlerc1b49bd2013-05-07 13:53:47 -0400796 try {
797 mContext.unbindService(info.connection);
798 } catch (IllegalArgumentException ex) {
799 // something happened to the service: we think we have a connection
800 // but it's bogus.
801 Slog.e(TAG, "Listener " + name + " could not be unbound: " + ex);
802 }
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700803 }
804 }
805 }
806 }
807 }
808
809 /**
810 * asynchronously notify all listeners about a new notification
811 */
Daniel Sandler09a247e2013-02-14 10:24:17 -0500812 private void notifyPostedLocked(NotificationRecord n) {
Daniel Sandler1a497d32013-04-18 14:52:45 -0400813 // make a copy in case changes are made to the underlying Notification object
814 final StatusBarNotification sbn = n.sbn.clone();
Daniel Sandler09a247e2013-02-14 10:24:17 -0500815 for (final NotificationListenerInfo info : mListeners) {
816 mHandler.post(new Runnable() {
817 @Override
818 public void run() {
819 info.notifyPostedIfUserMatch(sbn);
820 }});
821 }
822 }
823
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700824 /**
825 * asynchronously notify all listeners about a removed notification
826 */
Daniel Sandler09a247e2013-02-14 10:24:17 -0500827 private void notifyRemovedLocked(NotificationRecord n) {
Daniel Sandler1a497d32013-04-18 14:52:45 -0400828 // make a copy in case changes are made to the underlying Notification object
829 // NOTE: this copy is lightweight: it doesn't include heavyweight parts of the notification
830 final StatusBarNotification sbn_light = n.sbn.cloneLight();
831
Daniel Sandler09a247e2013-02-14 10:24:17 -0500832 for (final NotificationListenerInfo info : mListeners) {
833 mHandler.post(new Runnable() {
834 @Override
835 public void run() {
Daniel Sandler1a497d32013-04-18 14:52:45 -0400836 info.notifyRemovedIfUserMatch(sbn_light);
Daniel Sandler09a247e2013-02-14 10:24:17 -0500837 }});
838 }
839 }
840
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700841 // -- APIs to support listeners clicking/clearing notifications --
842
843 private NotificationListenerInfo checkListenerToken(INotificationListener listener) {
844 final IBinder token = listener.asBinder();
845 final int N = mListeners.size();
846 for (int i=0; i<N; i++) {
847 final NotificationListenerInfo info = mListeners.get(i);
848 if (info.listener.asBinder() == token) return info;
849 }
850 throw new SecurityException("Disallowed call from unknown listener: " + listener);
851 }
852
853 /**
854 * Allow an INotificationListener to simulate a "clear all" operation.
855 *
856 * {@see com.android.server.StatusBarManagerService.NotificationCallbacks#onClearAllNotifications}
857 *
858 * @param token The binder for the listener, to check that the caller is allowed
859 */
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400860 public void cancelAllNotificationsFromListener(INotificationListener token) {
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700861 NotificationListenerInfo info = checkListenerToken(token);
862 long identity = Binder.clearCallingIdentity();
863 try {
864 cancelAll(info.userid);
865 } finally {
866 Binder.restoreCallingIdentity(identity);
867 }
868 }
869
870 /**
871 * Allow an INotificationListener to simulate clearing (dismissing) a single notification.
872 *
873 * {@see com.android.server.StatusBarManagerService.NotificationCallbacks#onNotificationClear}
874 *
875 * @param token The binder for the listener, to check that the caller is allowed
876 */
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400877 public void cancelNotificationFromListener(INotificationListener token, String pkg, String tag, int id) {
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700878 NotificationListenerInfo info = checkListenerToken(token);
879 long identity = Binder.clearCallingIdentity();
880 try {
881 cancelNotification(pkg, tag, id, 0,
882 Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE,
883 true,
884 info.userid);
885 } finally {
886 Binder.restoreCallingIdentity(identity);
887 }
888 }
889
Daniel Sandler25cf8ce2013-04-24 15:34:57 -0400890 /**
891 * Allow an INotificationListener to request the list of outstanding notifications seen by
892 * the current user. Useful when starting up, after which point the listener callbacks should
893 * be used.
894 *
895 * @param token The binder for the listener, to check that the caller is allowed
896 */
897 public StatusBarNotification[] getActiveNotificationsFromListener(INotificationListener token) {
898 NotificationListenerInfo info = checkListenerToken(token);
899
900 StatusBarNotification[] result = new StatusBarNotification[0];
901 ArrayList<StatusBarNotification> list = new ArrayList<StatusBarNotification>();
902 synchronized (mNotificationList) {
903 final int N = mNotificationList.size();
904 for (int i=0; i<N; i++) {
905 StatusBarNotification sbn = mNotificationList.get(i).sbn;
906 if (info.enabledAndUserMatches(sbn)) {
907 list.add(sbn);
908 }
909 }
910 }
911 return list.toArray(result);
912 }
913
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700914 // -- end of listener APIs --
915
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500916 public static final class NotificationRecord
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 {
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500918 final StatusBarNotification sbn;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 IBinder statusBarKey;
920
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500921 NotificationRecord(StatusBarNotification sbn)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 {
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500923 this.sbn = sbn;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 }
Fred Quintana6ecaff12009-09-25 14:23:13 -0700925
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400926 public Notification getNotification() { return sbn.getNotification(); }
927 public int getFlags() { return sbn.getNotification().flags; }
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500928 public int getUserId() { return sbn.getUserId(); }
929
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 void dump(PrintWriter pw, String prefix, Context baseContext) {
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400931 final Notification notification = sbn.getNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 pw.println(prefix + this);
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400933 pw.println(prefix + " uid=" + sbn.getUid() + " userId=" + sbn.getUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 pw.println(prefix + " icon=0x" + Integer.toHexString(notification.icon)
Daniel Sandler4f91efd2013-04-25 16:38:41 -0400935 + " / " + idDebugString(baseContext, sbn.getPackageName(), notification.icon));
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400936 pw.println(prefix + " pri=" + notification.priority + " score=" + sbn.getScore());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 pw.println(prefix + " contentIntent=" + notification.contentIntent);
938 pw.println(prefix + " deleteIntent=" + notification.deleteIntent);
939 pw.println(prefix + " tickerText=" + notification.tickerText);
940 pw.println(prefix + " contentView=" + notification.contentView);
Daniel Sandlerf45564e2013-04-15 15:05:08 -0400941 pw.println(prefix + String.format(" defaults=0x%08x flags=0x%08x",
942 notification.defaults, notification.flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 pw.println(prefix + " sound=" + notification.sound);
944 pw.println(prefix + " vibrate=" + Arrays.toString(notification.vibrate));
Daniel Sandlerf45564e2013-04-15 15:05:08 -0400945 pw.println(prefix + String.format(" led=0x%08x onMs=%d offMs=%d",
946 notification.ledARGB, notification.ledOnMS, notification.ledOffMS));
947 if (notification.actions != null && notification.actions.length > 0) {
948 pw.println(prefix + " actions={");
949 final int N = notification.actions.length;
950 for (int i=0; i<N; i++) {
951 final Notification.Action action = notification.actions[i];
952 pw.println(String.format("%s [%d] \"%s\" -> %s",
953 prefix,
954 i,
955 action.title,
956 action.actionIntent.toString()
957 ));
958 }
959 pw.println(prefix + " }");
960 }
961 if (notification.extras != null && notification.extras.size() > 0) {
962 pw.println(prefix + " extras={");
963 for (String key : notification.extras.keySet()) {
964 pw.print(prefix + " " + key + "=");
965 Object val = notification.extras.get(key);
966 if (val == null) {
967 pw.println("null");
968 } else {
969 pw.print(val.toString());
970 if (val instanceof Bitmap) {
971 pw.print(String.format(" (%dx%d)",
972 ((Bitmap) val).getWidth(),
973 ((Bitmap) val).getHeight()));
974 } else if (val.getClass().isArray()) {
975 pw.println(" {");
976 final int N = Array.getLength(val);
977 for (int i=0; i<N; i++) {
978 if (i > 0) pw.println(",");
979 pw.print(prefix + " " + Array.get(val, i));
980 }
981 pw.print("\n" + prefix + " }");
982 }
983 pw.println();
984 }
985 }
986 pw.println(prefix + " }");
987 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 @Override
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500991 public final String toString() {
992 return String.format(
993 "NotificationRecord(0x%08x: pkg=%s user=%s id=%d tag=%s score=%d: %s)",
994 System.identityHashCode(this),
Daniel Sandler4f91efd2013-04-25 16:38:41 -0400995 this.sbn.getPackageName(), this.sbn.getUser(), this.sbn.getId(), this.sbn.getTag(),
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400996 this.sbn.getScore(), this.sbn.getNotification());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 }
998 }
999
1000 private static final class ToastRecord
1001 {
1002 final int pid;
1003 final String pkg;
1004 final ITransientNotification callback;
1005 int duration;
1006
1007 ToastRecord(int pid, String pkg, ITransientNotification callback, int duration)
1008 {
1009 this.pid = pid;
1010 this.pkg = pkg;
1011 this.callback = callback;
1012 this.duration = duration;
1013 }
1014
1015 void update(int duration) {
1016 this.duration = duration;
1017 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 void dump(PrintWriter pw, String prefix) {
1020 pw.println(prefix + this);
1021 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023 @Override
1024 public final String toString()
1025 {
1026 return "ToastRecord{"
1027 + Integer.toHexString(System.identityHashCode(this))
1028 + " pkg=" + pkg
1029 + " callback=" + callback
1030 + " duration=" + duration;
1031 }
1032 }
1033
Joe Onorato089de882010-04-12 08:18:45 -07001034 private StatusBarManagerService.NotificationCallbacks mNotificationCallbacks
1035 = new StatusBarManagerService.NotificationCallbacks() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036
1037 public void onSetDisabled(int status) {
1038 synchronized (mNotificationList) {
1039 mDisabledNotifications = status;
1040 if ((mDisabledNotifications & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) {
1041 // cancel whatever's going on
1042 long identity = Binder.clearCallingIdentity();
1043 try {
Jeff Sharkey098d5802012-04-26 17:30:34 -07001044 final IRingtonePlayer player = mAudioService.getRingtonePlayer();
1045 if (player != null) {
1046 player.stopAsync();
1047 }
1048 } catch (RemoteException e) {
1049 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 Binder.restoreCallingIdentity(identity);
1051 }
1052
1053 identity = Binder.clearCallingIdentity();
1054 try {
1055 mVibrator.cancel();
Jeff Sharkey098d5802012-04-26 17:30:34 -07001056 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 Binder.restoreCallingIdentity(identity);
1058 }
1059 }
1060 }
1061 }
1062
1063 public void onClearAll() {
Dianne Hackborn41203752012-08-31 14:05:51 -07001064 // XXX to be totally correct, the caller should tell us which user
1065 // this is for.
1066 cancelAll(ActivityManager.getCurrentUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 }
1068
Fred Quintana6ecaff12009-09-25 14:23:13 -07001069 public void onNotificationClick(String pkg, String tag, int id) {
Dianne Hackborn41203752012-08-31 14:05:51 -07001070 // XXX to be totally correct, the caller should tell us which user
1071 // this is for.
Fred Quintana6ecaff12009-09-25 14:23:13 -07001072 cancelNotification(pkg, tag, id, Notification.FLAG_AUTO_CANCEL,
Dianne Hackborn41203752012-08-31 14:05:51 -07001073 Notification.FLAG_FOREGROUND_SERVICE, false,
1074 ActivityManager.getCurrentUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 }
1076
Daniel Sandler0f0b11c2010-08-04 15:54:58 -04001077 public void onNotificationClear(String pkg, String tag, int id) {
Dianne Hackborn41203752012-08-31 14:05:51 -07001078 // XXX to be totally correct, the caller should tell us which user
1079 // this is for.
Joe Onorato46439ce2010-11-19 13:56:21 -08001080 cancelNotification(pkg, tag, id, 0,
1081 Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE,
Dianne Hackborn41203752012-08-31 14:05:51 -07001082 true, ActivityManager.getCurrentUser());
Daniel Sandler0f0b11c2010-08-04 15:54:58 -04001083 }
1084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 public void onPanelRevealed() {
1086 synchronized (mNotificationList) {
1087 // sound
1088 mSoundNotification = null;
Jeff Sharkey098d5802012-04-26 17:30:34 -07001089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 long identity = Binder.clearCallingIdentity();
1091 try {
Jeff Sharkey098d5802012-04-26 17:30:34 -07001092 final IRingtonePlayer player = mAudioService.getRingtonePlayer();
1093 if (player != null) {
1094 player.stopAsync();
1095 }
1096 } catch (RemoteException e) {
1097 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 Binder.restoreCallingIdentity(identity);
1099 }
1100
1101 // vibrate
1102 mVibrateNotification = null;
1103 identity = Binder.clearCallingIdentity();
1104 try {
1105 mVibrator.cancel();
Jeff Sharkey098d5802012-04-26 17:30:34 -07001106 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 Binder.restoreCallingIdentity(identity);
1108 }
1109
1110 // light
1111 mLights.clear();
1112 mLedNotification = null;
1113 updateLightsLocked();
1114 }
1115 }
Joe Onorato005847b2010-06-04 16:08:02 -04001116
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001117 public void onNotificationError(String pkg, String tag, int id,
1118 int uid, int initialPid, String message) {
Daniel Sandlerd0a2f862010-08-03 15:29:31 -04001119 Slog.d(TAG, "onNotification error pkg=" + pkg + " tag=" + tag + " id=" + id
1120 + "; will crashApplication(uid=" + uid + ", pid=" + initialPid + ")");
Dianne Hackborn41203752012-08-31 14:05:51 -07001121 // XXX to be totally correct, the caller should tell us which user
1122 // this is for.
1123 cancelNotification(pkg, tag, id, 0, 0, false, UserHandle.getUserId(uid));
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001124 long ident = Binder.clearCallingIdentity();
1125 try {
1126 ActivityManagerNative.getDefault().crashApplication(uid, initialPid, pkg,
1127 "Bad notification posted from package " + pkg
1128 + ": " + message);
1129 } catch (RemoteException e) {
1130 }
1131 Binder.restoreCallingIdentity(ident);
Joe Onorato005847b2010-06-04 16:08:02 -04001132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 };
1134
1135 private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
1136 @Override
1137 public void onReceive(Context context, Intent intent) {
1138 String action = intent.getAction();
1139
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001140 boolean queryRestart = false;
Chris Wrenae9bb572013-05-15 14:50:28 -04001141 boolean queryRemove = false;
Daniel Sandler26ece572012-06-01 15:38:46 -04001142 boolean packageChanged = false;
John Spurlock79f78922013-05-16 09:10:05 -04001143 boolean cancelNotifications = true;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001144
Chris Wren3da73022013-05-10 14:41:21 -04001145 if (action.equals(Intent.ACTION_PACKAGE_ADDED)
Chris Wrenae9bb572013-05-15 14:50:28 -04001146 || (queryRemove=action.equals(Intent.ACTION_PACKAGE_REMOVED))
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001147 || action.equals(Intent.ACTION_PACKAGE_RESTARTED)
Daniel Sandler26ece572012-06-01 15:38:46 -04001148 || (packageChanged=action.equals(Intent.ACTION_PACKAGE_CHANGED))
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001149 || (queryRestart=action.equals(Intent.ACTION_QUERY_PACKAGE_RESTART))
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001150 || action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001151 String pkgList[] = null;
Chris Wrenae9bb572013-05-15 14:50:28 -04001152 boolean queryReplace = queryRemove &&
1153 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
1154 if (DBG) Slog.i(TAG, "queryReplace=" + queryReplace);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001155 if (action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001156 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001157 } else if (queryRestart) {
1158 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001159 } else {
1160 Uri uri = intent.getData();
1161 if (uri == null) {
1162 return;
1163 }
1164 String pkgName = uri.getSchemeSpecificPart();
1165 if (pkgName == null) {
1166 return;
1167 }
Daniel Sandler26ece572012-06-01 15:38:46 -04001168 if (packageChanged) {
1169 // We cancel notifications for packages which have just been disabled
1170 final int enabled = mContext.getPackageManager()
1171 .getApplicationEnabledSetting(pkgName);
1172 if (enabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
1173 || enabled == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
John Spurlock79f78922013-05-16 09:10:05 -04001174 cancelNotifications = false;
Daniel Sandler26ece572012-06-01 15:38:46 -04001175 }
1176 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001177 pkgList = new String[]{pkgName};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 }
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001179
1180 boolean anyListenersInvolved = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001181 if (pkgList != null && (pkgList.length > 0)) {
1182 for (String pkgName : pkgList) {
John Spurlock79f78922013-05-16 09:10:05 -04001183 if (cancelNotifications) {
1184 cancelAllNotificationsInt(pkgName, 0, 0, !queryRestart,
1185 UserHandle.USER_ALL);
1186 }
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001187 if (mEnabledListenerPackageNames.contains(pkgName)) {
1188 anyListenersInvolved = true;
1189 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 }
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001192
1193 if (anyListenersInvolved) {
Chris Wrenae9bb572013-05-15 14:50:28 -04001194 // if we're not replacing a package, clean up orphaned bits
1195 if (!queryReplace) {
1196 disableNonexistentListeners();
1197 }
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001198 // make sure we're still bound to any of our
1199 // listeners who may have just upgraded
1200 rebindListenerServices();
1201 }
Mike Lockwood63b5ad92011-08-30 09:55:30 -04001202 } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
1203 // Keep track of screen on/off state, but do not turn off the notification light
1204 // until user passes through the lock screen or views the notification.
1205 mScreenOn = true;
1206 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
1207 mScreenOn = false;
Daniel Sandlere96ffb12010-03-11 13:38:06 -05001208 } else if (action.equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
Mike Lockwood63b5ad92011-08-30 09:55:30 -04001209 mInCall = (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
1210 TelephonyManager.EXTRA_STATE_OFFHOOK));
Daniel Sandlere96ffb12010-03-11 13:38:06 -05001211 updateNotificationPulse();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001212 } else if (action.equals(Intent.ACTION_USER_STOPPED)) {
1213 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
1214 if (userHandle >= 0) {
Dianne Hackborn41203752012-08-31 14:05:51 -07001215 cancelAllNotificationsInt(null, 0, 0, true, userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001216 }
Mike Lockwood63b5ad92011-08-30 09:55:30 -04001217 } else if (action.equals(Intent.ACTION_USER_PRESENT)) {
1218 // turn off LED when user passes through lock screen
1219 mNotificationLight.turnOff();
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001220 } else if (action.equals(Intent.ACTION_USER_SWITCHED)) {
1221 // reload per-user settings
1222 mSettingsObserver.update(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 }
1224 }
1225 };
1226
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001227 class SettingsObserver extends ContentObserver {
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001228 private final Uri NOTIFICATION_LIGHT_PULSE_URI
1229 = Settings.System.getUriFor(Settings.System.NOTIFICATION_LIGHT_PULSE);
1230
1231 private final Uri ENABLED_NOTIFICATION_LISTENERS_URI
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001232 = Settings.Secure.getUriFor(Settings.Secure.ENABLED_NOTIFICATION_LISTENERS);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001233
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001234 SettingsObserver(Handler handler) {
1235 super(handler);
1236 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001237
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001238 void observe() {
1239 ContentResolver resolver = mContext.getContentResolver();
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001240 resolver.registerContentObserver(NOTIFICATION_LIGHT_PULSE_URI,
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001241 false, this, UserHandle.USER_ALL);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001242 resolver.registerContentObserver(ENABLED_NOTIFICATION_LISTENERS_URI,
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001243 false, this, UserHandle.USER_ALL);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001244 update(null);
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001245 }
1246
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001247 @Override public void onChange(boolean selfChange, Uri uri) {
1248 update(uri);
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001249 }
1250
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001251 public void update(Uri uri) {
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001252 ContentResolver resolver = mContext.getContentResolver();
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001253 if (uri == null || NOTIFICATION_LIGHT_PULSE_URI.equals(uri)) {
1254 boolean pulseEnabled = Settings.System.getInt(resolver,
1255 Settings.System.NOTIFICATION_LIGHT_PULSE, 0) != 0;
1256 if (mNotificationPulseEnabled != pulseEnabled) {
1257 mNotificationPulseEnabled = pulseEnabled;
1258 updateNotificationPulse();
1259 }
1260 }
1261 if (uri == null || ENABLED_NOTIFICATION_LISTENERS_URI.equals(uri)) {
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001262 rebindListenerServices();
Mike Lockwoodc22404a2009-12-02 11:15:02 -05001263 }
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001264 }
1265 }
Mike Lockwoodc22404a2009-12-02 11:15:02 -05001266
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001267 private SettingsObserver mSettingsObserver;
1268
Daniel Sandleredbb3802012-11-13 20:49:47 -08001269 static long[] getLongArray(Resources r, int resid, int maxlen, long[] def) {
1270 int[] ar = r.getIntArray(resid);
1271 if (ar == null) {
1272 return def;
1273 }
1274 final int len = ar.length > maxlen ? maxlen : ar.length;
1275 long[] out = new long[len];
1276 for (int i=0; i<len; i++) {
1277 out[i] = ar[i];
1278 }
1279 return out;
1280 }
1281
Joe Onorato089de882010-04-12 08:18:45 -07001282 NotificationManagerService(Context context, StatusBarManagerService statusBar,
Mike Lockwood3a322132009-11-24 00:30:52 -05001283 LightsService lights)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 {
1285 super();
1286 mContext = context;
Jeff Brownc2346132012-04-13 01:55:38 -07001287 mVibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 mAm = ActivityManagerNative.getDefault();
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001289 mUserManager = (UserManager)context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 mToastQueue = new ArrayList<ToastRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 mHandler = new WorkerHandler();
San Mehat3ee13172010-02-04 20:54:43 -08001292
Daniel Sandler4a900acd2013-01-30 14:04:10 -05001293 mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
1294
1295 importOldBlockDb();
Daniel Sandler0da673f2012-04-11 12:33:16 -04001296
Joe Onorato089de882010-04-12 08:18:45 -07001297 mStatusBar = statusBar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 statusBar.setNotificationCallbacks(mNotificationCallbacks);
1299
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001300 mNotificationLight = lights.getLight(LightsService.LIGHT_ID_NOTIFICATIONS);
1301 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
1302
Mike Lockwood670f9322010-01-20 12:13:36 -05001303 Resources resources = mContext.getResources();
1304 mDefaultNotificationColor = resources.getColor(
Scott Greenwald9a05b312013-06-28 00:37:54 -04001305 R.color.config_defaultNotificationColor);
Mike Lockwood670f9322010-01-20 12:13:36 -05001306 mDefaultNotificationLedOn = resources.getInteger(
Scott Greenwald9a05b312013-06-28 00:37:54 -04001307 R.integer.config_defaultNotificationLedOn);
Mike Lockwood670f9322010-01-20 12:13:36 -05001308 mDefaultNotificationLedOff = resources.getInteger(
Scott Greenwald9a05b312013-06-28 00:37:54 -04001309 R.integer.config_defaultNotificationLedOff);
Mike Lockwood670f9322010-01-20 12:13:36 -05001310
Daniel Sandleredbb3802012-11-13 20:49:47 -08001311 mDefaultVibrationPattern = getLongArray(resources,
Scott Greenwald9a05b312013-06-28 00:37:54 -04001312 R.array.config_defaultNotificationVibePattern,
Daniel Sandleredbb3802012-11-13 20:49:47 -08001313 VIBRATE_PATTERN_MAXLEN,
1314 DEFAULT_VIBRATE_PATTERN);
1315
1316 mFallbackVibrationPattern = getLongArray(resources,
Scott Greenwald9a05b312013-06-28 00:37:54 -04001317 R.array.config_notificationFallbackVibePattern,
Daniel Sandleredbb3802012-11-13 20:49:47 -08001318 VIBRATE_PATTERN_MAXLEN,
1319 DEFAULT_VIBRATE_PATTERN);
1320
Joe Onorato39f5b6a2009-07-23 12:29:19 -04001321 // Don't start allowing notifications until the setup wizard has run once.
1322 // After that, including subsequent boots, init with notifications turned on.
1323 // This works on the first boot because the setup wizard will toggle this
1324 // flag at least once and we'll go back to 0 after that.
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001325 if (0 == Settings.Global.getInt(mContext.getContentResolver(),
1326 Settings.Global.DEVICE_PROVISIONED, 0)) {
Joe Onorato39f5b6a2009-07-23 12:29:19 -04001327 mDisabledNotifications = StatusBarManager.DISABLE_NOTIFICATION_ALERTS;
1328 }
1329
Mike Lockwood35e16bf2010-11-30 19:53:36 -05001330 // register for various Intents
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 IntentFilter filter = new IntentFilter();
Mike Lockwoodc22404a2009-12-02 11:15:02 -05001332 filter.addAction(Intent.ACTION_SCREEN_ON);
1333 filter.addAction(Intent.ACTION_SCREEN_OFF);
Daniel Sandlere96ffb12010-03-11 13:38:06 -05001334 filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
Mike Lockwood63b5ad92011-08-30 09:55:30 -04001335 filter.addAction(Intent.ACTION_USER_PRESENT);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001336 filter.addAction(Intent.ACTION_USER_STOPPED);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001337 filter.addAction(Intent.ACTION_USER_SWITCHED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 mContext.registerReceiver(mIntentReceiver, filter);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001339 IntentFilter pkgFilter = new IntentFilter();
Chris Wren3da73022013-05-10 14:41:21 -04001340 pkgFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001341 pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
Daniel Sandleraac0eb02011-08-06 22:51:56 -04001342 pkgFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001343 pkgFilter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
1344 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
1345 pkgFilter.addDataScheme("package");
1346 mContext.registerReceiver(mIntentReceiver, pkgFilter);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001347 IntentFilter sdFilter = new IntentFilter(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001348 mContext.registerReceiver(mIntentReceiver, sdFilter);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001349
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001350 mSettingsObserver = new SettingsObserver(mHandler);
1351 mSettingsObserver.observe();
Scott Greenwald9a05b312013-06-28 00:37:54 -04001352
1353 // spin up NotificationScorers
1354 String[] notificationScorerNames = resources.getStringArray(
1355 R.array.config_notificationScorers);
1356 for (String scorerName : notificationScorerNames) {
1357 try {
1358 Class<?> scorerClass = mContext.getClassLoader().loadClass(scorerName);
1359 NotificationScorer scorer = (NotificationScorer) scorerClass.newInstance();
1360 scorer.initialize(mContext);
1361 mScorers.add(scorer);
1362 } catch (ClassNotFoundException e) {
1363 Slog.w(TAG, "Couldn't find scorer " + scorerName + ".", e);
1364 } catch (InstantiationException e) {
1365 Slog.w(TAG, "Couldn't instantiate scorer " + scorerName + ".", e);
1366 } catch (IllegalAccessException e) {
1367 Slog.w(TAG, "Problem accessing scorer " + scorerName + ".", e);
1368 }
1369 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 }
1371
Daniel Sandler4a900acd2013-01-30 14:04:10 -05001372 /**
1373 * Read the old XML-based app block database and import those blockages into the AppOps system.
1374 */
1375 private void importOldBlockDb() {
1376 loadBlockDb();
1377
1378 PackageManager pm = mContext.getPackageManager();
1379 for (String pkg : mBlockedPackages) {
1380 PackageInfo info = null;
1381 try {
1382 info = pm.getPackageInfo(pkg, 0);
1383 setNotificationsEnabledForPackage(pkg, info.applicationInfo.uid, false);
1384 } catch (NameNotFoundException e) {
1385 // forget you
1386 }
1387 }
1388 mBlockedPackages.clear();
1389 if (mPolicyFile != null) {
1390 mPolicyFile.delete();
1391 }
1392 }
1393
Joe Onorato30275482009-07-08 17:09:14 -07001394 void systemReady() {
Jeff Sharkey098d5802012-04-26 17:30:34 -07001395 mAudioService = IAudioService.Stub.asInterface(
1396 ServiceManager.getService(Context.AUDIO_SERVICE));
1397
Joe Onorato30275482009-07-08 17:09:14 -07001398 // no beeping until we're basically done booting
1399 mSystemReady = true;
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001400
1401 // make sure our listener services are properly bound
1402 rebindListenerServices();
Joe Onorato30275482009-07-08 17:09:14 -07001403 }
1404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 // Toasts
1406 // ============================================================================
1407 public void enqueueToast(String pkg, ITransientNotification callback, int duration)
1408 {
Daniel Sandlera7035902010-03-30 15:45:31 -04001409 if (DBG) Slog.i(TAG, "enqueueToast pkg=" + pkg + " callback=" + callback + " duration=" + duration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410
1411 if (pkg == null || callback == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001412 Slog.e(TAG, "Not doing toast. pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 return ;
1414 }
1415
Daniel Sandler7c011302013-06-10 12:06:51 -04001416 final boolean isSystemToast = isCallerSystem() || ("android".equals(pkg));
Daniel Sandler0da673f2012-04-11 12:33:16 -04001417
Daniel Sandler4a900acd2013-01-30 14:04:10 -05001418 if (ENABLE_BLOCKED_TOASTS && !noteNotificationOp(pkg, Binder.getCallingUid())) {
1419 if (!isSystemToast) {
1420 Slog.e(TAG, "Suppressing toast from package " + pkg + " by user request.");
1421 return;
1422 }
Daniel Sandler0da673f2012-04-11 12:33:16 -04001423 }
1424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 synchronized (mToastQueue) {
1426 int callingPid = Binder.getCallingPid();
1427 long callingId = Binder.clearCallingIdentity();
1428 try {
1429 ToastRecord record;
1430 int index = indexOfToastLocked(pkg, callback);
1431 // If it's already in the queue, we update it in place, we don't
1432 // move it to the end of the queue.
1433 if (index >= 0) {
1434 record = mToastQueue.get(index);
1435 record.update(duration);
1436 } else {
Vairavan Srinivasanf9eb06c2011-01-21 18:08:36 -08001437 // Limit the number of toasts that any given package except the android
1438 // package can enqueue. Prevents DOS attacks and deals with leaks.
Daniel Sandler0da673f2012-04-11 12:33:16 -04001439 if (!isSystemToast) {
Vairavan Srinivasanf9eb06c2011-01-21 18:08:36 -08001440 int count = 0;
1441 final int N = mToastQueue.size();
1442 for (int i=0; i<N; i++) {
1443 final ToastRecord r = mToastQueue.get(i);
1444 if (r.pkg.equals(pkg)) {
1445 count++;
1446 if (count >= MAX_PACKAGE_NOTIFICATIONS) {
1447 Slog.e(TAG, "Package has already posted " + count
1448 + " toasts. Not showing more. Package=" + pkg);
1449 return;
1450 }
1451 }
1452 }
1453 }
1454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 record = new ToastRecord(callingPid, pkg, callback, duration);
1456 mToastQueue.add(record);
1457 index = mToastQueue.size() - 1;
1458 keepProcessAliveLocked(callingPid);
1459 }
1460 // If it's at index 0, it's the current toast. It doesn't matter if it's
1461 // new or just been updated. Call back and tell it to show itself.
1462 // If the callback fails, this will remove it from the list, so don't
1463 // assume that it's valid after this.
1464 if (index == 0) {
1465 showNextToastLocked();
1466 }
1467 } finally {
1468 Binder.restoreCallingIdentity(callingId);
1469 }
1470 }
1471 }
1472
1473 public void cancelToast(String pkg, ITransientNotification callback) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001474 Slog.i(TAG, "cancelToast pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475
1476 if (pkg == null || callback == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001477 Slog.e(TAG, "Not cancelling notification. pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 return ;
1479 }
1480
1481 synchronized (mToastQueue) {
1482 long callingId = Binder.clearCallingIdentity();
1483 try {
1484 int index = indexOfToastLocked(pkg, callback);
1485 if (index >= 0) {
1486 cancelToastLocked(index);
1487 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001488 Slog.w(TAG, "Toast already cancelled. pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 }
1490 } finally {
1491 Binder.restoreCallingIdentity(callingId);
1492 }
1493 }
1494 }
1495
1496 private void showNextToastLocked() {
1497 ToastRecord record = mToastQueue.get(0);
1498 while (record != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001499 if (DBG) Slog.d(TAG, "Show pkg=" + record.pkg + " callback=" + record.callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 try {
1501 record.callback.show();
John Spurlockdcf4f212013-05-21 17:19:53 -04001502 scheduleTimeoutLocked(record);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 return;
1504 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001505 Slog.w(TAG, "Object died trying to show notification " + record.callback
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 + " in package " + record.pkg);
1507 // remove it from the list and let the process die
1508 int index = mToastQueue.indexOf(record);
1509 if (index >= 0) {
1510 mToastQueue.remove(index);
1511 }
1512 keepProcessAliveLocked(record.pid);
1513 if (mToastQueue.size() > 0) {
1514 record = mToastQueue.get(0);
1515 } else {
1516 record = null;
1517 }
1518 }
1519 }
1520 }
1521
1522 private void cancelToastLocked(int index) {
1523 ToastRecord record = mToastQueue.get(index);
1524 try {
1525 record.callback.hide();
1526 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001527 Slog.w(TAG, "Object died trying to hide notification " + record.callback
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 + " in package " + record.pkg);
1529 // don't worry about this, we're about to remove it from
1530 // the list anyway
1531 }
1532 mToastQueue.remove(index);
1533 keepProcessAliveLocked(record.pid);
1534 if (mToastQueue.size() > 0) {
1535 // Show the next one. If the callback fails, this will remove
1536 // it from the list, so don't assume that the list hasn't changed
1537 // after this point.
1538 showNextToastLocked();
1539 }
1540 }
1541
John Spurlockdcf4f212013-05-21 17:19:53 -04001542 private void scheduleTimeoutLocked(ToastRecord r)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 mHandler.removeCallbacksAndMessages(r);
John Spurlockdcf4f212013-05-21 17:19:53 -04001545 if (r.duration != Toast.LENGTH_INFINITE) {
1546 Message m = Message.obtain(mHandler, MESSAGE_TIMEOUT, r);
1547 long delay = r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY;
1548 mHandler.sendMessageDelayed(m, delay);
1549 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 }
1551
1552 private void handleTimeout(ToastRecord record)
1553 {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001554 if (DBG) Slog.d(TAG, "Timeout pkg=" + record.pkg + " callback=" + record.callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 synchronized (mToastQueue) {
1556 int index = indexOfToastLocked(record.pkg, record.callback);
1557 if (index >= 0) {
1558 cancelToastLocked(index);
1559 }
1560 }
1561 }
1562
1563 // lock on mToastQueue
1564 private int indexOfToastLocked(String pkg, ITransientNotification callback)
1565 {
1566 IBinder cbak = callback.asBinder();
1567 ArrayList<ToastRecord> list = mToastQueue;
1568 int len = list.size();
1569 for (int i=0; i<len; i++) {
1570 ToastRecord r = list.get(i);
1571 if (r.pkg.equals(pkg) && r.callback.asBinder() == cbak) {
1572 return i;
1573 }
1574 }
1575 return -1;
1576 }
1577
1578 // lock on mToastQueue
1579 private void keepProcessAliveLocked(int pid)
1580 {
1581 int toastCount = 0; // toasts from this pid
1582 ArrayList<ToastRecord> list = mToastQueue;
1583 int N = list.size();
1584 for (int i=0; i<N; i++) {
1585 ToastRecord r = list.get(i);
1586 if (r.pid == pid) {
1587 toastCount++;
1588 }
1589 }
1590 try {
1591 mAm.setProcessForeground(mForegroundToken, pid, toastCount > 0);
1592 } catch (RemoteException e) {
1593 // Shouldn't happen.
1594 }
1595 }
1596
1597 private final class WorkerHandler extends Handler
1598 {
1599 @Override
1600 public void handleMessage(Message msg)
1601 {
1602 switch (msg.what)
1603 {
1604 case MESSAGE_TIMEOUT:
1605 handleTimeout((ToastRecord)msg.obj);
1606 break;
1607 }
1608 }
1609 }
1610
1611
1612 // Notifications
1613 // ============================================================================
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001614 public void enqueueNotificationWithTag(String pkg, String basePkg, String tag, int id,
1615 Notification notification, int[] idOut, int userId)
Fred Quintana6ecaff12009-09-25 14:23:13 -07001616 {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001617 enqueueNotificationInternal(pkg, basePkg, Binder.getCallingUid(), Binder.getCallingPid(),
Dianne Hackborn41203752012-08-31 14:05:51 -07001618 tag, id, notification, idOut, userId);
Daniel Sandlerd0a2f862010-08-03 15:29:31 -04001619 }
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001620
1621 private final static int clamp(int x, int low, int high) {
1622 return (x < low) ? low : ((x > high) ? high : x);
Daniel Sandlere40451a2011-02-03 14:51:35 -05001623 }
1624
Daniel Sandlerd0a2f862010-08-03 15:29:31 -04001625 // Not exposed via Binder; for system use only (otherwise malicious apps could spoof the
1626 // uid/pid of another application)
Scott Greenwald9b05c612013-06-25 23:44:05 -04001627
1628 public void enqueueNotificationInternal(final String pkg, String basePkg, final int callingUid,
1629 final int callingPid, final String tag, final int id, final Notification notification,
1630 int[] idOut, int incomingUserId)
Daniel Sandlerd0a2f862010-08-03 15:29:31 -04001631 {
Daniel Sandler0da673f2012-04-11 12:33:16 -04001632 if (DBG) {
1633 Slog.v(TAG, "enqueueNotificationInternal: pkg=" + pkg + " id=" + id + " notification=" + notification);
1634 }
1635 checkCallerIsSystemOrSameApp(pkg);
Daniel Sandler9eb434c2013-07-31 20:21:07 -04001636 final boolean isSystemNotification = isUidSystem(callingUid) || ("android".equals(pkg));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001637
Scott Greenwald9b05c612013-06-25 23:44:05 -04001638 final int userId = ActivityManager.handleIncomingUser(callingPid,
1639 callingUid, incomingUserId, true, false, "enqueueNotification", pkg);
Jeff Sharkey65c4a2b2012-09-25 17:22:27 -07001640 final UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001641
Joe Onoratobd73d012010-06-04 11:44:54 -07001642 // Limit the number of notifications that any given package except the android
1643 // package can enqueue. Prevents DOS attacks and deals with leaks.
Daniel Sandler0da673f2012-04-11 12:33:16 -04001644 if (!isSystemNotification) {
Joe Onoratobd73d012010-06-04 11:44:54 -07001645 synchronized (mNotificationList) {
1646 int count = 0;
1647 final int N = mNotificationList.size();
1648 for (int i=0; i<N; i++) {
1649 final NotificationRecord r = mNotificationList.get(i);
Daniel Sandler4f91efd2013-04-25 16:38:41 -04001650 if (r.sbn.getPackageName().equals(pkg) && r.sbn.getUserId() == userId) {
Joe Onoratobd73d012010-06-04 11:44:54 -07001651 count++;
1652 if (count >= MAX_PACKAGE_NOTIFICATIONS) {
1653 Slog.e(TAG, "Package has already posted " + count
1654 + " notifications. Not showing more. package=" + pkg);
1655 return;
1656 }
1657 }
1658 }
1659 }
1660 }
1661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 // This conditional is a dirty hack to limit the logging done on
1663 // behalf of the download manager without affecting other apps.
1664 if (!pkg.equals("com.android.providers.downloads")
1665 || Log.isLoggable("DownloadManager", Log.VERBOSE)) {
Daniel Sandler321e9c52012-10-12 10:59:26 -07001666 EventLog.writeEvent(EventLogTags.NOTIFICATION_ENQUEUE, pkg, id, tag, userId,
Daniel Sandlerb64cb882011-11-29 23:48:29 -05001667 notification.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 }
1669
1670 if (pkg == null || notification == null) {
1671 throw new IllegalArgumentException("null not allowed: pkg=" + pkg
1672 + " id=" + id + " notification=" + notification);
1673 }
1674 if (notification.icon != 0) {
1675 if (notification.contentView == null) {
1676 throw new IllegalArgumentException("contentView required: pkg=" + pkg
1677 + " id=" + id + " notification=" + notification);
1678 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 }
1680
Scott Greenwald9b05c612013-06-25 23:44:05 -04001681 mHandler.post(new Runnable() {
1682 @Override
1683 public void run() {
Daniel Sandler0da673f2012-04-11 12:33:16 -04001684
Scott Greenwald9b05c612013-06-25 23:44:05 -04001685 // === Scoring ===
Daniel Sandler0da673f2012-04-11 12:33:16 -04001686
Scott Greenwald9b05c612013-06-25 23:44:05 -04001687 // 0. Sanitize inputs
1688 notification.priority = clamp(notification.priority, Notification.PRIORITY_MIN,
1689 Notification.PRIORITY_MAX);
1690 // Migrate notification flags to scores
1691 if (0 != (notification.flags & Notification.FLAG_HIGH_PRIORITY)) {
1692 if (notification.priority < Notification.PRIORITY_MAX) {
1693 notification.priority = Notification.PRIORITY_MAX;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 }
Scott Greenwald9b05c612013-06-25 23:44:05 -04001695 } else if (SCORE_ONGOING_HIGHER &&
1696 0 != (notification.flags & Notification.FLAG_ONGOING_EVENT)) {
1697 if (notification.priority < Notification.PRIORITY_HIGH) {
1698 notification.priority = Notification.PRIORITY_HIGH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699 }
1700 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001701
Scott Greenwald9b05c612013-06-25 23:44:05 -04001702 // 1. initial score: buckets of 10, around the app
1703 int score = notification.priority * NOTIFICATION_PRIORITY_MULTIPLIER; //[-20..20]
1704
1705 // 2. Consult external heuristics (TBD)
1706
1707 // 3. Apply local rules
1708
Scott Greenwald9a05b312013-06-28 00:37:54 -04001709 int initialScore = score;
1710 if (!mScorers.isEmpty()) {
1711 if (DBG) Slog.v(TAG, "Initial score is " + score + ".");
1712 for (NotificationScorer scorer : mScorers) {
1713 try {
1714 score = scorer.getScore(notification, score);
1715 } catch (Throwable t) {
1716 Slog.w(TAG, "Scorer threw on .getScore.", t);
1717 }
1718 }
1719 if (DBG) Slog.v(TAG, "Final score is " + score + ".");
1720 }
1721
1722 // add extra to indicate score modified by NotificationScorer
1723 notification.extras.putBoolean(Notification.EXTRA_SCORE_MODIFIED,
1724 score != initialScore);
1725
Scott Greenwald9b05c612013-06-25 23:44:05 -04001726 // blocked apps
1727 if (ENABLE_BLOCKED_NOTIFICATIONS && !noteNotificationOp(pkg, callingUid)) {
1728 if (!isSystemNotification) {
1729 score = JUNK_SCORE;
1730 Slog.e(TAG, "Suppressing notification from package " + pkg
1731 + " by user request.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 }
Daniel Sandlerd4d2de22012-11-14 11:25:46 -08001733 }
1734
Scott Greenwald9b05c612013-06-25 23:44:05 -04001735 if (DBG) {
1736 Slog.v(TAG, "Assigned score=" + score + " to " + notification);
1737 }
1738
1739 if (score < SCORE_DISPLAY_THRESHOLD) {
1740 // Notification will be blocked because the score is too low.
1741 return;
1742 }
1743
1744 // Should this notification make noise, vibe, or use the LED?
1745 final boolean canInterrupt = (score >= SCORE_INTERRUPTION_THRESHOLD);
1746
1747 synchronized (mNotificationList) {
1748 final StatusBarNotification n = new StatusBarNotification(
1749 pkg, id, tag, callingUid, callingPid, score, notification, user);
1750 NotificationRecord r = new NotificationRecord(n);
1751 NotificationRecord old = null;
1752
1753 int index = indexOfNotificationLocked(pkg, tag, id, userId);
1754 if (index < 0) {
1755 mNotificationList.add(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 } else {
Scott Greenwald9b05c612013-06-25 23:44:05 -04001757 old = mNotificationList.remove(index);
1758 mNotificationList.add(index, r);
1759 // Make sure we don't lose the foreground service state.
1760 if (old != null) {
1761 notification.flags |=
1762 old.getNotification().flags & Notification.FLAG_FOREGROUND_SERVICE;
1763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 }
Scott Greenwald9b05c612013-06-25 23:44:05 -04001765
1766 // Ensure if this is a foreground service that the proper additional
1767 // flags are set.
1768 if ((notification.flags&Notification.FLAG_FOREGROUND_SERVICE) != 0) {
1769 notification.flags |= Notification.FLAG_ONGOING_EVENT
1770 | Notification.FLAG_NO_CLEAR;
1771 }
1772
1773 final int currentUser;
1774 final long token = Binder.clearCallingIdentity();
1775 try {
1776 currentUser = ActivityManager.getCurrentUser();
1777 } finally {
1778 Binder.restoreCallingIdentity(token);
1779 }
1780
1781 if (notification.icon != 0) {
1782 if (old != null && old.statusBarKey != null) {
1783 r.statusBarKey = old.statusBarKey;
1784 long identity = Binder.clearCallingIdentity();
1785 try {
1786 mStatusBar.updateNotification(r.statusBarKey, n);
Jeff Sharkey098d5802012-04-26 17:30:34 -07001787 }
Scott Greenwald9b05c612013-06-25 23:44:05 -04001788 finally {
1789 Binder.restoreCallingIdentity(identity);
1790 }
1791 } else {
1792 long identity = Binder.clearCallingIdentity();
1793 try {
1794 r.statusBarKey = mStatusBar.addNotification(n);
1795 if ((n.getNotification().flags & Notification.FLAG_SHOW_LIGHTS) != 0
1796 && canInterrupt) {
1797 mAttentionLight.pulse();
1798 }
1799 }
1800 finally {
1801 Binder.restoreCallingIdentity(identity);
1802 }
1803 }
1804 // Send accessibility events only for the current user.
1805 if (currentUser == userId) {
1806 sendAccessibilityEvent(notification, pkg);
1807 }
1808
1809 notifyPostedLocked(r);
1810 } else {
1811 Slog.e(TAG, "Not posting notification with icon==0: " + notification);
1812 if (old != null && old.statusBarKey != null) {
1813 long identity = Binder.clearCallingIdentity();
1814 try {
1815 mStatusBar.removeNotification(old.statusBarKey);
1816 }
1817 finally {
1818 Binder.restoreCallingIdentity(identity);
1819 }
1820
1821 notifyRemovedLocked(r);
1822 }
1823 // ATTENTION: in a future release we will bail out here
1824 // so that we do not play sounds, show lights, etc. for invalid notifications
1825 Slog.e(TAG, "WARNING: In a future release this will crash the app: "
1826 + n.getPackageName());
1827 }
1828
1829 // If we're not supposed to beep, vibrate, etc. then don't.
1830 if (((mDisabledNotifications & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) == 0)
1831 && (!(old != null
1832 && (notification.flags & Notification.FLAG_ONLY_ALERT_ONCE) != 0 ))
1833 && (r.getUserId() == UserHandle.USER_ALL ||
1834 (r.getUserId() == userId && r.getUserId() == currentUser))
1835 && canInterrupt
1836 && mSystemReady) {
1837
1838 final AudioManager audioManager = (AudioManager) mContext
1839 .getSystemService(Context.AUDIO_SERVICE);
1840
1841 // sound
1842
1843 // should we use the default notification sound? (indicated either by
1844 // DEFAULT_SOUND or because notification.sound is pointing at
1845 // Settings.System.NOTIFICATION_SOUND)
1846 final boolean useDefaultSound =
1847 (notification.defaults & Notification.DEFAULT_SOUND) != 0 ||
1848 Settings.System.DEFAULT_NOTIFICATION_URI
1849 .equals(notification.sound);
1850
1851 Uri soundUri = null;
1852 boolean hasValidSound = false;
1853
1854 if (useDefaultSound) {
1855 soundUri = Settings.System.DEFAULT_NOTIFICATION_URI;
1856
1857 // check to see if the default notification sound is silent
1858 ContentResolver resolver = mContext.getContentResolver();
1859 hasValidSound = Settings.System.getString(resolver,
1860 Settings.System.NOTIFICATION_SOUND) != null;
1861 } else if (notification.sound != null) {
1862 soundUri = notification.sound;
1863 hasValidSound = (soundUri != null);
1864 }
1865
1866 if (hasValidSound) {
1867 boolean looping = (notification.flags & Notification.FLAG_INSISTENT) != 0;
1868 int audioStreamType;
1869 if (notification.audioStreamType >= 0) {
1870 audioStreamType = notification.audioStreamType;
1871 } else {
1872 audioStreamType = DEFAULT_STREAM_TYPE;
1873 }
1874 mSoundNotification = r;
1875 // do not play notifications if stream volume is 0 (typically because
Jean-Michel Trivi23805662013-07-31 14:19:18 -07001876 // ringer mode is silent) or if there is a user of exclusive audio focus
Scott Greenwald9b05c612013-06-25 23:44:05 -04001877 if ((audioManager.getStreamVolume(audioStreamType) != 0)
Jean-Michel Trivi23805662013-07-31 14:19:18 -07001878 && !audioManager.isAudioFocusExclusive()) {
Scott Greenwald9b05c612013-06-25 23:44:05 -04001879 final long identity = Binder.clearCallingIdentity();
1880 try {
1881 final IRingtonePlayer player = mAudioService.getRingtonePlayer();
1882 if (player != null) {
1883 player.playAsync(soundUri, user, looping, audioStreamType);
1884 }
1885 } catch (RemoteException e) {
1886 } finally {
1887 Binder.restoreCallingIdentity(identity);
1888 }
1889 }
1890 }
1891
1892 // vibrate
1893 // Does the notification want to specify its own vibration?
1894 final boolean hasCustomVibrate = notification.vibrate != null;
1895
1896 // new in 4.2: if there was supposed to be a sound and we're in vibrate
1897 // mode, and no other vibration is specified, we fall back to vibration
1898 final boolean convertSoundToVibration =
1899 !hasCustomVibrate
1900 && hasValidSound
1901 && (audioManager.getRingerMode()
1902 == AudioManager.RINGER_MODE_VIBRATE);
1903
1904 // The DEFAULT_VIBRATE flag trumps any custom vibration AND the fallback.
1905 final boolean useDefaultVibrate =
1906 (notification.defaults & Notification.DEFAULT_VIBRATE) != 0;
1907
1908 if ((useDefaultVibrate || convertSoundToVibration || hasCustomVibrate)
1909 && !(audioManager.getRingerMode()
1910 == AudioManager.RINGER_MODE_SILENT)) {
1911 mVibrateNotification = r;
1912
1913 if (useDefaultVibrate || convertSoundToVibration) {
1914 // Escalate privileges so we can use the vibrator even if the
1915 // notifying app does not have the VIBRATE permission.
1916 long identity = Binder.clearCallingIdentity();
1917 try {
1918 mVibrator.vibrate(r.sbn.getUid(), r.sbn.getBasePkg(),
1919 useDefaultVibrate ? mDefaultVibrationPattern
1920 : mFallbackVibrationPattern,
1921 ((notification.flags & Notification.FLAG_INSISTENT) != 0)
1922 ? 0: -1);
1923 } finally {
1924 Binder.restoreCallingIdentity(identity);
1925 }
1926 } else if (notification.vibrate.length > 1) {
1927 // If you want your own vibration pattern, you need the VIBRATE
1928 // permission
1929 mVibrator.vibrate(r.sbn.getUid(), r.sbn.getBasePkg(),
1930 notification.vibrate,
1931 ((notification.flags & Notification.FLAG_INSISTENT) != 0)
1932 ? 0: -1);
1933 }
1934 }
1935 }
1936
1937 // light
1938 // the most recent thing gets the light
1939 mLights.remove(old);
1940 if (mLedNotification == old) {
1941 mLedNotification = null;
1942 }
1943 //Slog.i(TAG, "notification.lights="
1944 // + ((old.notification.lights.flags & Notification.FLAG_SHOW_LIGHTS)
1945 // != 0));
1946 if ((notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0
1947 && canInterrupt) {
1948 mLights.add(r);
1949 updateLightsLocked();
1950 } else {
1951 if (old != null
1952 && ((old.getFlags() & Notification.FLAG_SHOW_LIGHTS) != 0)) {
1953 updateLightsLocked();
Eric Laurent524dc042009-11-27 05:07:55 -08001954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 }
1956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001957 }
Scott Greenwald9b05c612013-06-25 23:44:05 -04001958 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959
1960 idOut[0] = id;
1961 }
1962
Joe Onorato30275482009-07-08 17:09:14 -07001963 private void sendAccessibilityEvent(Notification notification, CharSequence packageName) {
svetoslavganov75986cf2009-05-14 22:28:01 -07001964 AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
1965 if (!manager.isEnabled()) {
1966 return;
1967 }
1968
1969 AccessibilityEvent event =
1970 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED);
1971 event.setPackageName(packageName);
1972 event.setClassName(Notification.class.getName());
1973 event.setParcelableData(notification);
1974 CharSequence tickerText = notification.tickerText;
1975 if (!TextUtils.isEmpty(tickerText)) {
1976 event.getText().add(tickerText);
1977 }
1978
1979 manager.sendAccessibilityEvent(event);
1980 }
1981
Joe Onorato46439ce2010-11-19 13:56:21 -08001982 private void cancelNotificationLocked(NotificationRecord r, boolean sendDelete) {
1983 // tell the app
1984 if (sendDelete) {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001985 if (r.getNotification().deleteIntent != null) {
Joe Onorato46439ce2010-11-19 13:56:21 -08001986 try {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001987 r.getNotification().deleteIntent.send();
Joe Onorato46439ce2010-11-19 13:56:21 -08001988 } catch (PendingIntent.CanceledException ex) {
1989 // do nothing - there's no relevant way to recover, and
1990 // no reason to let this propagate
Daniel Sandler4f91efd2013-04-25 16:38:41 -04001991 Slog.w(TAG, "canceled PendingIntent for " + r.sbn.getPackageName(), ex);
Joe Onorato46439ce2010-11-19 13:56:21 -08001992 }
1993 }
1994 }
1995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 // status bar
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001997 if (r.getNotification().icon != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998 long identity = Binder.clearCallingIdentity();
1999 try {
Joe Onorato0cbda992010-05-02 16:28:15 -07002000 mStatusBar.removeNotification(r.statusBarKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 }
2002 finally {
2003 Binder.restoreCallingIdentity(identity);
2004 }
2005 r.statusBarKey = null;
Daniel Sandler09a247e2013-02-14 10:24:17 -05002006 notifyRemovedLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 }
2008
2009 // sound
2010 if (mSoundNotification == r) {
2011 mSoundNotification = null;
Jeff Sharkey098d5802012-04-26 17:30:34 -07002012 final long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 try {
Jeff Sharkey098d5802012-04-26 17:30:34 -07002014 final IRingtonePlayer player = mAudioService.getRingtonePlayer();
2015 if (player != null) {
2016 player.stopAsync();
2017 }
2018 } catch (RemoteException e) {
2019 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002020 Binder.restoreCallingIdentity(identity);
2021 }
2022 }
2023
2024 // vibrate
2025 if (mVibrateNotification == r) {
2026 mVibrateNotification = null;
2027 long identity = Binder.clearCallingIdentity();
2028 try {
2029 mVibrator.cancel();
2030 }
2031 finally {
2032 Binder.restoreCallingIdentity(identity);
2033 }
2034 }
2035
2036 // light
2037 mLights.remove(r);
2038 if (mLedNotification == r) {
2039 mLedNotification = null;
2040 }
Daniel Sandler23d7c702013-03-07 16:32:06 -05002041
2042 // Save it for users of getHistoricalNotifications()
2043 mArchive.record(r.sbn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 }
2045
2046 /**
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002047 * Cancels a notification ONLY if it has all of the {@code mustHaveFlags}
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002048 * and none of the {@code mustNotHaveFlags}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 */
Svetoslav Ganov835835e2013-08-04 20:17:52 -07002050 private void cancelNotification(final String pkg, final String tag, final int id,
2051 final int mustHaveFlags, final int mustNotHaveFlags, final boolean sendDelete,
2052 final int userId) {
2053 // In enqueueNotificationInternal notifications are added by scheduling the
2054 // work on the worker handler. Hence, we also schedule the cancel on this
2055 // handler to avoid a scenario where an add notification call followed by a
2056 // remove notification call ends up in not removing the notification.
2057 mHandler.post(new Runnable() {
2058 @Override
2059 public void run() {
2060 EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL, pkg, id, tag, userId,
2061 mustHaveFlags, mustNotHaveFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062
Svetoslav Ganov835835e2013-08-04 20:17:52 -07002063 synchronized (mNotificationList) {
2064 int index = indexOfNotificationLocked(pkg, tag, id, userId);
2065 if (index >= 0) {
2066 NotificationRecord r = mNotificationList.get(index);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002067
Svetoslav Ganov835835e2013-08-04 20:17:52 -07002068 if ((r.getNotification().flags & mustHaveFlags) != mustHaveFlags) {
2069 return;
2070 }
2071 if ((r.getNotification().flags & mustNotHaveFlags) != 0) {
2072 return;
2073 }
2074
2075 mNotificationList.remove(index);
2076
2077 cancelNotificationLocked(r, sendDelete);
2078 updateLightsLocked();
2079 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 }
Svetoslav Ganov835835e2013-08-04 20:17:52 -07002082 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 }
2084
2085 /**
Daniel Sandler321e9c52012-10-12 10:59:26 -07002086 * Determine whether the userId applies to the notification in question, either because
2087 * they match exactly, or one of them is USER_ALL (which is treated as a wildcard).
2088 */
2089 private boolean notificationMatchesUserId(NotificationRecord r, int userId) {
2090 return
2091 // looking for USER_ALL notifications? match everything
2092 userId == UserHandle.USER_ALL
2093 // a notification sent to USER_ALL matches any query
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002094 || r.getUserId() == UserHandle.USER_ALL
Daniel Sandler321e9c52012-10-12 10:59:26 -07002095 // an exact user match
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002096 || r.getUserId() == userId;
Daniel Sandler321e9c52012-10-12 10:59:26 -07002097 }
2098
2099 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002100 * Cancels all notifications from a given package that have all of the
2101 * {@code mustHaveFlags}.
2102 */
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002103 boolean cancelAllNotificationsInt(String pkg, int mustHaveFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002104 int mustNotHaveFlags, boolean doit, int userId) {
Daniel Sandler321e9c52012-10-12 10:59:26 -07002105 EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL_ALL, pkg, userId,
2106 mustHaveFlags, mustNotHaveFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107
2108 synchronized (mNotificationList) {
2109 final int N = mNotificationList.size();
2110 boolean canceledSomething = false;
2111 for (int i = N-1; i >= 0; --i) {
2112 NotificationRecord r = mNotificationList.get(i);
Daniel Sandler321e9c52012-10-12 10:59:26 -07002113 if (!notificationMatchesUserId(r, userId)) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002114 continue;
2115 }
Amith Yamasani5ec00e92012-11-07 16:58:30 -08002116 // Don't remove notifications to all, if there's no package name specified
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002117 if (r.getUserId() == UserHandle.USER_ALL && pkg == null) {
Amith Yamasani5ec00e92012-11-07 16:58:30 -08002118 continue;
2119 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002120 if ((r.getFlags() & mustHaveFlags) != mustHaveFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002121 continue;
2122 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002123 if ((r.getFlags() & mustNotHaveFlags) != 0) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002124 continue;
2125 }
Daniel Sandler4f91efd2013-04-25 16:38:41 -04002126 if (pkg != null && !r.sbn.getPackageName().equals(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127 continue;
2128 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002129 canceledSomething = true;
2130 if (!doit) {
2131 return true;
2132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133 mNotificationList.remove(i);
Joe Onorato46439ce2010-11-19 13:56:21 -08002134 cancelNotificationLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 }
2136 if (canceledSomething) {
2137 updateLightsLocked();
2138 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002139 return canceledSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002140 }
2141 }
2142
Dianne Hackborn41203752012-08-31 14:05:51 -07002143 public void cancelNotificationWithTag(String pkg, String tag, int id, int userId) {
Daniel Sandler0da673f2012-04-11 12:33:16 -04002144 checkCallerIsSystemOrSameApp(pkg);
Dianne Hackborn41203752012-08-31 14:05:51 -07002145 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07002146 Binder.getCallingUid(), userId, true, false, "cancelNotificationWithTag", pkg);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002147 // Don't allow client applications to cancel foreground service notis.
Fred Quintana6ecaff12009-09-25 14:23:13 -07002148 cancelNotification(pkg, tag, id, 0,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002149 Binder.getCallingUid() == Process.SYSTEM_UID
Dianne Hackborn41203752012-08-31 14:05:51 -07002150 ? 0 : Notification.FLAG_FOREGROUND_SERVICE, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002151 }
2152
Dianne Hackborn41203752012-08-31 14:05:51 -07002153 public void cancelAllNotifications(String pkg, int userId) {
Daniel Sandler0da673f2012-04-11 12:33:16 -04002154 checkCallerIsSystemOrSameApp(pkg);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002155
Dianne Hackborn41203752012-08-31 14:05:51 -07002156 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07002157 Binder.getCallingUid(), userId, true, false, "cancelAllNotifications", pkg);
Dianne Hackborn41203752012-08-31 14:05:51 -07002158
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002159 // Calling from user space, don't allow the canceling of actively
2160 // running foreground services.
Dianne Hackborn41203752012-08-31 14:05:51 -07002161 cancelAllNotificationsInt(pkg, 0, Notification.FLAG_FOREGROUND_SERVICE, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002162 }
2163
Daniel Sandler9eb434c2013-07-31 20:21:07 -04002164 // Return true if the UID is a system or phone UID and therefore should not have
Daniel Sandler7c011302013-06-10 12:06:51 -04002165 // any notifications or toasts blocked.
Daniel Sandler9eb434c2013-07-31 20:21:07 -04002166 boolean isUidSystem(int uid) {
Daniel Sandler7c011302013-06-10 12:06:51 -04002167 final int appid = UserHandle.getAppId(uid);
2168 return (appid == Process.SYSTEM_UID || appid == Process.PHONE_UID || uid == 0);
2169 }
2170
Daniel Sandler9eb434c2013-07-31 20:21:07 -04002171 // same as isUidSystem(int, int) for the Binder caller's UID.
2172 boolean isCallerSystem() {
2173 return isUidSystem(Binder.getCallingUid());
2174 }
2175
Daniel Sandler0da673f2012-04-11 12:33:16 -04002176 void checkCallerIsSystem() {
Daniel Sandler7c011302013-06-10 12:06:51 -04002177 if (isCallerSystem()) {
Daniel Sandler0da673f2012-04-11 12:33:16 -04002178 return;
2179 }
Daniel Sandler7c011302013-06-10 12:06:51 -04002180 throw new SecurityException("Disallowed call for uid " + Binder.getCallingUid());
Daniel Sandler0da673f2012-04-11 12:33:16 -04002181 }
2182
2183 void checkCallerIsSystemOrSameApp(String pkg) {
Daniel Sandler7c011302013-06-10 12:06:51 -04002184 if (isCallerSystem()) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002185 return;
2186 }
Daniel Sandler7c011302013-06-10 12:06:51 -04002187 final int uid = Binder.getCallingUid();
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002188 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07002189 ApplicationInfo ai = AppGlobals.getPackageManager().getApplicationInfo(
2190 pkg, 0, UserHandle.getCallingUserId());
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002191 if (!UserHandle.isSameApp(ai.uid, uid)) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002192 throw new SecurityException("Calling uid " + uid + " gave package"
2193 + pkg + " which is owned by uid " + ai.uid);
2194 }
Amith Yamasanif203aee2012-08-29 18:41:53 -07002195 } catch (RemoteException re) {
2196 throw new SecurityException("Unknown package " + pkg + "\n" + re);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002197 }
2198 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002199
Dianne Hackborn41203752012-08-31 14:05:51 -07002200 void cancelAll(int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002201 synchronized (mNotificationList) {
2202 final int N = mNotificationList.size();
2203 for (int i=N-1; i>=0; i--) {
2204 NotificationRecord r = mNotificationList.get(i);
2205
Daniel Sandler321e9c52012-10-12 10:59:26 -07002206 if (!notificationMatchesUserId(r, userId)) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002207 continue;
2208 }
2209
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002210 if ((r.getFlags() & (Notification.FLAG_ONGOING_EVENT
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002211 | Notification.FLAG_NO_CLEAR)) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212 mNotificationList.remove(i);
Joe Onorato46439ce2010-11-19 13:56:21 -08002213 cancelNotificationLocked(r, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214 }
2215 }
2216
2217 updateLightsLocked();
2218 }
2219 }
2220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002221 // lock on mNotificationList
2222 private void updateLightsLocked()
2223 {
The Android Open Source Project10592532009-03-18 17:39:46 -07002224 // handle notification lights
2225 if (mLedNotification == null) {
2226 // get next notification, if any
2227 int n = mLights.size();
2228 if (n > 0) {
2229 mLedNotification = mLights.get(n-1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002230 }
2231 }
Mike Lockwoodc22404a2009-12-02 11:15:02 -05002232
Mike Lockwood63b5ad92011-08-30 09:55:30 -04002233 // Don't flash while we are in a call or screen is on
2234 if (mLedNotification == null || mInCall || mScreenOn) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002235 mNotificationLight.turnOff();
The Android Open Source Project10592532009-03-18 17:39:46 -07002236 } else {
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04002237 final Notification ledno = mLedNotification.sbn.getNotification();
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002238 int ledARGB = ledno.ledARGB;
2239 int ledOnMS = ledno.ledOnMS;
2240 int ledOffMS = ledno.ledOffMS;
2241 if ((ledno.defaults & Notification.DEFAULT_LIGHTS) != 0) {
Mike Lockwood670f9322010-01-20 12:13:36 -05002242 ledARGB = mDefaultNotificationColor;
2243 ledOnMS = mDefaultNotificationLedOn;
2244 ledOffMS = mDefaultNotificationLedOff;
2245 }
2246 if (mNotificationPulseEnabled) {
2247 // pulse repeatedly
2248 mNotificationLight.setFlashing(ledARGB, LightsService.LIGHT_FLASH_TIMED,
2249 ledOnMS, ledOffMS);
Mike Lockwood670f9322010-01-20 12:13:36 -05002250 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002251 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002252 }
2253
2254 // lock on mNotificationList
Dianne Hackborn41203752012-08-31 14:05:51 -07002255 private int indexOfNotificationLocked(String pkg, String tag, int id, int userId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002256 {
2257 ArrayList<NotificationRecord> list = mNotificationList;
2258 final int len = list.size();
2259 for (int i=0; i<len; i++) {
2260 NotificationRecord r = list.get(i);
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04002261 if (!notificationMatchesUserId(r, userId) || r.sbn.getId() != id) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002262 continue;
2263 }
Fred Quintana6ecaff12009-09-25 14:23:13 -07002264 if (tag == null) {
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04002265 if (r.sbn.getTag() != null) {
Fred Quintana6ecaff12009-09-25 14:23:13 -07002266 continue;
2267 }
2268 } else {
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04002269 if (!tag.equals(r.sbn.getTag())) {
Fred Quintana6ecaff12009-09-25 14:23:13 -07002270 continue;
2271 }
2272 }
Daniel Sandler4f91efd2013-04-25 16:38:41 -04002273 if (r.sbn.getPackageName().equals(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002274 return i;
2275 }
2276 }
2277 return -1;
2278 }
2279
Mike Lockwoodc22404a2009-12-02 11:15:02 -05002280 private void updateNotificationPulse() {
2281 synchronized (mNotificationList) {
2282 updateLightsLocked();
2283 }
2284 }
2285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002286 // ======================================================================
2287 @Override
2288 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2289 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2290 != PackageManager.PERMISSION_GRANTED) {
2291 pw.println("Permission Denial: can't dump NotificationManager from from pid="
2292 + Binder.getCallingPid()
2293 + ", uid=" + Binder.getCallingUid());
2294 return;
2295 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002297 pw.println("Current Notification Manager state:");
2298
Daniel Sandler5feceeb2013-03-22 18:29:23 -07002299 pw.println(" Listeners (" + mEnabledListenersForCurrentUser.size()
2300 + ") enabled for current user:");
2301 for (ComponentName cmpt : mEnabledListenersForCurrentUser) {
2302 pw.println(" " + cmpt);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04002303 }
Daniel Sandler4b749ef2013-03-18 21:53:04 -04002304
Daniel Sandler5feceeb2013-03-22 18:29:23 -07002305 pw.println(" Live listeners (" + mListeners.size() + "):");
Daniel Sandler4b749ef2013-03-18 21:53:04 -04002306 for (NotificationListenerInfo info : mListeners) {
Daniel Sandler5feceeb2013-03-22 18:29:23 -07002307 pw.println(" " + info.component
2308 + " (user " + info.userid + "): " + info.listener
2309 + (info.isSystem?" SYSTEM":""));
Daniel Sandler4b749ef2013-03-18 21:53:04 -04002310 }
2311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002312 int N;
2313
2314 synchronized (mToastQueue) {
2315 N = mToastQueue.size();
2316 if (N > 0) {
2317 pw.println(" Toast Queue:");
2318 for (int i=0; i<N; i++) {
2319 mToastQueue.get(i).dump(pw, " ");
2320 }
2321 pw.println(" ");
2322 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324 }
2325
2326 synchronized (mNotificationList) {
2327 N = mNotificationList.size();
2328 if (N > 0) {
2329 pw.println(" Notification List:");
2330 for (int i=0; i<N; i++) {
2331 mNotificationList.get(i).dump(pw, " ", mContext);
2332 }
2333 pw.println(" ");
2334 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002336 N = mLights.size();
2337 if (N > 0) {
2338 pw.println(" Lights List:");
2339 for (int i=0; i<N; i++) {
Daniel Sandlerf45564e2013-04-15 15:05:08 -04002340 pw.println(" " + mLights.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002341 }
2342 pw.println(" ");
2343 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002345 pw.println(" mSoundNotification=" + mSoundNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002346 pw.println(" mVibrateNotification=" + mVibrateNotification);
Joe Onorato39f5b6a2009-07-23 12:29:19 -04002347 pw.println(" mDisabledNotifications=0x" + Integer.toHexString(mDisabledNotifications));
2348 pw.println(" mSystemReady=" + mSystemReady);
Daniel Sandler5e62e3a2013-04-15 20:57:02 -04002349 pw.println(" mArchive=" + mArchive.toString());
2350 Iterator<StatusBarNotification> iter = mArchive.descendingIterator();
2351 int i=0;
2352 while (iter.hasNext()) {
2353 pw.println(" " + iter.next());
2354 if (++i >= 5) {
2355 if (iter.hasNext()) pw.println(" ...");
2356 break;
2357 }
2358 }
2359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360 }
2361 }
2362}