blob: 04386759df509e451898cb1e00813ca1e6c58eeb [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
Christopher Tate06e5fed2013-10-09 14:39:15 -07001170 try {
1171 final int enabled = mContext.getPackageManager()
1172 .getApplicationEnabledSetting(pkgName);
1173 if (enabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
1174 || enabled == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
1175 cancelNotifications = false;
1176 }
1177 } catch (IllegalArgumentException e) {
1178 // Package doesn't exist; probably racing with uninstall.
1179 // cancelNotifications is already true, so nothing to do here.
1180 if (DBG) {
1181 Slog.i(TAG, "Exception trying to look up app enabled setting", e);
1182 }
Daniel Sandler26ece572012-06-01 15:38:46 -04001183 }
1184 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001185 pkgList = new String[]{pkgName};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 }
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001187
1188 boolean anyListenersInvolved = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001189 if (pkgList != null && (pkgList.length > 0)) {
1190 for (String pkgName : pkgList) {
John Spurlock79f78922013-05-16 09:10:05 -04001191 if (cancelNotifications) {
1192 cancelAllNotificationsInt(pkgName, 0, 0, !queryRestart,
1193 UserHandle.USER_ALL);
1194 }
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001195 if (mEnabledListenerPackageNames.contains(pkgName)) {
1196 anyListenersInvolved = true;
1197 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 }
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001200
1201 if (anyListenersInvolved) {
Chris Wrenae9bb572013-05-15 14:50:28 -04001202 // if we're not replacing a package, clean up orphaned bits
1203 if (!queryReplace) {
1204 disableNonexistentListeners();
1205 }
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001206 // make sure we're still bound to any of our
1207 // listeners who may have just upgraded
1208 rebindListenerServices();
1209 }
Mike Lockwood63b5ad92011-08-30 09:55:30 -04001210 } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
1211 // Keep track of screen on/off state, but do not turn off the notification light
1212 // until user passes through the lock screen or views the notification.
1213 mScreenOn = true;
1214 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
1215 mScreenOn = false;
Daniel Sandlere96ffb12010-03-11 13:38:06 -05001216 } else if (action.equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
Mike Lockwood63b5ad92011-08-30 09:55:30 -04001217 mInCall = (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
1218 TelephonyManager.EXTRA_STATE_OFFHOOK));
Daniel Sandlere96ffb12010-03-11 13:38:06 -05001219 updateNotificationPulse();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001220 } else if (action.equals(Intent.ACTION_USER_STOPPED)) {
1221 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
1222 if (userHandle >= 0) {
Dianne Hackborn41203752012-08-31 14:05:51 -07001223 cancelAllNotificationsInt(null, 0, 0, true, userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001224 }
Mike Lockwood63b5ad92011-08-30 09:55:30 -04001225 } else if (action.equals(Intent.ACTION_USER_PRESENT)) {
1226 // turn off LED when user passes through lock screen
1227 mNotificationLight.turnOff();
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001228 } else if (action.equals(Intent.ACTION_USER_SWITCHED)) {
1229 // reload per-user settings
1230 mSettingsObserver.update(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 }
1232 }
1233 };
1234
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001235 class SettingsObserver extends ContentObserver {
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001236 private final Uri NOTIFICATION_LIGHT_PULSE_URI
1237 = Settings.System.getUriFor(Settings.System.NOTIFICATION_LIGHT_PULSE);
1238
1239 private final Uri ENABLED_NOTIFICATION_LISTENERS_URI
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001240 = Settings.Secure.getUriFor(Settings.Secure.ENABLED_NOTIFICATION_LISTENERS);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001241
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001242 SettingsObserver(Handler handler) {
1243 super(handler);
1244 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001245
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001246 void observe() {
1247 ContentResolver resolver = mContext.getContentResolver();
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001248 resolver.registerContentObserver(NOTIFICATION_LIGHT_PULSE_URI,
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001249 false, this, UserHandle.USER_ALL);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001250 resolver.registerContentObserver(ENABLED_NOTIFICATION_LISTENERS_URI,
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001251 false, this, UserHandle.USER_ALL);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001252 update(null);
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001253 }
1254
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001255 @Override public void onChange(boolean selfChange, Uri uri) {
1256 update(uri);
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001257 }
1258
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001259 public void update(Uri uri) {
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001260 ContentResolver resolver = mContext.getContentResolver();
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001261 if (uri == null || NOTIFICATION_LIGHT_PULSE_URI.equals(uri)) {
1262 boolean pulseEnabled = Settings.System.getInt(resolver,
1263 Settings.System.NOTIFICATION_LIGHT_PULSE, 0) != 0;
1264 if (mNotificationPulseEnabled != pulseEnabled) {
1265 mNotificationPulseEnabled = pulseEnabled;
1266 updateNotificationPulse();
1267 }
1268 }
1269 if (uri == null || ENABLED_NOTIFICATION_LISTENERS_URI.equals(uri)) {
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001270 rebindListenerServices();
Mike Lockwoodc22404a2009-12-02 11:15:02 -05001271 }
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001272 }
1273 }
Mike Lockwoodc22404a2009-12-02 11:15:02 -05001274
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001275 private SettingsObserver mSettingsObserver;
1276
Daniel Sandleredbb3802012-11-13 20:49:47 -08001277 static long[] getLongArray(Resources r, int resid, int maxlen, long[] def) {
1278 int[] ar = r.getIntArray(resid);
1279 if (ar == null) {
1280 return def;
1281 }
1282 final int len = ar.length > maxlen ? maxlen : ar.length;
1283 long[] out = new long[len];
1284 for (int i=0; i<len; i++) {
1285 out[i] = ar[i];
1286 }
1287 return out;
1288 }
1289
Joe Onorato089de882010-04-12 08:18:45 -07001290 NotificationManagerService(Context context, StatusBarManagerService statusBar,
Mike Lockwood3a322132009-11-24 00:30:52 -05001291 LightsService lights)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 {
1293 super();
1294 mContext = context;
Jeff Brownc2346132012-04-13 01:55:38 -07001295 mVibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 mAm = ActivityManagerNative.getDefault();
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001297 mUserManager = (UserManager)context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 mToastQueue = new ArrayList<ToastRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 mHandler = new WorkerHandler();
San Mehat3ee13172010-02-04 20:54:43 -08001300
Daniel Sandler4a900acd2013-01-30 14:04:10 -05001301 mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
1302
1303 importOldBlockDb();
Daniel Sandler0da673f2012-04-11 12:33:16 -04001304
Joe Onorato089de882010-04-12 08:18:45 -07001305 mStatusBar = statusBar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 statusBar.setNotificationCallbacks(mNotificationCallbacks);
1307
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001308 mNotificationLight = lights.getLight(LightsService.LIGHT_ID_NOTIFICATIONS);
1309 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
1310
Mike Lockwood670f9322010-01-20 12:13:36 -05001311 Resources resources = mContext.getResources();
1312 mDefaultNotificationColor = resources.getColor(
Scott Greenwald9a05b312013-06-28 00:37:54 -04001313 R.color.config_defaultNotificationColor);
Mike Lockwood670f9322010-01-20 12:13:36 -05001314 mDefaultNotificationLedOn = resources.getInteger(
Scott Greenwald9a05b312013-06-28 00:37:54 -04001315 R.integer.config_defaultNotificationLedOn);
Mike Lockwood670f9322010-01-20 12:13:36 -05001316 mDefaultNotificationLedOff = resources.getInteger(
Scott Greenwald9a05b312013-06-28 00:37:54 -04001317 R.integer.config_defaultNotificationLedOff);
Mike Lockwood670f9322010-01-20 12:13:36 -05001318
Daniel Sandleredbb3802012-11-13 20:49:47 -08001319 mDefaultVibrationPattern = getLongArray(resources,
Scott Greenwald9a05b312013-06-28 00:37:54 -04001320 R.array.config_defaultNotificationVibePattern,
Daniel Sandleredbb3802012-11-13 20:49:47 -08001321 VIBRATE_PATTERN_MAXLEN,
1322 DEFAULT_VIBRATE_PATTERN);
1323
1324 mFallbackVibrationPattern = getLongArray(resources,
Scott Greenwald9a05b312013-06-28 00:37:54 -04001325 R.array.config_notificationFallbackVibePattern,
Daniel Sandleredbb3802012-11-13 20:49:47 -08001326 VIBRATE_PATTERN_MAXLEN,
1327 DEFAULT_VIBRATE_PATTERN);
1328
Joe Onorato39f5b6a2009-07-23 12:29:19 -04001329 // Don't start allowing notifications until the setup wizard has run once.
1330 // After that, including subsequent boots, init with notifications turned on.
1331 // This works on the first boot because the setup wizard will toggle this
1332 // flag at least once and we'll go back to 0 after that.
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001333 if (0 == Settings.Global.getInt(mContext.getContentResolver(),
1334 Settings.Global.DEVICE_PROVISIONED, 0)) {
Joe Onorato39f5b6a2009-07-23 12:29:19 -04001335 mDisabledNotifications = StatusBarManager.DISABLE_NOTIFICATION_ALERTS;
1336 }
1337
Mike Lockwood35e16bf2010-11-30 19:53:36 -05001338 // register for various Intents
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 IntentFilter filter = new IntentFilter();
Mike Lockwoodc22404a2009-12-02 11:15:02 -05001340 filter.addAction(Intent.ACTION_SCREEN_ON);
1341 filter.addAction(Intent.ACTION_SCREEN_OFF);
Daniel Sandlere96ffb12010-03-11 13:38:06 -05001342 filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
Mike Lockwood63b5ad92011-08-30 09:55:30 -04001343 filter.addAction(Intent.ACTION_USER_PRESENT);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001344 filter.addAction(Intent.ACTION_USER_STOPPED);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001345 filter.addAction(Intent.ACTION_USER_SWITCHED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 mContext.registerReceiver(mIntentReceiver, filter);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001347 IntentFilter pkgFilter = new IntentFilter();
Chris Wren3da73022013-05-10 14:41:21 -04001348 pkgFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001349 pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
Daniel Sandleraac0eb02011-08-06 22:51:56 -04001350 pkgFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001351 pkgFilter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
1352 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
1353 pkgFilter.addDataScheme("package");
1354 mContext.registerReceiver(mIntentReceiver, pkgFilter);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001355 IntentFilter sdFilter = new IntentFilter(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001356 mContext.registerReceiver(mIntentReceiver, sdFilter);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001357
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001358 mSettingsObserver = new SettingsObserver(mHandler);
1359 mSettingsObserver.observe();
Scott Greenwald9a05b312013-06-28 00:37:54 -04001360
1361 // spin up NotificationScorers
1362 String[] notificationScorerNames = resources.getStringArray(
1363 R.array.config_notificationScorers);
1364 for (String scorerName : notificationScorerNames) {
1365 try {
1366 Class<?> scorerClass = mContext.getClassLoader().loadClass(scorerName);
1367 NotificationScorer scorer = (NotificationScorer) scorerClass.newInstance();
1368 scorer.initialize(mContext);
1369 mScorers.add(scorer);
1370 } catch (ClassNotFoundException e) {
1371 Slog.w(TAG, "Couldn't find scorer " + scorerName + ".", e);
1372 } catch (InstantiationException e) {
1373 Slog.w(TAG, "Couldn't instantiate scorer " + scorerName + ".", e);
1374 } catch (IllegalAccessException e) {
1375 Slog.w(TAG, "Problem accessing scorer " + scorerName + ".", e);
1376 }
1377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 }
1379
Daniel Sandler4a900acd2013-01-30 14:04:10 -05001380 /**
1381 * Read the old XML-based app block database and import those blockages into the AppOps system.
1382 */
1383 private void importOldBlockDb() {
1384 loadBlockDb();
1385
1386 PackageManager pm = mContext.getPackageManager();
1387 for (String pkg : mBlockedPackages) {
1388 PackageInfo info = null;
1389 try {
1390 info = pm.getPackageInfo(pkg, 0);
1391 setNotificationsEnabledForPackage(pkg, info.applicationInfo.uid, false);
1392 } catch (NameNotFoundException e) {
1393 // forget you
1394 }
1395 }
1396 mBlockedPackages.clear();
1397 if (mPolicyFile != null) {
1398 mPolicyFile.delete();
1399 }
1400 }
1401
Joe Onorato30275482009-07-08 17:09:14 -07001402 void systemReady() {
Jeff Sharkey098d5802012-04-26 17:30:34 -07001403 mAudioService = IAudioService.Stub.asInterface(
1404 ServiceManager.getService(Context.AUDIO_SERVICE));
1405
Joe Onorato30275482009-07-08 17:09:14 -07001406 // no beeping until we're basically done booting
1407 mSystemReady = true;
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001408
1409 // make sure our listener services are properly bound
1410 rebindListenerServices();
Joe Onorato30275482009-07-08 17:09:14 -07001411 }
1412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 // Toasts
1414 // ============================================================================
1415 public void enqueueToast(String pkg, ITransientNotification callback, int duration)
1416 {
Daniel Sandlera7035902010-03-30 15:45:31 -04001417 if (DBG) Slog.i(TAG, "enqueueToast pkg=" + pkg + " callback=" + callback + " duration=" + duration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418
1419 if (pkg == null || callback == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001420 Slog.e(TAG, "Not doing toast. pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 return ;
1422 }
1423
Daniel Sandler7c011302013-06-10 12:06:51 -04001424 final boolean isSystemToast = isCallerSystem() || ("android".equals(pkg));
Daniel Sandler0da673f2012-04-11 12:33:16 -04001425
Daniel Sandler4a900acd2013-01-30 14:04:10 -05001426 if (ENABLE_BLOCKED_TOASTS && !noteNotificationOp(pkg, Binder.getCallingUid())) {
1427 if (!isSystemToast) {
1428 Slog.e(TAG, "Suppressing toast from package " + pkg + " by user request.");
1429 return;
1430 }
Daniel Sandler0da673f2012-04-11 12:33:16 -04001431 }
1432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 synchronized (mToastQueue) {
1434 int callingPid = Binder.getCallingPid();
1435 long callingId = Binder.clearCallingIdentity();
1436 try {
1437 ToastRecord record;
1438 int index = indexOfToastLocked(pkg, callback);
1439 // If it's already in the queue, we update it in place, we don't
1440 // move it to the end of the queue.
1441 if (index >= 0) {
1442 record = mToastQueue.get(index);
1443 record.update(duration);
1444 } else {
Vairavan Srinivasanf9eb06c2011-01-21 18:08:36 -08001445 // Limit the number of toasts that any given package except the android
1446 // package can enqueue. Prevents DOS attacks and deals with leaks.
Daniel Sandler0da673f2012-04-11 12:33:16 -04001447 if (!isSystemToast) {
Vairavan Srinivasanf9eb06c2011-01-21 18:08:36 -08001448 int count = 0;
1449 final int N = mToastQueue.size();
1450 for (int i=0; i<N; i++) {
1451 final ToastRecord r = mToastQueue.get(i);
1452 if (r.pkg.equals(pkg)) {
1453 count++;
1454 if (count >= MAX_PACKAGE_NOTIFICATIONS) {
1455 Slog.e(TAG, "Package has already posted " + count
1456 + " toasts. Not showing more. Package=" + pkg);
1457 return;
1458 }
1459 }
1460 }
1461 }
1462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 record = new ToastRecord(callingPid, pkg, callback, duration);
1464 mToastQueue.add(record);
1465 index = mToastQueue.size() - 1;
1466 keepProcessAliveLocked(callingPid);
1467 }
1468 // If it's at index 0, it's the current toast. It doesn't matter if it's
1469 // new or just been updated. Call back and tell it to show itself.
1470 // If the callback fails, this will remove it from the list, so don't
1471 // assume that it's valid after this.
1472 if (index == 0) {
1473 showNextToastLocked();
1474 }
1475 } finally {
1476 Binder.restoreCallingIdentity(callingId);
1477 }
1478 }
1479 }
1480
1481 public void cancelToast(String pkg, ITransientNotification callback) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001482 Slog.i(TAG, "cancelToast pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483
1484 if (pkg == null || callback == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001485 Slog.e(TAG, "Not cancelling notification. pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 return ;
1487 }
1488
1489 synchronized (mToastQueue) {
1490 long callingId = Binder.clearCallingIdentity();
1491 try {
1492 int index = indexOfToastLocked(pkg, callback);
1493 if (index >= 0) {
1494 cancelToastLocked(index);
1495 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001496 Slog.w(TAG, "Toast already cancelled. pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 }
1498 } finally {
1499 Binder.restoreCallingIdentity(callingId);
1500 }
1501 }
1502 }
1503
1504 private void showNextToastLocked() {
1505 ToastRecord record = mToastQueue.get(0);
1506 while (record != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001507 if (DBG) Slog.d(TAG, "Show pkg=" + record.pkg + " callback=" + record.callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 try {
1509 record.callback.show();
John Spurlockdcf4f212013-05-21 17:19:53 -04001510 scheduleTimeoutLocked(record);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 return;
1512 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001513 Slog.w(TAG, "Object died trying to show notification " + record.callback
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 + " in package " + record.pkg);
1515 // remove it from the list and let the process die
1516 int index = mToastQueue.indexOf(record);
1517 if (index >= 0) {
1518 mToastQueue.remove(index);
1519 }
1520 keepProcessAliveLocked(record.pid);
1521 if (mToastQueue.size() > 0) {
1522 record = mToastQueue.get(0);
1523 } else {
1524 record = null;
1525 }
1526 }
1527 }
1528 }
1529
1530 private void cancelToastLocked(int index) {
1531 ToastRecord record = mToastQueue.get(index);
1532 try {
1533 record.callback.hide();
1534 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001535 Slog.w(TAG, "Object died trying to hide notification " + record.callback
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 + " in package " + record.pkg);
1537 // don't worry about this, we're about to remove it from
1538 // the list anyway
1539 }
1540 mToastQueue.remove(index);
1541 keepProcessAliveLocked(record.pid);
1542 if (mToastQueue.size() > 0) {
1543 // Show the next one. If the callback fails, this will remove
1544 // it from the list, so don't assume that the list hasn't changed
1545 // after this point.
1546 showNextToastLocked();
1547 }
1548 }
1549
John Spurlockdcf4f212013-05-21 17:19:53 -04001550 private void scheduleTimeoutLocked(ToastRecord r)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 mHandler.removeCallbacksAndMessages(r);
John Spurlockf1a36642013-10-12 17:50:42 -04001553 Message m = Message.obtain(mHandler, MESSAGE_TIMEOUT, r);
1554 long delay = r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY;
1555 mHandler.sendMessageDelayed(m, delay);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 }
1557
1558 private void handleTimeout(ToastRecord record)
1559 {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001560 if (DBG) Slog.d(TAG, "Timeout pkg=" + record.pkg + " callback=" + record.callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 synchronized (mToastQueue) {
1562 int index = indexOfToastLocked(record.pkg, record.callback);
1563 if (index >= 0) {
1564 cancelToastLocked(index);
1565 }
1566 }
1567 }
1568
1569 // lock on mToastQueue
1570 private int indexOfToastLocked(String pkg, ITransientNotification callback)
1571 {
1572 IBinder cbak = callback.asBinder();
1573 ArrayList<ToastRecord> list = mToastQueue;
1574 int len = list.size();
1575 for (int i=0; i<len; i++) {
1576 ToastRecord r = list.get(i);
1577 if (r.pkg.equals(pkg) && r.callback.asBinder() == cbak) {
1578 return i;
1579 }
1580 }
1581 return -1;
1582 }
1583
1584 // lock on mToastQueue
1585 private void keepProcessAliveLocked(int pid)
1586 {
1587 int toastCount = 0; // toasts from this pid
1588 ArrayList<ToastRecord> list = mToastQueue;
1589 int N = list.size();
1590 for (int i=0; i<N; i++) {
1591 ToastRecord r = list.get(i);
1592 if (r.pid == pid) {
1593 toastCount++;
1594 }
1595 }
1596 try {
1597 mAm.setProcessForeground(mForegroundToken, pid, toastCount > 0);
1598 } catch (RemoteException e) {
1599 // Shouldn't happen.
1600 }
1601 }
1602
1603 private final class WorkerHandler extends Handler
1604 {
1605 @Override
1606 public void handleMessage(Message msg)
1607 {
1608 switch (msg.what)
1609 {
1610 case MESSAGE_TIMEOUT:
1611 handleTimeout((ToastRecord)msg.obj);
1612 break;
1613 }
1614 }
1615 }
1616
1617
1618 // Notifications
1619 // ============================================================================
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001620 public void enqueueNotificationWithTag(String pkg, String basePkg, String tag, int id,
1621 Notification notification, int[] idOut, int userId)
Fred Quintana6ecaff12009-09-25 14:23:13 -07001622 {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001623 enqueueNotificationInternal(pkg, basePkg, Binder.getCallingUid(), Binder.getCallingPid(),
Dianne Hackborn41203752012-08-31 14:05:51 -07001624 tag, id, notification, idOut, userId);
Daniel Sandlerd0a2f862010-08-03 15:29:31 -04001625 }
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001626
1627 private final static int clamp(int x, int low, int high) {
1628 return (x < low) ? low : ((x > high) ? high : x);
Daniel Sandlere40451a2011-02-03 14:51:35 -05001629 }
1630
Daniel Sandlerd0a2f862010-08-03 15:29:31 -04001631 // Not exposed via Binder; for system use only (otherwise malicious apps could spoof the
1632 // uid/pid of another application)
Scott Greenwald9b05c612013-06-25 23:44:05 -04001633
1634 public void enqueueNotificationInternal(final String pkg, String basePkg, final int callingUid,
1635 final int callingPid, final String tag, final int id, final Notification notification,
1636 int[] idOut, int incomingUserId)
Daniel Sandlerd0a2f862010-08-03 15:29:31 -04001637 {
Daniel Sandler0da673f2012-04-11 12:33:16 -04001638 if (DBG) {
1639 Slog.v(TAG, "enqueueNotificationInternal: pkg=" + pkg + " id=" + id + " notification=" + notification);
1640 }
1641 checkCallerIsSystemOrSameApp(pkg);
Daniel Sandler9eb434c2013-07-31 20:21:07 -04001642 final boolean isSystemNotification = isUidSystem(callingUid) || ("android".equals(pkg));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001643
Scott Greenwald9b05c612013-06-25 23:44:05 -04001644 final int userId = ActivityManager.handleIncomingUser(callingPid,
1645 callingUid, incomingUserId, true, false, "enqueueNotification", pkg);
Jeff Sharkey65c4a2b2012-09-25 17:22:27 -07001646 final UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001647
Joe Onoratobd73d012010-06-04 11:44:54 -07001648 // Limit the number of notifications that any given package except the android
1649 // package can enqueue. Prevents DOS attacks and deals with leaks.
Daniel Sandler0da673f2012-04-11 12:33:16 -04001650 if (!isSystemNotification) {
Joe Onoratobd73d012010-06-04 11:44:54 -07001651 synchronized (mNotificationList) {
1652 int count = 0;
1653 final int N = mNotificationList.size();
1654 for (int i=0; i<N; i++) {
1655 final NotificationRecord r = mNotificationList.get(i);
Daniel Sandler4f91efd2013-04-25 16:38:41 -04001656 if (r.sbn.getPackageName().equals(pkg) && r.sbn.getUserId() == userId) {
Joe Onoratobd73d012010-06-04 11:44:54 -07001657 count++;
1658 if (count >= MAX_PACKAGE_NOTIFICATIONS) {
1659 Slog.e(TAG, "Package has already posted " + count
1660 + " notifications. Not showing more. package=" + pkg);
1661 return;
1662 }
1663 }
1664 }
1665 }
1666 }
1667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 // This conditional is a dirty hack to limit the logging done on
1669 // behalf of the download manager without affecting other apps.
1670 if (!pkg.equals("com.android.providers.downloads")
1671 || Log.isLoggable("DownloadManager", Log.VERBOSE)) {
Daniel Sandler321e9c52012-10-12 10:59:26 -07001672 EventLog.writeEvent(EventLogTags.NOTIFICATION_ENQUEUE, pkg, id, tag, userId,
Daniel Sandlerb64cb882011-11-29 23:48:29 -05001673 notification.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 }
1675
1676 if (pkg == null || notification == null) {
1677 throw new IllegalArgumentException("null not allowed: pkg=" + pkg
1678 + " id=" + id + " notification=" + notification);
1679 }
1680 if (notification.icon != 0) {
1681 if (notification.contentView == null) {
1682 throw new IllegalArgumentException("contentView required: pkg=" + pkg
1683 + " id=" + id + " notification=" + notification);
1684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001685 }
1686
Scott Greenwald9b05c612013-06-25 23:44:05 -04001687 mHandler.post(new Runnable() {
1688 @Override
1689 public void run() {
Daniel Sandler0da673f2012-04-11 12:33:16 -04001690
Scott Greenwald9b05c612013-06-25 23:44:05 -04001691 // === Scoring ===
Daniel Sandler0da673f2012-04-11 12:33:16 -04001692
Scott Greenwald9b05c612013-06-25 23:44:05 -04001693 // 0. Sanitize inputs
1694 notification.priority = clamp(notification.priority, Notification.PRIORITY_MIN,
1695 Notification.PRIORITY_MAX);
1696 // Migrate notification flags to scores
1697 if (0 != (notification.flags & Notification.FLAG_HIGH_PRIORITY)) {
1698 if (notification.priority < Notification.PRIORITY_MAX) {
1699 notification.priority = Notification.PRIORITY_MAX;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 }
Scott Greenwald9b05c612013-06-25 23:44:05 -04001701 } else if (SCORE_ONGOING_HIGHER &&
1702 0 != (notification.flags & Notification.FLAG_ONGOING_EVENT)) {
1703 if (notification.priority < Notification.PRIORITY_HIGH) {
1704 notification.priority = Notification.PRIORITY_HIGH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 }
1706 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001707
Scott Greenwald9b05c612013-06-25 23:44:05 -04001708 // 1. initial score: buckets of 10, around the app
1709 int score = notification.priority * NOTIFICATION_PRIORITY_MULTIPLIER; //[-20..20]
1710
1711 // 2. Consult external heuristics (TBD)
1712
1713 // 3. Apply local rules
1714
Scott Greenwald9a05b312013-06-28 00:37:54 -04001715 int initialScore = score;
1716 if (!mScorers.isEmpty()) {
1717 if (DBG) Slog.v(TAG, "Initial score is " + score + ".");
1718 for (NotificationScorer scorer : mScorers) {
1719 try {
1720 score = scorer.getScore(notification, score);
1721 } catch (Throwable t) {
1722 Slog.w(TAG, "Scorer threw on .getScore.", t);
1723 }
1724 }
1725 if (DBG) Slog.v(TAG, "Final score is " + score + ".");
1726 }
1727
1728 // add extra to indicate score modified by NotificationScorer
1729 notification.extras.putBoolean(Notification.EXTRA_SCORE_MODIFIED,
1730 score != initialScore);
1731
Scott Greenwald9b05c612013-06-25 23:44:05 -04001732 // blocked apps
1733 if (ENABLE_BLOCKED_NOTIFICATIONS && !noteNotificationOp(pkg, callingUid)) {
1734 if (!isSystemNotification) {
1735 score = JUNK_SCORE;
1736 Slog.e(TAG, "Suppressing notification from package " + pkg
1737 + " by user request.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 }
Daniel Sandlerd4d2de22012-11-14 11:25:46 -08001739 }
1740
Scott Greenwald9b05c612013-06-25 23:44:05 -04001741 if (DBG) {
1742 Slog.v(TAG, "Assigned score=" + score + " to " + notification);
1743 }
1744
1745 if (score < SCORE_DISPLAY_THRESHOLD) {
1746 // Notification will be blocked because the score is too low.
1747 return;
1748 }
1749
1750 // Should this notification make noise, vibe, or use the LED?
1751 final boolean canInterrupt = (score >= SCORE_INTERRUPTION_THRESHOLD);
1752
1753 synchronized (mNotificationList) {
1754 final StatusBarNotification n = new StatusBarNotification(
1755 pkg, id, tag, callingUid, callingPid, score, notification, user);
1756 NotificationRecord r = new NotificationRecord(n);
1757 NotificationRecord old = null;
1758
1759 int index = indexOfNotificationLocked(pkg, tag, id, userId);
1760 if (index < 0) {
1761 mNotificationList.add(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 } else {
Scott Greenwald9b05c612013-06-25 23:44:05 -04001763 old = mNotificationList.remove(index);
1764 mNotificationList.add(index, r);
1765 // Make sure we don't lose the foreground service state.
1766 if (old != null) {
1767 notification.flags |=
1768 old.getNotification().flags & Notification.FLAG_FOREGROUND_SERVICE;
1769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 }
Scott Greenwald9b05c612013-06-25 23:44:05 -04001771
1772 // Ensure if this is a foreground service that the proper additional
1773 // flags are set.
1774 if ((notification.flags&Notification.FLAG_FOREGROUND_SERVICE) != 0) {
1775 notification.flags |= Notification.FLAG_ONGOING_EVENT
1776 | Notification.FLAG_NO_CLEAR;
1777 }
1778
1779 final int currentUser;
1780 final long token = Binder.clearCallingIdentity();
1781 try {
1782 currentUser = ActivityManager.getCurrentUser();
1783 } finally {
1784 Binder.restoreCallingIdentity(token);
1785 }
1786
1787 if (notification.icon != 0) {
1788 if (old != null && old.statusBarKey != null) {
1789 r.statusBarKey = old.statusBarKey;
1790 long identity = Binder.clearCallingIdentity();
1791 try {
1792 mStatusBar.updateNotification(r.statusBarKey, n);
Jeff Sharkey098d5802012-04-26 17:30:34 -07001793 }
Scott Greenwald9b05c612013-06-25 23:44:05 -04001794 finally {
1795 Binder.restoreCallingIdentity(identity);
1796 }
1797 } else {
1798 long identity = Binder.clearCallingIdentity();
1799 try {
1800 r.statusBarKey = mStatusBar.addNotification(n);
1801 if ((n.getNotification().flags & Notification.FLAG_SHOW_LIGHTS) != 0
1802 && canInterrupt) {
1803 mAttentionLight.pulse();
1804 }
1805 }
1806 finally {
1807 Binder.restoreCallingIdentity(identity);
1808 }
1809 }
1810 // Send accessibility events only for the current user.
1811 if (currentUser == userId) {
1812 sendAccessibilityEvent(notification, pkg);
1813 }
1814
1815 notifyPostedLocked(r);
1816 } else {
1817 Slog.e(TAG, "Not posting notification with icon==0: " + notification);
1818 if (old != null && old.statusBarKey != null) {
1819 long identity = Binder.clearCallingIdentity();
1820 try {
1821 mStatusBar.removeNotification(old.statusBarKey);
1822 }
1823 finally {
1824 Binder.restoreCallingIdentity(identity);
1825 }
1826
1827 notifyRemovedLocked(r);
1828 }
1829 // ATTENTION: in a future release we will bail out here
1830 // so that we do not play sounds, show lights, etc. for invalid notifications
1831 Slog.e(TAG, "WARNING: In a future release this will crash the app: "
1832 + n.getPackageName());
1833 }
1834
1835 // If we're not supposed to beep, vibrate, etc. then don't.
1836 if (((mDisabledNotifications & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) == 0)
1837 && (!(old != null
1838 && (notification.flags & Notification.FLAG_ONLY_ALERT_ONCE) != 0 ))
1839 && (r.getUserId() == UserHandle.USER_ALL ||
1840 (r.getUserId() == userId && r.getUserId() == currentUser))
1841 && canInterrupt
1842 && mSystemReady) {
1843
1844 final AudioManager audioManager = (AudioManager) mContext
1845 .getSystemService(Context.AUDIO_SERVICE);
1846
1847 // sound
1848
1849 // should we use the default notification sound? (indicated either by
1850 // DEFAULT_SOUND or because notification.sound is pointing at
1851 // Settings.System.NOTIFICATION_SOUND)
1852 final boolean useDefaultSound =
1853 (notification.defaults & Notification.DEFAULT_SOUND) != 0 ||
1854 Settings.System.DEFAULT_NOTIFICATION_URI
1855 .equals(notification.sound);
1856
1857 Uri soundUri = null;
1858 boolean hasValidSound = false;
1859
1860 if (useDefaultSound) {
1861 soundUri = Settings.System.DEFAULT_NOTIFICATION_URI;
1862
1863 // check to see if the default notification sound is silent
1864 ContentResolver resolver = mContext.getContentResolver();
1865 hasValidSound = Settings.System.getString(resolver,
1866 Settings.System.NOTIFICATION_SOUND) != null;
1867 } else if (notification.sound != null) {
1868 soundUri = notification.sound;
1869 hasValidSound = (soundUri != null);
1870 }
1871
1872 if (hasValidSound) {
1873 boolean looping = (notification.flags & Notification.FLAG_INSISTENT) != 0;
1874 int audioStreamType;
1875 if (notification.audioStreamType >= 0) {
1876 audioStreamType = notification.audioStreamType;
1877 } else {
1878 audioStreamType = DEFAULT_STREAM_TYPE;
1879 }
1880 mSoundNotification = r;
1881 // do not play notifications if stream volume is 0 (typically because
Jean-Michel Trivi23805662013-07-31 14:19:18 -07001882 // ringer mode is silent) or if there is a user of exclusive audio focus
Scott Greenwald9b05c612013-06-25 23:44:05 -04001883 if ((audioManager.getStreamVolume(audioStreamType) != 0)
Jean-Michel Trivi23805662013-07-31 14:19:18 -07001884 && !audioManager.isAudioFocusExclusive()) {
Scott Greenwald9b05c612013-06-25 23:44:05 -04001885 final long identity = Binder.clearCallingIdentity();
1886 try {
1887 final IRingtonePlayer player = mAudioService.getRingtonePlayer();
1888 if (player != null) {
1889 player.playAsync(soundUri, user, looping, audioStreamType);
1890 }
1891 } catch (RemoteException e) {
1892 } finally {
1893 Binder.restoreCallingIdentity(identity);
1894 }
1895 }
1896 }
1897
1898 // vibrate
1899 // Does the notification want to specify its own vibration?
1900 final boolean hasCustomVibrate = notification.vibrate != null;
1901
1902 // new in 4.2: if there was supposed to be a sound and we're in vibrate
1903 // mode, and no other vibration is specified, we fall back to vibration
1904 final boolean convertSoundToVibration =
1905 !hasCustomVibrate
1906 && hasValidSound
1907 && (audioManager.getRingerMode()
1908 == AudioManager.RINGER_MODE_VIBRATE);
1909
1910 // The DEFAULT_VIBRATE flag trumps any custom vibration AND the fallback.
1911 final boolean useDefaultVibrate =
1912 (notification.defaults & Notification.DEFAULT_VIBRATE) != 0;
1913
1914 if ((useDefaultVibrate || convertSoundToVibration || hasCustomVibrate)
1915 && !(audioManager.getRingerMode()
1916 == AudioManager.RINGER_MODE_SILENT)) {
1917 mVibrateNotification = r;
1918
1919 if (useDefaultVibrate || convertSoundToVibration) {
1920 // Escalate privileges so we can use the vibrator even if the
1921 // notifying app does not have the VIBRATE permission.
1922 long identity = Binder.clearCallingIdentity();
1923 try {
1924 mVibrator.vibrate(r.sbn.getUid(), r.sbn.getBasePkg(),
1925 useDefaultVibrate ? mDefaultVibrationPattern
1926 : mFallbackVibrationPattern,
1927 ((notification.flags & Notification.FLAG_INSISTENT) != 0)
1928 ? 0: -1);
1929 } finally {
1930 Binder.restoreCallingIdentity(identity);
1931 }
1932 } else if (notification.vibrate.length > 1) {
1933 // If you want your own vibration pattern, you need the VIBRATE
1934 // permission
1935 mVibrator.vibrate(r.sbn.getUid(), r.sbn.getBasePkg(),
1936 notification.vibrate,
1937 ((notification.flags & Notification.FLAG_INSISTENT) != 0)
1938 ? 0: -1);
1939 }
1940 }
1941 }
1942
1943 // light
1944 // the most recent thing gets the light
1945 mLights.remove(old);
1946 if (mLedNotification == old) {
1947 mLedNotification = null;
1948 }
1949 //Slog.i(TAG, "notification.lights="
1950 // + ((old.notification.lights.flags & Notification.FLAG_SHOW_LIGHTS)
1951 // != 0));
1952 if ((notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0
1953 && canInterrupt) {
1954 mLights.add(r);
1955 updateLightsLocked();
1956 } else {
1957 if (old != null
1958 && ((old.getFlags() & Notification.FLAG_SHOW_LIGHTS) != 0)) {
1959 updateLightsLocked();
Eric Laurent524dc042009-11-27 05:07:55 -08001960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 }
1962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 }
Scott Greenwald9b05c612013-06-25 23:44:05 -04001964 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965
1966 idOut[0] = id;
1967 }
1968
Joe Onorato30275482009-07-08 17:09:14 -07001969 private void sendAccessibilityEvent(Notification notification, CharSequence packageName) {
svetoslavganov75986cf2009-05-14 22:28:01 -07001970 AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
1971 if (!manager.isEnabled()) {
1972 return;
1973 }
1974
1975 AccessibilityEvent event =
1976 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED);
1977 event.setPackageName(packageName);
1978 event.setClassName(Notification.class.getName());
1979 event.setParcelableData(notification);
1980 CharSequence tickerText = notification.tickerText;
1981 if (!TextUtils.isEmpty(tickerText)) {
1982 event.getText().add(tickerText);
1983 }
1984
1985 manager.sendAccessibilityEvent(event);
1986 }
1987
Joe Onorato46439ce2010-11-19 13:56:21 -08001988 private void cancelNotificationLocked(NotificationRecord r, boolean sendDelete) {
1989 // tell the app
1990 if (sendDelete) {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001991 if (r.getNotification().deleteIntent != null) {
Joe Onorato46439ce2010-11-19 13:56:21 -08001992 try {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001993 r.getNotification().deleteIntent.send();
Joe Onorato46439ce2010-11-19 13:56:21 -08001994 } catch (PendingIntent.CanceledException ex) {
1995 // do nothing - there's no relevant way to recover, and
1996 // no reason to let this propagate
Daniel Sandler4f91efd2013-04-25 16:38:41 -04001997 Slog.w(TAG, "canceled PendingIntent for " + r.sbn.getPackageName(), ex);
Joe Onorato46439ce2010-11-19 13:56:21 -08001998 }
1999 }
2000 }
2001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002 // status bar
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002003 if (r.getNotification().icon != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 long identity = Binder.clearCallingIdentity();
2005 try {
Joe Onorato0cbda992010-05-02 16:28:15 -07002006 mStatusBar.removeNotification(r.statusBarKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 }
2008 finally {
2009 Binder.restoreCallingIdentity(identity);
2010 }
2011 r.statusBarKey = null;
Daniel Sandler09a247e2013-02-14 10:24:17 -05002012 notifyRemovedLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 }
2014
2015 // sound
2016 if (mSoundNotification == r) {
2017 mSoundNotification = null;
Jeff Sharkey098d5802012-04-26 17:30:34 -07002018 final long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 try {
Jeff Sharkey098d5802012-04-26 17:30:34 -07002020 final IRingtonePlayer player = mAudioService.getRingtonePlayer();
2021 if (player != null) {
2022 player.stopAsync();
2023 }
2024 } catch (RemoteException e) {
2025 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 Binder.restoreCallingIdentity(identity);
2027 }
2028 }
2029
2030 // vibrate
2031 if (mVibrateNotification == r) {
2032 mVibrateNotification = null;
2033 long identity = Binder.clearCallingIdentity();
2034 try {
2035 mVibrator.cancel();
2036 }
2037 finally {
2038 Binder.restoreCallingIdentity(identity);
2039 }
2040 }
2041
2042 // light
2043 mLights.remove(r);
2044 if (mLedNotification == r) {
2045 mLedNotification = null;
2046 }
Daniel Sandler23d7c702013-03-07 16:32:06 -05002047
2048 // Save it for users of getHistoricalNotifications()
2049 mArchive.record(r.sbn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 }
2051
2052 /**
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002053 * Cancels a notification ONLY if it has all of the {@code mustHaveFlags}
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002054 * and none of the {@code mustNotHaveFlags}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055 */
Svetoslav Ganov835835e2013-08-04 20:17:52 -07002056 private void cancelNotification(final String pkg, final String tag, final int id,
2057 final int mustHaveFlags, final int mustNotHaveFlags, final boolean sendDelete,
2058 final int userId) {
2059 // In enqueueNotificationInternal notifications are added by scheduling the
2060 // work on the worker handler. Hence, we also schedule the cancel on this
2061 // handler to avoid a scenario where an add notification call followed by a
2062 // remove notification call ends up in not removing the notification.
2063 mHandler.post(new Runnable() {
2064 @Override
2065 public void run() {
2066 EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL, pkg, id, tag, userId,
2067 mustHaveFlags, mustNotHaveFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002068
Svetoslav Ganov835835e2013-08-04 20:17:52 -07002069 synchronized (mNotificationList) {
2070 int index = indexOfNotificationLocked(pkg, tag, id, userId);
2071 if (index >= 0) {
2072 NotificationRecord r = mNotificationList.get(index);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002073
Svetoslav Ganov835835e2013-08-04 20:17:52 -07002074 if ((r.getNotification().flags & mustHaveFlags) != mustHaveFlags) {
2075 return;
2076 }
2077 if ((r.getNotification().flags & mustNotHaveFlags) != 0) {
2078 return;
2079 }
2080
2081 mNotificationList.remove(index);
2082
2083 cancelNotificationLocked(r, sendDelete);
2084 updateLightsLocked();
2085 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002087 }
Svetoslav Ganov835835e2013-08-04 20:17:52 -07002088 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 }
2090
2091 /**
Daniel Sandler321e9c52012-10-12 10:59:26 -07002092 * Determine whether the userId applies to the notification in question, either because
2093 * they match exactly, or one of them is USER_ALL (which is treated as a wildcard).
2094 */
2095 private boolean notificationMatchesUserId(NotificationRecord r, int userId) {
2096 return
2097 // looking for USER_ALL notifications? match everything
2098 userId == UserHandle.USER_ALL
2099 // a notification sent to USER_ALL matches any query
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002100 || r.getUserId() == UserHandle.USER_ALL
Daniel Sandler321e9c52012-10-12 10:59:26 -07002101 // an exact user match
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002102 || r.getUserId() == userId;
Daniel Sandler321e9c52012-10-12 10:59:26 -07002103 }
2104
2105 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106 * Cancels all notifications from a given package that have all of the
2107 * {@code mustHaveFlags}.
2108 */
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002109 boolean cancelAllNotificationsInt(String pkg, int mustHaveFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002110 int mustNotHaveFlags, boolean doit, int userId) {
Daniel Sandler321e9c52012-10-12 10:59:26 -07002111 EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL_ALL, pkg, userId,
2112 mustHaveFlags, mustNotHaveFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113
2114 synchronized (mNotificationList) {
2115 final int N = mNotificationList.size();
2116 boolean canceledSomething = false;
2117 for (int i = N-1; i >= 0; --i) {
2118 NotificationRecord r = mNotificationList.get(i);
Daniel Sandler321e9c52012-10-12 10:59:26 -07002119 if (!notificationMatchesUserId(r, userId)) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002120 continue;
2121 }
Amith Yamasani5ec00e92012-11-07 16:58:30 -08002122 // Don't remove notifications to all, if there's no package name specified
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002123 if (r.getUserId() == UserHandle.USER_ALL && pkg == null) {
Amith Yamasani5ec00e92012-11-07 16:58:30 -08002124 continue;
2125 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002126 if ((r.getFlags() & mustHaveFlags) != mustHaveFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127 continue;
2128 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002129 if ((r.getFlags() & mustNotHaveFlags) != 0) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002130 continue;
2131 }
Daniel Sandler4f91efd2013-04-25 16:38:41 -04002132 if (pkg != null && !r.sbn.getPackageName().equals(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133 continue;
2134 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002135 canceledSomething = true;
2136 if (!doit) {
2137 return true;
2138 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 mNotificationList.remove(i);
Joe Onorato46439ce2010-11-19 13:56:21 -08002140 cancelNotificationLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 }
2142 if (canceledSomething) {
2143 updateLightsLocked();
2144 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002145 return canceledSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146 }
2147 }
2148
Dianne Hackborn41203752012-08-31 14:05:51 -07002149 public void cancelNotificationWithTag(String pkg, String tag, int id, int userId) {
Daniel Sandler0da673f2012-04-11 12:33:16 -04002150 checkCallerIsSystemOrSameApp(pkg);
Dianne Hackborn41203752012-08-31 14:05:51 -07002151 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07002152 Binder.getCallingUid(), userId, true, false, "cancelNotificationWithTag", pkg);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002153 // Don't allow client applications to cancel foreground service notis.
Fred Quintana6ecaff12009-09-25 14:23:13 -07002154 cancelNotification(pkg, tag, id, 0,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002155 Binder.getCallingUid() == Process.SYSTEM_UID
Dianne Hackborn41203752012-08-31 14:05:51 -07002156 ? 0 : Notification.FLAG_FOREGROUND_SERVICE, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 }
2158
Dianne Hackborn41203752012-08-31 14:05:51 -07002159 public void cancelAllNotifications(String pkg, int userId) {
Daniel Sandler0da673f2012-04-11 12:33:16 -04002160 checkCallerIsSystemOrSameApp(pkg);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002161
Dianne Hackborn41203752012-08-31 14:05:51 -07002162 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07002163 Binder.getCallingUid(), userId, true, false, "cancelAllNotifications", pkg);
Dianne Hackborn41203752012-08-31 14:05:51 -07002164
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002165 // Calling from user space, don't allow the canceling of actively
2166 // running foreground services.
Dianne Hackborn41203752012-08-31 14:05:51 -07002167 cancelAllNotificationsInt(pkg, 0, Notification.FLAG_FOREGROUND_SERVICE, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002168 }
2169
Daniel Sandler9eb434c2013-07-31 20:21:07 -04002170 // Return true if the UID is a system or phone UID and therefore should not have
Daniel Sandler7c011302013-06-10 12:06:51 -04002171 // any notifications or toasts blocked.
Daniel Sandler9eb434c2013-07-31 20:21:07 -04002172 boolean isUidSystem(int uid) {
Daniel Sandler7c011302013-06-10 12:06:51 -04002173 final int appid = UserHandle.getAppId(uid);
2174 return (appid == Process.SYSTEM_UID || appid == Process.PHONE_UID || uid == 0);
2175 }
2176
Daniel Sandler9eb434c2013-07-31 20:21:07 -04002177 // same as isUidSystem(int, int) for the Binder caller's UID.
2178 boolean isCallerSystem() {
2179 return isUidSystem(Binder.getCallingUid());
2180 }
2181
Daniel Sandler0da673f2012-04-11 12:33:16 -04002182 void checkCallerIsSystem() {
Daniel Sandler7c011302013-06-10 12:06:51 -04002183 if (isCallerSystem()) {
Daniel Sandler0da673f2012-04-11 12:33:16 -04002184 return;
2185 }
Daniel Sandler7c011302013-06-10 12:06:51 -04002186 throw new SecurityException("Disallowed call for uid " + Binder.getCallingUid());
Daniel Sandler0da673f2012-04-11 12:33:16 -04002187 }
2188
2189 void checkCallerIsSystemOrSameApp(String pkg) {
Daniel Sandler7c011302013-06-10 12:06:51 -04002190 if (isCallerSystem()) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002191 return;
2192 }
Daniel Sandler7c011302013-06-10 12:06:51 -04002193 final int uid = Binder.getCallingUid();
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002194 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07002195 ApplicationInfo ai = AppGlobals.getPackageManager().getApplicationInfo(
2196 pkg, 0, UserHandle.getCallingUserId());
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002197 if (!UserHandle.isSameApp(ai.uid, uid)) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002198 throw new SecurityException("Calling uid " + uid + " gave package"
2199 + pkg + " which is owned by uid " + ai.uid);
2200 }
Amith Yamasanif203aee2012-08-29 18:41:53 -07002201 } catch (RemoteException re) {
2202 throw new SecurityException("Unknown package " + pkg + "\n" + re);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002203 }
2204 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002205
Dianne Hackborn41203752012-08-31 14:05:51 -07002206 void cancelAll(int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002207 synchronized (mNotificationList) {
2208 final int N = mNotificationList.size();
2209 for (int i=N-1; i>=0; i--) {
2210 NotificationRecord r = mNotificationList.get(i);
2211
Daniel Sandler321e9c52012-10-12 10:59:26 -07002212 if (!notificationMatchesUserId(r, userId)) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002213 continue;
2214 }
2215
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002216 if ((r.getFlags() & (Notification.FLAG_ONGOING_EVENT
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002217 | Notification.FLAG_NO_CLEAR)) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 mNotificationList.remove(i);
Joe Onorato46439ce2010-11-19 13:56:21 -08002219 cancelNotificationLocked(r, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002220 }
2221 }
2222
2223 updateLightsLocked();
2224 }
2225 }
2226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002227 // lock on mNotificationList
2228 private void updateLightsLocked()
2229 {
The Android Open Source Project10592532009-03-18 17:39:46 -07002230 // handle notification lights
2231 if (mLedNotification == null) {
2232 // get next notification, if any
2233 int n = mLights.size();
2234 if (n > 0) {
2235 mLedNotification = mLights.get(n-1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002236 }
2237 }
Mike Lockwoodc22404a2009-12-02 11:15:02 -05002238
Mike Lockwood63b5ad92011-08-30 09:55:30 -04002239 // Don't flash while we are in a call or screen is on
2240 if (mLedNotification == null || mInCall || mScreenOn) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002241 mNotificationLight.turnOff();
The Android Open Source Project10592532009-03-18 17:39:46 -07002242 } else {
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04002243 final Notification ledno = mLedNotification.sbn.getNotification();
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002244 int ledARGB = ledno.ledARGB;
2245 int ledOnMS = ledno.ledOnMS;
2246 int ledOffMS = ledno.ledOffMS;
2247 if ((ledno.defaults & Notification.DEFAULT_LIGHTS) != 0) {
Mike Lockwood670f9322010-01-20 12:13:36 -05002248 ledARGB = mDefaultNotificationColor;
2249 ledOnMS = mDefaultNotificationLedOn;
2250 ledOffMS = mDefaultNotificationLedOff;
2251 }
2252 if (mNotificationPulseEnabled) {
2253 // pulse repeatedly
2254 mNotificationLight.setFlashing(ledARGB, LightsService.LIGHT_FLASH_TIMED,
2255 ledOnMS, ledOffMS);
Mike Lockwood670f9322010-01-20 12:13:36 -05002256 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002258 }
2259
2260 // lock on mNotificationList
Dianne Hackborn41203752012-08-31 14:05:51 -07002261 private int indexOfNotificationLocked(String pkg, String tag, int id, int userId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002262 {
2263 ArrayList<NotificationRecord> list = mNotificationList;
2264 final int len = list.size();
2265 for (int i=0; i<len; i++) {
2266 NotificationRecord r = list.get(i);
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04002267 if (!notificationMatchesUserId(r, userId) || r.sbn.getId() != id) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002268 continue;
2269 }
Fred Quintana6ecaff12009-09-25 14:23:13 -07002270 if (tag == null) {
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04002271 if (r.sbn.getTag() != null) {
Fred Quintana6ecaff12009-09-25 14:23:13 -07002272 continue;
2273 }
2274 } else {
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04002275 if (!tag.equals(r.sbn.getTag())) {
Fred Quintana6ecaff12009-09-25 14:23:13 -07002276 continue;
2277 }
2278 }
Daniel Sandler4f91efd2013-04-25 16:38:41 -04002279 if (r.sbn.getPackageName().equals(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280 return i;
2281 }
2282 }
2283 return -1;
2284 }
2285
Mike Lockwoodc22404a2009-12-02 11:15:02 -05002286 private void updateNotificationPulse() {
2287 synchronized (mNotificationList) {
2288 updateLightsLocked();
2289 }
2290 }
2291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 // ======================================================================
2293 @Override
2294 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2295 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2296 != PackageManager.PERMISSION_GRANTED) {
2297 pw.println("Permission Denial: can't dump NotificationManager from from pid="
2298 + Binder.getCallingPid()
2299 + ", uid=" + Binder.getCallingUid());
2300 return;
2301 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002303 pw.println("Current Notification Manager state:");
2304
Daniel Sandler5feceeb2013-03-22 18:29:23 -07002305 pw.println(" Listeners (" + mEnabledListenersForCurrentUser.size()
2306 + ") enabled for current user:");
2307 for (ComponentName cmpt : mEnabledListenersForCurrentUser) {
2308 pw.println(" " + cmpt);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04002309 }
Daniel Sandler4b749ef2013-03-18 21:53:04 -04002310
Daniel Sandler5feceeb2013-03-22 18:29:23 -07002311 pw.println(" Live listeners (" + mListeners.size() + "):");
Daniel Sandler4b749ef2013-03-18 21:53:04 -04002312 for (NotificationListenerInfo info : mListeners) {
Daniel Sandler5feceeb2013-03-22 18:29:23 -07002313 pw.println(" " + info.component
2314 + " (user " + info.userid + "): " + info.listener
2315 + (info.isSystem?" SYSTEM":""));
Daniel Sandler4b749ef2013-03-18 21:53:04 -04002316 }
2317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 int N;
2319
2320 synchronized (mToastQueue) {
2321 N = mToastQueue.size();
2322 if (N > 0) {
2323 pw.println(" Toast Queue:");
2324 for (int i=0; i<N; i++) {
2325 mToastQueue.get(i).dump(pw, " ");
2326 }
2327 pw.println(" ");
2328 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002330 }
2331
2332 synchronized (mNotificationList) {
2333 N = mNotificationList.size();
2334 if (N > 0) {
2335 pw.println(" Notification List:");
2336 for (int i=0; i<N; i++) {
2337 mNotificationList.get(i).dump(pw, " ", mContext);
2338 }
2339 pw.println(" ");
2340 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002342 N = mLights.size();
2343 if (N > 0) {
2344 pw.println(" Lights List:");
2345 for (int i=0; i<N; i++) {
Daniel Sandlerf45564e2013-04-15 15:05:08 -04002346 pw.println(" " + mLights.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002347 }
2348 pw.println(" ");
2349 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002351 pw.println(" mSoundNotification=" + mSoundNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002352 pw.println(" mVibrateNotification=" + mVibrateNotification);
Joe Onorato39f5b6a2009-07-23 12:29:19 -04002353 pw.println(" mDisabledNotifications=0x" + Integer.toHexString(mDisabledNotifications));
2354 pw.println(" mSystemReady=" + mSystemReady);
Daniel Sandler5e62e3a2013-04-15 20:57:02 -04002355 pw.println(" mArchive=" + mArchive.toString());
2356 Iterator<StatusBarNotification> iter = mArchive.descendingIterator();
2357 int i=0;
2358 while (iter.hasNext()) {
2359 pw.println(" " + iter.next());
2360 if (++i >= 5) {
2361 if (iter.hasNext()) pw.println(" ...");
2362 break;
2363 }
2364 }
2365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 }
2367 }
2368}