blob: 903bc0bfc526d21fd8976372632232b43884c430 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey098d5802012-04-26 17:30:34 -070019import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
20import static org.xmlpull.v1.XmlPullParser.END_TAG;
21import static org.xmlpull.v1.XmlPullParser.START_TAG;
svetoslavganov75986cf2009-05-14 22:28:01 -070022
Dianne Hackborn41203752012-08-31 14:05:51 -070023import android.app.ActivityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.app.ActivityManagerNative;
Amith Yamasanif203aee2012-08-29 18:41:53 -070025import android.app.AppGlobals;
Daniel Sandler4a900acd2013-01-30 14:04:10 -050026import android.app.AppOpsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.app.IActivityManager;
28import android.app.INotificationManager;
29import android.app.ITransientNotification;
30import android.app.Notification;
31import android.app.PendingIntent;
32import android.app.StatusBarManager;
33import android.content.BroadcastReceiver;
Daniel Sandler5feceeb2013-03-22 18:29:23 -070034import android.content.ComponentName;
Dianne Hackborn1dac2772009-06-26 18:16:48 -070035import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.content.Context;
37import android.content.Intent;
38import android.content.IntentFilter;
Daniel Sandler5feceeb2013-03-22 18:29:23 -070039import android.content.ServiceConnection;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070040import android.content.pm.ApplicationInfo;
Daniel Sandler4a900acd2013-01-30 14:04:10 -050041import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.pm.PackageManager;
Chris Wrenae9bb572013-05-15 14:50:28 -040043import android.content.pm.ResolveInfo;
44import android.content.pm.ServiceInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.PackageManager.NameNotFoundException;
46import android.content.res.Resources;
Dianne Hackborn1dac2772009-06-26 18:16:48 -070047import android.database.ContentObserver;
Daniel Sandlerf45564e2013-04-15 15:05:08 -040048import android.graphics.Bitmap;
svetoslavganov75986cf2009-05-14 22:28:01 -070049import android.media.AudioManager;
Jeff Sharkey098d5802012-04-26 17:30:34 -070050import android.media.IAudioService;
51import android.media.IRingtonePlayer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.Binder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.os.IBinder;
56import android.os.Message;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070057import android.os.Process;
svetoslavganov75986cf2009-05-14 22:28:01 -070058import android.os.RemoteException;
Jeff Sharkey098d5802012-04-26 17:30:34 -070059import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070060import android.os.UserHandle;
Daniel Sandler4b749ef2013-03-18 21:53:04 -040061import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.os.Vibrator;
63import android.provider.Settings;
Daniel Sandler5feceeb2013-03-22 18:29:23 -070064import android.service.notification.INotificationListener;
65import android.service.notification.NotificationListenerService;
66import android.service.notification.StatusBarNotification;
Daniel Sandlere96ffb12010-03-11 13:38:06 -050067import android.telephony.TelephonyManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070068import android.text.TextUtils;
Dianne Hackborn39606a02012-07-31 17:54:35 -070069import android.util.AtomicFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.util.EventLog;
71import android.util.Log;
Andy Stadler110988c2010-12-03 14:29:16 -080072import android.util.Slog;
Daniel Sandler0da673f2012-04-11 12:33:16 -040073import android.util.Xml;
svetoslavganov75986cf2009-05-14 22:28:01 -070074import android.view.accessibility.AccessibilityEvent;
75import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.widget.Toast;
77
Jeff Sharkey098d5802012-04-26 17:30:34 -070078import org.xmlpull.v1.XmlPullParser;
79import org.xmlpull.v1.XmlPullParserException;
Jeff Sharkey098d5802012-04-26 17:30:34 -070080
Daniel Sandler0da673f2012-04-11 12:33:16 -040081import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import java.io.FileDescriptor;
Daniel Sandler0da673f2012-04-11 12:33:16 -040083import java.io.FileInputStream;
84import java.io.FileNotFoundException;
Daniel Sandler0da673f2012-04-11 12:33:16 -040085import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import java.io.PrintWriter;
Daniel Sandlerf45564e2013-04-15 15:05:08 -040087import java.lang.reflect.Array;
Daniel Sandlerfde19b12013-01-17 00:21:05 -050088import java.util.ArrayDeque;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import java.util.ArrayList;
90import java.util.Arrays;
Daniel Sandler0da673f2012-04-11 12:33:16 -040091import java.util.HashSet;
Daniel Sandlerfde19b12013-01-17 00:21:05 -050092import java.util.Iterator;
Chris Wrenae9bb572013-05-15 14:50:28 -040093import java.util.List;
Daniel Sandlerfde19b12013-01-17 00:21:05 -050094import java.util.NoSuchElementException;
Chris Wrenae9bb572013-05-15 14:50:28 -040095import java.util.Set;
Daniel Sandler0da673f2012-04-11 12:33:16 -040096
97import libcore.io.IoUtils;
98
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099
Daniel Sandlerd0a2f862010-08-03 15:29:31 -0400100/** {@hide} */
101public class NotificationManagerService extends INotificationManager.Stub
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102{
103 private static final String TAG = "NotificationService";
104 private static final boolean DBG = false;
105
Joe Onoratobd73d012010-06-04 11:44:54 -0700106 private static final int MAX_PACKAGE_NOTIFICATIONS = 50;
107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 // message codes
109 private static final int MESSAGE_TIMEOUT = 2;
110
111 private static final int LONG_DELAY = 3500; // 3.5 seconds
112 private static final int SHORT_DELAY = 2000; // 2 seconds
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800113
114 private static final long[] DEFAULT_VIBRATE_PATTERN = {0, 250, 250, 250};
Daniel Sandleredbb3802012-11-13 20:49:47 -0800115 private static final int VIBRATE_PATTERN_MAXLEN = 8 * 2 + 1; // up to eight bumps
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116
117 private static final int DEFAULT_STREAM_TYPE = AudioManager.STREAM_NOTIFICATION;
Daniel Sandler49a2ad12012-03-28 15:46:39 -0400118 private static final boolean SCORE_ONGOING_HIGHER = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119
Daniel Sandler0da673f2012-04-11 12:33:16 -0400120 private static final int JUNK_SCORE = -1000;
121 private static final int NOTIFICATION_PRIORITY_MULTIPLIER = 10;
122 private static final int SCORE_DISPLAY_THRESHOLD = Notification.PRIORITY_MIN * NOTIFICATION_PRIORITY_MULTIPLIER;
123
Daniel Sandler526fa0e2012-12-04 14:51:50 -0500124 // Notifications with scores below this will not interrupt the user, either via LED or
125 // sound or vibration
126 private static final int SCORE_INTERRUPTION_THRESHOLD =
127 Notification.PRIORITY_LOW * NOTIFICATION_PRIORITY_MULTIPLIER;
128
Daniel Sandler0da673f2012-04-11 12:33:16 -0400129 private static final boolean ENABLE_BLOCKED_NOTIFICATIONS = true;
130 private static final boolean ENABLE_BLOCKED_TOASTS = true;
131
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700132 private static final String ENABLED_NOTIFICATION_LISTENERS_SEPARATOR = ":";
133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134 final Context mContext;
135 final IActivityManager mAm;
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400136 final UserManager mUserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 final IBinder mForegroundToken = new Binder();
138
139 private WorkerHandler mHandler;
Joe Onorato089de882010-04-12 08:18:45 -0700140 private StatusBarManagerService mStatusBar;
Mike Lockwood3cb67a32009-11-27 14:25:58 -0500141 private LightsService.Light mNotificationLight;
142 private LightsService.Light mAttentionLight;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
Mike Lockwood670f9322010-01-20 12:13:36 -0500144 private int mDefaultNotificationColor;
145 private int mDefaultNotificationLedOn;
146 private int mDefaultNotificationLedOff;
147
Daniel Sandleredbb3802012-11-13 20:49:47 -0800148 private long[] mDefaultVibrationPattern;
149 private long[] mFallbackVibrationPattern;
150
Joe Onorato30275482009-07-08 17:09:14 -0700151 private boolean mSystemReady;
Joe Onorato39f5b6a2009-07-23 12:29:19 -0400152 private int mDisabledNotifications;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153
Jeff Sharkey098d5802012-04-26 17:30:34 -0700154 private NotificationRecord mSoundNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 private NotificationRecord mVibrateNotification;
Jeff Sharkey098d5802012-04-26 17:30:34 -0700156
157 private IAudioService mAudioService;
Jeff Brownc2346132012-04-13 01:55:38 -0700158 private Vibrator mVibrator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
Mike Lockwoodc22404a2009-12-02 11:15:02 -0500160 // for enabling and disabling notification pulse behavior
Mike Lockwood63b5ad92011-08-30 09:55:30 -0400161 private boolean mScreenOn = true;
Daniel Sandlere96ffb12010-03-11 13:38:06 -0500162 private boolean mInCall = false;
Mike Lockwoodc22404a2009-12-02 11:15:02 -0500163 private boolean mNotificationPulseEnabled;
164
Daniel Sandler09a247e2013-02-14 10:24:17 -0500165 // used as a mutex for access to all active notifications & listeners
Fred Quintana6ecaff12009-09-25 14:23:13 -0700166 private final ArrayList<NotificationRecord> mNotificationList =
167 new ArrayList<NotificationRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168
169 private ArrayList<ToastRecord> mToastQueue;
170
171 private ArrayList<NotificationRecord> mLights = new ArrayList<NotificationRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172 private NotificationRecord mLedNotification;
svetoslavganov75986cf2009-05-14 22:28:01 -0700173
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500174 private final AppOpsManager mAppOps;
175
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700176 // contains connections to all connected listeners, including app services
177 // and system listeners
178 private ArrayList<NotificationListenerInfo> mListeners
179 = new ArrayList<NotificationListenerInfo>();
180 // things that will be put into mListeners as soon as they're ready
181 private ArrayList<String> mServicesBinding = new ArrayList<String>();
182 // lists the component names of all enabled (and therefore connected) listener
183 // app services for the current user only
184 private HashSet<ComponentName> mEnabledListenersForCurrentUser
185 = new HashSet<ComponentName>();
186 // Just the packages from mEnabledListenersForCurrentUser
187 private HashSet<String> mEnabledListenerPackageNames = new HashSet<String>();
Daniel Sandler09a247e2013-02-14 10:24:17 -0500188
Daniel Sandler0da673f2012-04-11 12:33:16 -0400189 // Notification control database. For now just contains disabled packages.
190 private AtomicFile mPolicyFile;
191 private HashSet<String> mBlockedPackages = new HashSet<String>();
192
193 private static final int DB_VERSION = 1;
194
195 private static final String TAG_BODY = "notification-policy";
196 private static final String ATTR_VERSION = "version";
197
198 private static final String TAG_BLOCKED_PKGS = "blocked-packages";
199 private static final String TAG_PACKAGE = "package";
200 private static final String ATTR_NAME = "name";
201
Daniel Sandler09a247e2013-02-14 10:24:17 -0500202 private class NotificationListenerInfo implements DeathRecipient {
203 INotificationListener listener;
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700204 ComponentName component;
Daniel Sandler09a247e2013-02-14 10:24:17 -0500205 int userid;
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400206 boolean isSystem;
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700207 ServiceConnection connection;
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400208
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700209 public NotificationListenerInfo(INotificationListener listener, ComponentName component,
210 int userid, boolean isSystem) {
Daniel Sandler09a247e2013-02-14 10:24:17 -0500211 this.listener = listener;
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700212 this.component = component;
Daniel Sandler09a247e2013-02-14 10:24:17 -0500213 this.userid = userid;
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400214 this.isSystem = isSystem;
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700215 this.connection = null;
216 }
217
218 public NotificationListenerInfo(INotificationListener listener, ComponentName component,
219 int userid, ServiceConnection connection) {
220 this.listener = listener;
221 this.component = component;
222 this.userid = userid;
223 this.isSystem = false;
224 this.connection = connection;
Daniel Sandler09a247e2013-02-14 10:24:17 -0500225 }
226
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400227 boolean enabledAndUserMatches(StatusBarNotification sbn) {
228 final int nid = sbn.getUserId();
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700229 if (!isEnabledForCurrentUser()) {
230 return false;
231 }
Daniel Sandler21ca44d2013-03-07 13:58:00 -0500232 if (this.userid == UserHandle.USER_ALL) return true;
Daniel Sandler21ca44d2013-03-07 13:58:00 -0500233 return (nid == UserHandle.USER_ALL || nid == this.userid);
234 }
235
Daniel Sandler09a247e2013-02-14 10:24:17 -0500236 public void notifyPostedIfUserMatch(StatusBarNotification sbn) {
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700237 if (!enabledAndUserMatches(sbn)) {
238 return;
239 }
Daniel Sandler09a247e2013-02-14 10:24:17 -0500240 try {
241 listener.onNotificationPosted(sbn);
242 } catch (RemoteException ex) {
Daniel Sandler1a497d32013-04-18 14:52:45 -0400243 Log.e(TAG, "unable to notify listener (posted): " + listener, ex);
Daniel Sandler09a247e2013-02-14 10:24:17 -0500244 }
245 }
246
247 public void notifyRemovedIfUserMatch(StatusBarNotification sbn) {
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400248 if (!enabledAndUserMatches(sbn)) return;
Daniel Sandler09a247e2013-02-14 10:24:17 -0500249 try {
250 listener.onNotificationRemoved(sbn);
251 } catch (RemoteException ex) {
Daniel Sandler1a497d32013-04-18 14:52:45 -0400252 Log.e(TAG, "unable to notify listener (removed): " + listener, ex);
Daniel Sandler09a247e2013-02-14 10:24:17 -0500253 }
254 }
255
256 @Override
257 public void binderDied() {
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700258 if (connection == null) {
259 // This is not a service; it won't be recreated. We can give up this connection.
260 unregisterListener(this.listener, this.userid);
261 }
Daniel Sandler09a247e2013-02-14 10:24:17 -0500262 }
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400263
264 /** convenience method for looking in mEnabledListenersForCurrentUser */
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700265 public boolean isEnabledForCurrentUser() {
266 if (this.isSystem) return true;
267 if (this.connection == null) return false;
268 return mEnabledListenersForCurrentUser.contains(this.component);
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400269 }
Daniel Sandler09a247e2013-02-14 10:24:17 -0500270 }
271
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500272 private static class Archive {
Daniel Sandler5e62e3a2013-04-15 20:57:02 -0400273 static final int BUFFER_SIZE = 250;
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500274 ArrayDeque<StatusBarNotification> mBuffer = new ArrayDeque<StatusBarNotification>(BUFFER_SIZE);
275
276 public Archive() {
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500277 }
Jeff Sharkey0c1baf92013-04-03 13:08:52 -0700278
Daniel Sandler5e62e3a2013-04-15 20:57:02 -0400279 public String toString() {
280 final StringBuilder sb = new StringBuilder();
281 final int N = mBuffer.size();
282 sb.append("Archive (");
283 sb.append(N);
284 sb.append(" notification");
285 sb.append((N==1)?")":"s)");
286 return sb.toString();
287 }
288
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500289 public void record(StatusBarNotification nr) {
Jeff Sharkey0c1baf92013-04-03 13:08:52 -0700290 // Nuke heavy parts of notification before storing in archive
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400291 nr.getNotification().lightenPayload();
Jeff Sharkey0c1baf92013-04-03 13:08:52 -0700292
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500293 if (mBuffer.size() == BUFFER_SIZE) {
294 mBuffer.removeFirst();
295 }
296 mBuffer.addLast(nr);
297 }
298
Daniel Sandler5e62e3a2013-04-15 20:57:02 -0400299
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500300 public void clear() {
301 mBuffer.clear();
302 }
303
304 public Iterator<StatusBarNotification> descendingIterator() {
305 return mBuffer.descendingIterator();
306 }
307 public Iterator<StatusBarNotification> ascendingIterator() {
308 return mBuffer.iterator();
309 }
310 public Iterator<StatusBarNotification> filter(
311 final Iterator<StatusBarNotification> iter, final String pkg, final int userId) {
312 return new Iterator<StatusBarNotification>() {
313 StatusBarNotification mNext = findNext();
314
315 private StatusBarNotification findNext() {
316 while (iter.hasNext()) {
317 StatusBarNotification nr = iter.next();
Daniel Sandler4f91efd2013-04-25 16:38:41 -0400318 if ((pkg == null || nr.getPackageName() == pkg)
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500319 && (userId == UserHandle.USER_ALL || nr.getUserId() == userId)) {
320 return nr;
321 }
322 }
323 return null;
324 }
325
326 @Override
327 public boolean hasNext() {
328 return mNext == null;
329 }
330
331 @Override
332 public StatusBarNotification next() {
333 StatusBarNotification next = mNext;
334 if (next == null) {
335 throw new NoSuchElementException();
336 }
337 mNext = findNext();
338 return next;
339 }
340
341 @Override
342 public void remove() {
343 iter.remove();
344 }
345 };
346 }
Daniel Sandler78d0d252013-02-12 08:14:52 -0500347
348 public StatusBarNotification[] getArray(int count) {
349 if (count == 0) count = Archive.BUFFER_SIZE;
350 final StatusBarNotification[] a
351 = new StatusBarNotification[Math.min(count, mBuffer.size())];
352 Iterator<StatusBarNotification> iter = descendingIterator();
353 int i=0;
354 while (iter.hasNext() && i < count) {
355 a[i++] = iter.next();
356 }
357 return a;
358 }
359
360 public StatusBarNotification[] getArray(int count, String pkg, int userId) {
361 if (count == 0) count = Archive.BUFFER_SIZE;
362 final StatusBarNotification[] a
363 = new StatusBarNotification[Math.min(count, mBuffer.size())];
364 Iterator<StatusBarNotification> iter = filter(descendingIterator(), pkg, userId);
365 int i=0;
366 while (iter.hasNext() && i < count) {
367 a[i++] = iter.next();
368 }
369 return a;
370 }
371
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500372 }
373
374 Archive mArchive = new Archive();
375
Daniel Sandler0da673f2012-04-11 12:33:16 -0400376 private void loadBlockDb() {
377 synchronized(mBlockedPackages) {
378 if (mPolicyFile == null) {
379 File dir = new File("/data/system");
380 mPolicyFile = new AtomicFile(new File(dir, "notification_policy.xml"));
381
382 mBlockedPackages.clear();
383
384 FileInputStream infile = null;
385 try {
386 infile = mPolicyFile.openRead();
387 final XmlPullParser parser = Xml.newPullParser();
388 parser.setInput(infile, null);
389
390 int type;
391 String tag;
392 int version = DB_VERSION;
393 while ((type = parser.next()) != END_DOCUMENT) {
394 tag = parser.getName();
395 if (type == START_TAG) {
396 if (TAG_BODY.equals(tag)) {
397 version = Integer.parseInt(parser.getAttributeValue(null, ATTR_VERSION));
398 } else if (TAG_BLOCKED_PKGS.equals(tag)) {
399 while ((type = parser.next()) != END_DOCUMENT) {
400 tag = parser.getName();
401 if (TAG_PACKAGE.equals(tag)) {
402 mBlockedPackages.add(parser.getAttributeValue(null, ATTR_NAME));
403 } else if (TAG_BLOCKED_PKGS.equals(tag) && type == END_TAG) {
404 break;
405 }
406 }
407 }
408 }
409 }
410 } catch (FileNotFoundException e) {
411 // No data yet
412 } catch (IOException e) {
413 Log.wtf(TAG, "Unable to read blocked notifications database", e);
414 } catch (NumberFormatException e) {
415 Log.wtf(TAG, "Unable to parse blocked notifications database", e);
416 } catch (XmlPullParserException e) {
417 Log.wtf(TAG, "Unable to parse blocked notifications database", e);
418 } finally {
419 IoUtils.closeQuietly(infile);
420 }
421 }
422 }
423 }
424
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500425 /**
426 * Use this when you just want to know if notifications are OK for this package.
427 */
428 public boolean areNotificationsEnabledForPackage(String pkg, int uid) {
Daniel Sandler0da673f2012-04-11 12:33:16 -0400429 checkCallerIsSystem();
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500430 return (mAppOps.checkOpNoThrow(AppOpsManager.OP_POST_NOTIFICATION, uid, pkg)
431 == AppOpsManager.MODE_ALLOWED);
Daniel Sandler0da673f2012-04-11 12:33:16 -0400432 }
433
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500434 /** Use this when you actually want to post a notification or toast.
435 *
436 * Unchecked. Not exposed via Binder, but can be called in the course of enqueue*().
437 */
438 private boolean noteNotificationOp(String pkg, int uid) {
439 if (mAppOps.noteOpNoThrow(AppOpsManager.OP_POST_NOTIFICATION, uid, pkg)
440 != AppOpsManager.MODE_ALLOWED) {
441 Slog.v(TAG, "notifications are disabled by AppOps for " + pkg);
442 return false;
Daniel Sandler0da673f2012-04-11 12:33:16 -0400443 }
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500444 return true;
Daniel Sandler0da673f2012-04-11 12:33:16 -0400445 }
446
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500447 public void setNotificationsEnabledForPackage(String pkg, int uid, boolean enabled) {
Daniel Sandler0da673f2012-04-11 12:33:16 -0400448 checkCallerIsSystem();
Daniel Sandler32e698b2013-04-18 10:51:35 -0400449
450 Slog.v(TAG, (enabled?"en":"dis") + "abling notifications for " + pkg);
451
Daniel Sandler4a900acd2013-01-30 14:04:10 -0500452 mAppOps.setMode(AppOpsManager.OP_POST_NOTIFICATION, uid, pkg,
453 enabled ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
Daniel Sandler32e698b2013-04-18 10:51:35 -0400454
455 // Now, cancel any outstanding notifications that are part of a just-disabled app
456 if (ENABLE_BLOCKED_NOTIFICATIONS && !enabled) {
457 cancelAllNotificationsInt(pkg, 0, 0, true, UserHandle.getUserId(uid));
458 }
Daniel Sandler0da673f2012-04-11 12:33:16 -0400459 }
460
461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 private static String idDebugString(Context baseContext, String packageName, int id) {
463 Context c = null;
464
465 if (packageName != null) {
466 try {
467 c = baseContext.createPackageContext(packageName, 0);
468 } catch (NameNotFoundException e) {
469 c = baseContext;
470 }
471 } else {
472 c = baseContext;
473 }
474
475 String pkg;
476 String type;
477 String name;
478
479 Resources r = c.getResources();
480 try {
481 return r.getResourceName(id);
482 } catch (Resources.NotFoundException e) {
483 return "<name unknown>";
484 }
485 }
486
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700487 /**
488 * System-only API for getting a list of current (i.e. not cleared) notifications.
489 *
490 * Requires ACCESS_NOTIFICATIONS which is signature|system.
491 */
492 @Override
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500493 public StatusBarNotification[] getActiveNotifications(String callingPkg) {
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400494 // enforce() will ensure the calling uid has the correct permission
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500495 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_NOTIFICATIONS,
Daniel Sandler78d0d252013-02-12 08:14:52 -0500496 "NotificationManagerService.getActiveNotifications");
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500497
498 StatusBarNotification[] tmp = null;
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500499 int uid = Binder.getCallingUid();
500
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400501 // noteOp will check to make sure the callingPkg matches the uid
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500502 if (mAppOps.noteOpNoThrow(AppOpsManager.OP_ACCESS_NOTIFICATIONS, uid, callingPkg)
503 == AppOpsManager.MODE_ALLOWED) {
504 synchronized (mNotificationList) {
505 tmp = new StatusBarNotification[mNotificationList.size()];
506 final int N = mNotificationList.size();
507 for (int i=0; i<N; i++) {
508 tmp[i] = mNotificationList.get(i).sbn;
509 }
510 }
511 }
512 return tmp;
513 }
514
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700515 /**
516 * System-only API for getting a list of recent (cleared, no longer shown) notifications.
517 *
518 * Requires ACCESS_NOTIFICATIONS which is signature|system.
519 */
520 @Override
Daniel Sandler78d0d252013-02-12 08:14:52 -0500521 public StatusBarNotification[] getHistoricalNotifications(String callingPkg, int count) {
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400522 // enforce() will ensure the calling uid has the correct permission
Daniel Sandler78d0d252013-02-12 08:14:52 -0500523 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_NOTIFICATIONS,
524 "NotificationManagerService.getHistoricalNotifications");
525
526 StatusBarNotification[] tmp = null;
527 int uid = Binder.getCallingUid();
528
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400529 // noteOp will check to make sure the callingPkg matches the uid
Daniel Sandler78d0d252013-02-12 08:14:52 -0500530 if (mAppOps.noteOpNoThrow(AppOpsManager.OP_ACCESS_NOTIFICATIONS, uid, callingPkg)
531 == AppOpsManager.MODE_ALLOWED) {
532 synchronized (mArchive) {
533 tmp = mArchive.getArray(count);
534 }
535 }
536 return tmp;
537 }
538
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700539 /**
Chris Wrenae9bb572013-05-15 14:50:28 -0400540 * Remove notification access for any services that no longer exist.
541 */
542 void disableNonexistentListeners() {
543 int currentUser = ActivityManager.getCurrentUser();
544 String flatIn = Settings.Secure.getStringForUser(
545 mContext.getContentResolver(),
546 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
547 currentUser);
548 if (!TextUtils.isEmpty(flatIn)) {
549 if (DBG) Slog.v(TAG, "flat before: " + flatIn);
550 PackageManager pm = mContext.getPackageManager();
551 List<ResolveInfo> installedServices = pm.queryIntentServicesAsUser(
552 new Intent(NotificationListenerService.SERVICE_INTERFACE),
553 PackageManager.GET_SERVICES | PackageManager.GET_META_DATA,
554 currentUser);
555
556 Set<ComponentName> installed = new HashSet<ComponentName>();
557 for (int i = 0, count = installedServices.size(); i < count; i++) {
558 ResolveInfo resolveInfo = installedServices.get(i);
559 ServiceInfo info = resolveInfo.serviceInfo;
560
561 if (!android.Manifest.permission.BIND_NOTIFICATION_LISTENER_SERVICE.equals(
562 info.permission)) {
563 Slog.w(TAG, "Skipping notification listener service "
564 + info.packageName + "/" + info.name
565 + ": it does not require the permission "
566 + android.Manifest.permission.BIND_NOTIFICATION_LISTENER_SERVICE);
567 continue;
568 }
569 installed.add(new ComponentName(info.packageName, info.name));
570 }
571
572 String flatOut = "";
573 if (!installed.isEmpty()) {
574 String[] enabled = flatIn.split(ENABLED_NOTIFICATION_LISTENERS_SEPARATOR);
575 ArrayList<String> remaining = new ArrayList<String>(enabled.length);
576 for (int i = 0; i < enabled.length; i++) {
577 ComponentName enabledComponent = ComponentName.unflattenFromString(enabled[i]);
578 if (installed.contains(enabledComponent)) {
579 remaining.add(enabled[i]);
580 }
581 }
582 flatOut = TextUtils.join(ENABLED_NOTIFICATION_LISTENERS_SEPARATOR, remaining);
583 }
584 if (DBG) Slog.v(TAG, "flat after: " + flatOut);
585 if (!flatIn.equals(flatOut)) {
586 Settings.Secure.putStringForUser(mContext.getContentResolver(),
587 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
588 flatOut, currentUser);
589 }
590 }
591 }
592
593 /**
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700594 * Called whenever packages change, the user switches, or ENABLED_NOTIFICATION_LISTENERS
595 * is altered. (For example in response to USER_SWITCHED in our broadcast receiver)
596 */
597 void rebindListenerServices() {
John Spurlock3ec4e702013-05-16 13:42:38 -0400598 final int currentUser = ActivityManager.getCurrentUser();
599 String flat = Settings.Secure.getStringForUser(
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700600 mContext.getContentResolver(),
John Spurlock3ec4e702013-05-16 13:42:38 -0400601 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
602 currentUser);
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700603
604 NotificationListenerInfo[] toRemove = new NotificationListenerInfo[mListeners.size()];
605 final ArrayList<ComponentName> toAdd;
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700606
607 synchronized (mNotificationList) {
608 // unbind and remove all existing listeners
609 toRemove = mListeners.toArray(toRemove);
610
611 toAdd = new ArrayList<ComponentName>();
612 final HashSet<ComponentName> newEnabled = new HashSet<ComponentName>();
613 final HashSet<String> newPackages = new HashSet<String>();
614
615 // decode the list of components
616 if (flat != null) {
617 String[] components = flat.split(ENABLED_NOTIFICATION_LISTENERS_SEPARATOR);
618 for (int i=0; i<components.length; i++) {
619 final ComponentName component
620 = ComponentName.unflattenFromString(components[i]);
621 if (component != null) {
622 newEnabled.add(component);
623 toAdd.add(component);
624 newPackages.add(component.getPackageName());
625 }
626 }
627
628 mEnabledListenersForCurrentUser = newEnabled;
629 mEnabledListenerPackageNames = newPackages;
630 }
631 }
632
633 for (NotificationListenerInfo info : toRemove) {
634 final ComponentName component = info.component;
635 final int oldUser = info.userid;
636 Slog.v(TAG, "disabling notification listener for user " + oldUser + ": " + component);
637 unregisterListenerService(component, info.userid);
638 }
639
640 final int N = toAdd.size();
641 for (int i=0; i<N; i++) {
642 final ComponentName component = toAdd.get(i);
643 Slog.v(TAG, "enabling notification listener for user " + currentUser + ": "
644 + component);
645 registerListenerService(component, currentUser);
646 }
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400647 }
648
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700649 /**
650 * Register a listener binder directly with the notification manager.
651 *
652 * Only works with system callers. Apps should extend
653 * {@link android.service.notification.NotificationListenerService}.
654 */
Daniel Sandler09a247e2013-02-14 10:24:17 -0500655 @Override
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400656 public void registerListener(final INotificationListener listener,
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700657 final ComponentName component, final int userid) {
658 checkCallerIsSystem();
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400659
Daniel Sandler09a247e2013-02-14 10:24:17 -0500660 synchronized (mNotificationList) {
661 try {
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400662 NotificationListenerInfo info
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700663 = new NotificationListenerInfo(listener, component, userid, true);
Daniel Sandler09a247e2013-02-14 10:24:17 -0500664 listener.asBinder().linkToDeath(info, 0);
665 mListeners.add(info);
666 } catch (RemoteException e) {
667 // already dead
668 }
669 }
670 }
671
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700672 /**
673 * Version of registerListener that takes the name of a
674 * {@link android.service.notification.NotificationListenerService} to bind to.
675 *
676 * This is the mechanism by which third parties may subscribe to notifications.
677 */
678 private void registerListenerService(final ComponentName name, final int userid) {
679 checkCallerIsSystem();
680
681 if (DBG) Slog.v(TAG, "registerListenerService: " + name + " u=" + userid);
682
683 synchronized (mNotificationList) {
684 final String servicesBindingTag = name.toString() + "/" + userid;
685 if (mServicesBinding.contains(servicesBindingTag)) {
686 // stop registering this thing already! we're working on it
687 return;
688 }
689 mServicesBinding.add(servicesBindingTag);
690
691 final int N = mListeners.size();
692 for (int i=N-1; i>=0; i--) {
693 final NotificationListenerInfo info = mListeners.get(i);
694 if (name.equals(info.component)
695 && info.userid == userid) {
696 // cut old connections
697 if (DBG) Slog.v(TAG, " disconnecting old listener: " + info.listener);
698 mListeners.remove(i);
699 if (info.connection != null) {
700 mContext.unbindService(info.connection);
701 }
702 }
703 }
704
705 Intent intent = new Intent(NotificationListenerService.SERVICE_INTERFACE);
706 intent.setComponent(name);
707
708 intent.putExtra(Intent.EXTRA_CLIENT_LABEL,
709 com.android.internal.R.string.notification_listener_binding_label);
710 intent.putExtra(Intent.EXTRA_CLIENT_INTENT, PendingIntent.getActivity(
711 mContext, 0, new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS), 0));
712
713 try {
714 if (DBG) Slog.v(TAG, "binding: " + intent);
715 if (!mContext.bindServiceAsUser(intent,
716 new ServiceConnection() {
717 INotificationListener mListener;
718 @Override
719 public void onServiceConnected(ComponentName name, IBinder service) {
720 synchronized (mNotificationList) {
721 mServicesBinding.remove(servicesBindingTag);
722 try {
723 mListener = INotificationListener.Stub.asInterface(service);
724 NotificationListenerInfo info = new NotificationListenerInfo(
725 mListener, name, userid, this);
726 service.linkToDeath(info, 0);
727 mListeners.add(info);
728 } catch (RemoteException e) {
729 // already dead
730 }
731 }
732 }
733
734 @Override
735 public void onServiceDisconnected(ComponentName name) {
736 Slog.v(TAG, "notification listener connection lost: " + name);
737 }
738 },
739 Context.BIND_AUTO_CREATE,
740 new UserHandle(userid)))
741 {
742 mServicesBinding.remove(servicesBindingTag);
743 Slog.w(TAG, "Unable to bind listener service: " + intent);
744 return;
745 }
746 } catch (SecurityException ex) {
747 Slog.e(TAG, "Unable to bind listener service: " + intent, ex);
748 return;
749 }
750 }
751 }
752
753 /**
754 * Remove a listener binder directly
755 */
Daniel Sandler09a247e2013-02-14 10:24:17 -0500756 @Override
757 public void unregisterListener(INotificationListener listener, int userid) {
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400758 // no need to check permissions; if your listener binder is in the list,
759 // that's proof that you had permission to add it in the first place
760
Daniel Sandler09a247e2013-02-14 10:24:17 -0500761 synchronized (mNotificationList) {
762 final int N = mListeners.size();
763 for (int i=N-1; i>=0; i--) {
764 final NotificationListenerInfo info = mListeners.get(i);
765 if (info.listener == listener && info.userid == userid) {
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700766 mListeners.remove(i);
767 if (info.connection != null) {
768 mContext.unbindService(info.connection);
769 }
Daniel Sandler09a247e2013-02-14 10:24:17 -0500770 }
771 }
772 }
773 }
774
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700775 /**
776 * Remove a listener service for the given user by ComponentName
777 */
778 private void unregisterListenerService(ComponentName name, int userid) {
779 checkCallerIsSystem();
780
781 synchronized (mNotificationList) {
782 final int N = mListeners.size();
783 for (int i=N-1; i>=0; i--) {
784 final NotificationListenerInfo info = mListeners.get(i);
785 if (name.equals(info.component)
786 && info.userid == userid) {
787 mListeners.remove(i);
788 if (info.connection != null) {
Daniel Sandlerc1b49bd2013-05-07 13:53:47 -0400789 try {
790 mContext.unbindService(info.connection);
791 } catch (IllegalArgumentException ex) {
792 // something happened to the service: we think we have a connection
793 // but it's bogus.
794 Slog.e(TAG, "Listener " + name + " could not be unbound: " + ex);
795 }
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700796 }
797 }
798 }
799 }
800 }
801
802 /**
803 * asynchronously notify all listeners about a new notification
804 */
Daniel Sandler09a247e2013-02-14 10:24:17 -0500805 private void notifyPostedLocked(NotificationRecord n) {
Daniel Sandler1a497d32013-04-18 14:52:45 -0400806 // make a copy in case changes are made to the underlying Notification object
807 final StatusBarNotification sbn = n.sbn.clone();
Daniel Sandler09a247e2013-02-14 10:24:17 -0500808 for (final NotificationListenerInfo info : mListeners) {
809 mHandler.post(new Runnable() {
810 @Override
811 public void run() {
812 info.notifyPostedIfUserMatch(sbn);
813 }});
814 }
815 }
816
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700817 /**
818 * asynchronously notify all listeners about a removed notification
819 */
Daniel Sandler09a247e2013-02-14 10:24:17 -0500820 private void notifyRemovedLocked(NotificationRecord n) {
Daniel Sandler1a497d32013-04-18 14:52:45 -0400821 // make a copy in case changes are made to the underlying Notification object
822 // NOTE: this copy is lightweight: it doesn't include heavyweight parts of the notification
823 final StatusBarNotification sbn_light = n.sbn.cloneLight();
824
Daniel Sandler09a247e2013-02-14 10:24:17 -0500825 for (final NotificationListenerInfo info : mListeners) {
826 mHandler.post(new Runnable() {
827 @Override
828 public void run() {
Daniel Sandler1a497d32013-04-18 14:52:45 -0400829 info.notifyRemovedIfUserMatch(sbn_light);
Daniel Sandler09a247e2013-02-14 10:24:17 -0500830 }});
831 }
832 }
833
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700834 // -- APIs to support listeners clicking/clearing notifications --
835
836 private NotificationListenerInfo checkListenerToken(INotificationListener listener) {
837 final IBinder token = listener.asBinder();
838 final int N = mListeners.size();
839 for (int i=0; i<N; i++) {
840 final NotificationListenerInfo info = mListeners.get(i);
841 if (info.listener.asBinder() == token) return info;
842 }
843 throw new SecurityException("Disallowed call from unknown listener: " + listener);
844 }
845
846 /**
847 * Allow an INotificationListener to simulate a "clear all" operation.
848 *
849 * {@see com.android.server.StatusBarManagerService.NotificationCallbacks#onClearAllNotifications}
850 *
851 * @param token The binder for the listener, to check that the caller is allowed
852 */
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400853 public void cancelAllNotificationsFromListener(INotificationListener token) {
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700854 NotificationListenerInfo info = checkListenerToken(token);
855 long identity = Binder.clearCallingIdentity();
856 try {
857 cancelAll(info.userid);
858 } finally {
859 Binder.restoreCallingIdentity(identity);
860 }
861 }
862
863 /**
864 * Allow an INotificationListener to simulate clearing (dismissing) a single notification.
865 *
866 * {@see com.android.server.StatusBarManagerService.NotificationCallbacks#onNotificationClear}
867 *
868 * @param token The binder for the listener, to check that the caller is allowed
869 */
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400870 public void cancelNotificationFromListener(INotificationListener token, String pkg, String tag, int id) {
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700871 NotificationListenerInfo info = checkListenerToken(token);
872 long identity = Binder.clearCallingIdentity();
873 try {
874 cancelNotification(pkg, tag, id, 0,
875 Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE,
876 true,
877 info.userid);
878 } finally {
879 Binder.restoreCallingIdentity(identity);
880 }
881 }
882
Daniel Sandler25cf8ce2013-04-24 15:34:57 -0400883 /**
884 * Allow an INotificationListener to request the list of outstanding notifications seen by
885 * the current user. Useful when starting up, after which point the listener callbacks should
886 * be used.
887 *
888 * @param token The binder for the listener, to check that the caller is allowed
889 */
890 public StatusBarNotification[] getActiveNotificationsFromListener(INotificationListener token) {
891 NotificationListenerInfo info = checkListenerToken(token);
892
893 StatusBarNotification[] result = new StatusBarNotification[0];
894 ArrayList<StatusBarNotification> list = new ArrayList<StatusBarNotification>();
895 synchronized (mNotificationList) {
896 final int N = mNotificationList.size();
897 for (int i=0; i<N; i++) {
898 StatusBarNotification sbn = mNotificationList.get(i).sbn;
899 if (info.enabledAndUserMatches(sbn)) {
900 list.add(sbn);
901 }
902 }
903 }
904 return list.toArray(result);
905 }
906
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700907 // -- end of listener APIs --
908
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500909 public static final class NotificationRecord
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 {
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500911 final StatusBarNotification sbn;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 IBinder statusBarKey;
913
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500914 NotificationRecord(StatusBarNotification sbn)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 {
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500916 this.sbn = sbn;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 }
Fred Quintana6ecaff12009-09-25 14:23:13 -0700918
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400919 public Notification getNotification() { return sbn.getNotification(); }
920 public int getFlags() { return sbn.getNotification().flags; }
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500921 public int getUserId() { return sbn.getUserId(); }
922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 void dump(PrintWriter pw, String prefix, Context baseContext) {
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400924 final Notification notification = sbn.getNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 pw.println(prefix + this);
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400926 pw.println(prefix + " uid=" + sbn.getUid() + " userId=" + sbn.getUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 pw.println(prefix + " icon=0x" + Integer.toHexString(notification.icon)
Daniel Sandler4f91efd2013-04-25 16:38:41 -0400928 + " / " + idDebugString(baseContext, sbn.getPackageName(), notification.icon));
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400929 pw.println(prefix + " pri=" + notification.priority + " score=" + sbn.getScore());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 pw.println(prefix + " contentIntent=" + notification.contentIntent);
931 pw.println(prefix + " deleteIntent=" + notification.deleteIntent);
932 pw.println(prefix + " tickerText=" + notification.tickerText);
933 pw.println(prefix + " contentView=" + notification.contentView);
Daniel Sandlerf45564e2013-04-15 15:05:08 -0400934 pw.println(prefix + String.format(" defaults=0x%08x flags=0x%08x",
935 notification.defaults, notification.flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 pw.println(prefix + " sound=" + notification.sound);
937 pw.println(prefix + " vibrate=" + Arrays.toString(notification.vibrate));
Daniel Sandlerf45564e2013-04-15 15:05:08 -0400938 pw.println(prefix + String.format(" led=0x%08x onMs=%d offMs=%d",
939 notification.ledARGB, notification.ledOnMS, notification.ledOffMS));
940 if (notification.actions != null && notification.actions.length > 0) {
941 pw.println(prefix + " actions={");
942 final int N = notification.actions.length;
943 for (int i=0; i<N; i++) {
944 final Notification.Action action = notification.actions[i];
945 pw.println(String.format("%s [%d] \"%s\" -> %s",
946 prefix,
947 i,
948 action.title,
949 action.actionIntent.toString()
950 ));
951 }
952 pw.println(prefix + " }");
953 }
954 if (notification.extras != null && notification.extras.size() > 0) {
955 pw.println(prefix + " extras={");
956 for (String key : notification.extras.keySet()) {
957 pw.print(prefix + " " + key + "=");
958 Object val = notification.extras.get(key);
959 if (val == null) {
960 pw.println("null");
961 } else {
962 pw.print(val.toString());
963 if (val instanceof Bitmap) {
964 pw.print(String.format(" (%dx%d)",
965 ((Bitmap) val).getWidth(),
966 ((Bitmap) val).getHeight()));
967 } else if (val.getClass().isArray()) {
968 pw.println(" {");
969 final int N = Array.getLength(val);
970 for (int i=0; i<N; i++) {
971 if (i > 0) pw.println(",");
972 pw.print(prefix + " " + Array.get(val, i));
973 }
974 pw.print("\n" + prefix + " }");
975 }
976 pw.println();
977 }
978 }
979 pw.println(prefix + " }");
980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800982
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 @Override
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500984 public final String toString() {
985 return String.format(
986 "NotificationRecord(0x%08x: pkg=%s user=%s id=%d tag=%s score=%d: %s)",
987 System.identityHashCode(this),
Daniel Sandler4f91efd2013-04-25 16:38:41 -0400988 this.sbn.getPackageName(), this.sbn.getUser(), this.sbn.getId(), this.sbn.getTag(),
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400989 this.sbn.getScore(), this.sbn.getNotification());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 }
991 }
992
993 private static final class ToastRecord
994 {
995 final int pid;
996 final String pkg;
997 final ITransientNotification callback;
998 int duration;
999
1000 ToastRecord(int pid, String pkg, ITransientNotification callback, int duration)
1001 {
1002 this.pid = pid;
1003 this.pkg = pkg;
1004 this.callback = callback;
1005 this.duration = duration;
1006 }
1007
1008 void update(int duration) {
1009 this.duration = duration;
1010 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 void dump(PrintWriter pw, String prefix) {
1013 pw.println(prefix + this);
1014 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 @Override
1017 public final String toString()
1018 {
1019 return "ToastRecord{"
1020 + Integer.toHexString(System.identityHashCode(this))
1021 + " pkg=" + pkg
1022 + " callback=" + callback
1023 + " duration=" + duration;
1024 }
1025 }
1026
Joe Onorato089de882010-04-12 08:18:45 -07001027 private StatusBarManagerService.NotificationCallbacks mNotificationCallbacks
1028 = new StatusBarManagerService.NotificationCallbacks() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029
1030 public void onSetDisabled(int status) {
1031 synchronized (mNotificationList) {
1032 mDisabledNotifications = status;
1033 if ((mDisabledNotifications & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) {
1034 // cancel whatever's going on
1035 long identity = Binder.clearCallingIdentity();
1036 try {
Jeff Sharkey098d5802012-04-26 17:30:34 -07001037 final IRingtonePlayer player = mAudioService.getRingtonePlayer();
1038 if (player != null) {
1039 player.stopAsync();
1040 }
1041 } catch (RemoteException e) {
1042 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 Binder.restoreCallingIdentity(identity);
1044 }
1045
1046 identity = Binder.clearCallingIdentity();
1047 try {
1048 mVibrator.cancel();
Jeff Sharkey098d5802012-04-26 17:30:34 -07001049 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 Binder.restoreCallingIdentity(identity);
1051 }
1052 }
1053 }
1054 }
1055
1056 public void onClearAll() {
Dianne Hackborn41203752012-08-31 14:05:51 -07001057 // XXX to be totally correct, the caller should tell us which user
1058 // this is for.
1059 cancelAll(ActivityManager.getCurrentUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 }
1061
Fred Quintana6ecaff12009-09-25 14:23:13 -07001062 public void onNotificationClick(String pkg, String tag, int id) {
Dianne Hackborn41203752012-08-31 14:05:51 -07001063 // XXX to be totally correct, the caller should tell us which user
1064 // this is for.
Fred Quintana6ecaff12009-09-25 14:23:13 -07001065 cancelNotification(pkg, tag, id, Notification.FLAG_AUTO_CANCEL,
Dianne Hackborn41203752012-08-31 14:05:51 -07001066 Notification.FLAG_FOREGROUND_SERVICE, false,
1067 ActivityManager.getCurrentUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 }
1069
Daniel Sandler0f0b11c2010-08-04 15:54:58 -04001070 public void onNotificationClear(String pkg, String tag, int id) {
Dianne Hackborn41203752012-08-31 14:05:51 -07001071 // XXX to be totally correct, the caller should tell us which user
1072 // this is for.
Joe Onorato46439ce2010-11-19 13:56:21 -08001073 cancelNotification(pkg, tag, id, 0,
1074 Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE,
Dianne Hackborn41203752012-08-31 14:05:51 -07001075 true, ActivityManager.getCurrentUser());
Daniel Sandler0f0b11c2010-08-04 15:54:58 -04001076 }
1077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 public void onPanelRevealed() {
1079 synchronized (mNotificationList) {
1080 // sound
1081 mSoundNotification = null;
Jeff Sharkey098d5802012-04-26 17:30:34 -07001082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 long identity = Binder.clearCallingIdentity();
1084 try {
Jeff Sharkey098d5802012-04-26 17:30:34 -07001085 final IRingtonePlayer player = mAudioService.getRingtonePlayer();
1086 if (player != null) {
1087 player.stopAsync();
1088 }
1089 } catch (RemoteException e) {
1090 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 Binder.restoreCallingIdentity(identity);
1092 }
1093
1094 // vibrate
1095 mVibrateNotification = null;
1096 identity = Binder.clearCallingIdentity();
1097 try {
1098 mVibrator.cancel();
Jeff Sharkey098d5802012-04-26 17:30:34 -07001099 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 Binder.restoreCallingIdentity(identity);
1101 }
1102
1103 // light
1104 mLights.clear();
1105 mLedNotification = null;
1106 updateLightsLocked();
1107 }
1108 }
Joe Onorato005847b2010-06-04 16:08:02 -04001109
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001110 public void onNotificationError(String pkg, String tag, int id,
1111 int uid, int initialPid, String message) {
Daniel Sandlerd0a2f862010-08-03 15:29:31 -04001112 Slog.d(TAG, "onNotification error pkg=" + pkg + " tag=" + tag + " id=" + id
1113 + "; will crashApplication(uid=" + uid + ", pid=" + initialPid + ")");
Dianne Hackborn41203752012-08-31 14:05:51 -07001114 // XXX to be totally correct, the caller should tell us which user
1115 // this is for.
1116 cancelNotification(pkg, tag, id, 0, 0, false, UserHandle.getUserId(uid));
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07001117 long ident = Binder.clearCallingIdentity();
1118 try {
1119 ActivityManagerNative.getDefault().crashApplication(uid, initialPid, pkg,
1120 "Bad notification posted from package " + pkg
1121 + ": " + message);
1122 } catch (RemoteException e) {
1123 }
1124 Binder.restoreCallingIdentity(ident);
Joe Onorato005847b2010-06-04 16:08:02 -04001125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 };
1127
1128 private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
1129 @Override
1130 public void onReceive(Context context, Intent intent) {
1131 String action = intent.getAction();
1132
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001133 boolean queryRestart = false;
Chris Wrenae9bb572013-05-15 14:50:28 -04001134 boolean queryRemove = false;
Daniel Sandler26ece572012-06-01 15:38:46 -04001135 boolean packageChanged = false;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001136
Chris Wren3da73022013-05-10 14:41:21 -04001137 if (action.equals(Intent.ACTION_PACKAGE_ADDED)
Chris Wrenae9bb572013-05-15 14:50:28 -04001138 || (queryRemove=action.equals(Intent.ACTION_PACKAGE_REMOVED))
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001139 || action.equals(Intent.ACTION_PACKAGE_RESTARTED)
Daniel Sandler26ece572012-06-01 15:38:46 -04001140 || (packageChanged=action.equals(Intent.ACTION_PACKAGE_CHANGED))
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001141 || (queryRestart=action.equals(Intent.ACTION_QUERY_PACKAGE_RESTART))
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001142 || action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001143 String pkgList[] = null;
Chris Wrenae9bb572013-05-15 14:50:28 -04001144 boolean queryReplace = queryRemove &&
1145 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
1146 if (DBG) Slog.i(TAG, "queryReplace=" + queryReplace);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001147 if (action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001148 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001149 } else if (queryRestart) {
1150 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001151 } else {
1152 Uri uri = intent.getData();
1153 if (uri == null) {
1154 return;
1155 }
1156 String pkgName = uri.getSchemeSpecificPart();
1157 if (pkgName == null) {
1158 return;
1159 }
Daniel Sandler26ece572012-06-01 15:38:46 -04001160 if (packageChanged) {
1161 // We cancel notifications for packages which have just been disabled
1162 final int enabled = mContext.getPackageManager()
1163 .getApplicationEnabledSetting(pkgName);
1164 if (enabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
1165 || enabled == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
1166 return;
1167 }
1168 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001169 pkgList = new String[]{pkgName};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170 }
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001171
1172 boolean anyListenersInvolved = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001173 if (pkgList != null && (pkgList.length > 0)) {
1174 for (String pkgName : pkgList) {
Dianne Hackborn41203752012-08-31 14:05:51 -07001175 cancelAllNotificationsInt(pkgName, 0, 0, !queryRestart,
1176 UserHandle.USER_ALL);
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001177 if (mEnabledListenerPackageNames.contains(pkgName)) {
1178 anyListenersInvolved = true;
1179 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 }
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001182
1183 if (anyListenersInvolved) {
Chris Wrenae9bb572013-05-15 14:50:28 -04001184 // if we're not replacing a package, clean up orphaned bits
1185 if (!queryReplace) {
1186 disableNonexistentListeners();
1187 }
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001188 // make sure we're still bound to any of our
1189 // listeners who may have just upgraded
1190 rebindListenerServices();
1191 }
Mike Lockwood63b5ad92011-08-30 09:55:30 -04001192 } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
1193 // Keep track of screen on/off state, but do not turn off the notification light
1194 // until user passes through the lock screen or views the notification.
1195 mScreenOn = true;
1196 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
1197 mScreenOn = false;
Daniel Sandlere96ffb12010-03-11 13:38:06 -05001198 } else if (action.equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
Mike Lockwood63b5ad92011-08-30 09:55:30 -04001199 mInCall = (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
1200 TelephonyManager.EXTRA_STATE_OFFHOOK));
Daniel Sandlere96ffb12010-03-11 13:38:06 -05001201 updateNotificationPulse();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001202 } else if (action.equals(Intent.ACTION_USER_STOPPED)) {
1203 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
1204 if (userHandle >= 0) {
Dianne Hackborn41203752012-08-31 14:05:51 -07001205 cancelAllNotificationsInt(null, 0, 0, true, userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001206 }
Mike Lockwood63b5ad92011-08-30 09:55:30 -04001207 } else if (action.equals(Intent.ACTION_USER_PRESENT)) {
1208 // turn off LED when user passes through lock screen
1209 mNotificationLight.turnOff();
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001210 } else if (action.equals(Intent.ACTION_USER_SWITCHED)) {
1211 // reload per-user settings
1212 mSettingsObserver.update(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 }
1214 }
1215 };
1216
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001217 class SettingsObserver extends ContentObserver {
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001218 private final Uri NOTIFICATION_LIGHT_PULSE_URI
1219 = Settings.System.getUriFor(Settings.System.NOTIFICATION_LIGHT_PULSE);
1220
1221 private final Uri ENABLED_NOTIFICATION_LISTENERS_URI
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001222 = Settings.Secure.getUriFor(Settings.Secure.ENABLED_NOTIFICATION_LISTENERS);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001223
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001224 SettingsObserver(Handler handler) {
1225 super(handler);
1226 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001227
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001228 void observe() {
1229 ContentResolver resolver = mContext.getContentResolver();
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001230 resolver.registerContentObserver(NOTIFICATION_LIGHT_PULSE_URI,
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001231 false, this, UserHandle.USER_ALL);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001232 resolver.registerContentObserver(ENABLED_NOTIFICATION_LISTENERS_URI,
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001233 false, this, UserHandle.USER_ALL);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001234 update(null);
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001235 }
1236
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001237 @Override public void onChange(boolean selfChange, Uri uri) {
1238 update(uri);
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001239 }
1240
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001241 public void update(Uri uri) {
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001242 ContentResolver resolver = mContext.getContentResolver();
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001243 if (uri == null || NOTIFICATION_LIGHT_PULSE_URI.equals(uri)) {
1244 boolean pulseEnabled = Settings.System.getInt(resolver,
1245 Settings.System.NOTIFICATION_LIGHT_PULSE, 0) != 0;
1246 if (mNotificationPulseEnabled != pulseEnabled) {
1247 mNotificationPulseEnabled = pulseEnabled;
1248 updateNotificationPulse();
1249 }
1250 }
1251 if (uri == null || ENABLED_NOTIFICATION_LISTENERS_URI.equals(uri)) {
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001252 rebindListenerServices();
Mike Lockwoodc22404a2009-12-02 11:15:02 -05001253 }
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001254 }
1255 }
Mike Lockwoodc22404a2009-12-02 11:15:02 -05001256
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001257 private SettingsObserver mSettingsObserver;
1258
Daniel Sandleredbb3802012-11-13 20:49:47 -08001259 static long[] getLongArray(Resources r, int resid, int maxlen, long[] def) {
1260 int[] ar = r.getIntArray(resid);
1261 if (ar == null) {
1262 return def;
1263 }
1264 final int len = ar.length > maxlen ? maxlen : ar.length;
1265 long[] out = new long[len];
1266 for (int i=0; i<len; i++) {
1267 out[i] = ar[i];
1268 }
1269 return out;
1270 }
1271
Joe Onorato089de882010-04-12 08:18:45 -07001272 NotificationManagerService(Context context, StatusBarManagerService statusBar,
Mike Lockwood3a322132009-11-24 00:30:52 -05001273 LightsService lights)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 {
1275 super();
1276 mContext = context;
Jeff Brownc2346132012-04-13 01:55:38 -07001277 mVibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 mAm = ActivityManagerNative.getDefault();
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001279 mUserManager = (UserManager)context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 mToastQueue = new ArrayList<ToastRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 mHandler = new WorkerHandler();
San Mehat3ee13172010-02-04 20:54:43 -08001282
Daniel Sandler4a900acd2013-01-30 14:04:10 -05001283 mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
1284
1285 importOldBlockDb();
Daniel Sandler0da673f2012-04-11 12:33:16 -04001286
Joe Onorato089de882010-04-12 08:18:45 -07001287 mStatusBar = statusBar;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 statusBar.setNotificationCallbacks(mNotificationCallbacks);
1289
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001290 mNotificationLight = lights.getLight(LightsService.LIGHT_ID_NOTIFICATIONS);
1291 mAttentionLight = lights.getLight(LightsService.LIGHT_ID_ATTENTION);
1292
Mike Lockwood670f9322010-01-20 12:13:36 -05001293 Resources resources = mContext.getResources();
1294 mDefaultNotificationColor = resources.getColor(
1295 com.android.internal.R.color.config_defaultNotificationColor);
1296 mDefaultNotificationLedOn = resources.getInteger(
1297 com.android.internal.R.integer.config_defaultNotificationLedOn);
1298 mDefaultNotificationLedOff = resources.getInteger(
1299 com.android.internal.R.integer.config_defaultNotificationLedOff);
1300
Daniel Sandleredbb3802012-11-13 20:49:47 -08001301 mDefaultVibrationPattern = getLongArray(resources,
1302 com.android.internal.R.array.config_defaultNotificationVibePattern,
1303 VIBRATE_PATTERN_MAXLEN,
1304 DEFAULT_VIBRATE_PATTERN);
1305
1306 mFallbackVibrationPattern = getLongArray(resources,
1307 com.android.internal.R.array.config_notificationFallbackVibePattern,
1308 VIBRATE_PATTERN_MAXLEN,
1309 DEFAULT_VIBRATE_PATTERN);
1310
Joe Onorato39f5b6a2009-07-23 12:29:19 -04001311 // Don't start allowing notifications until the setup wizard has run once.
1312 // After that, including subsequent boots, init with notifications turned on.
1313 // This works on the first boot because the setup wizard will toggle this
1314 // flag at least once and we'll go back to 0 after that.
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001315 if (0 == Settings.Global.getInt(mContext.getContentResolver(),
1316 Settings.Global.DEVICE_PROVISIONED, 0)) {
Joe Onorato39f5b6a2009-07-23 12:29:19 -04001317 mDisabledNotifications = StatusBarManager.DISABLE_NOTIFICATION_ALERTS;
1318 }
1319
Mike Lockwood35e16bf2010-11-30 19:53:36 -05001320 // register for various Intents
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 IntentFilter filter = new IntentFilter();
Mike Lockwoodc22404a2009-12-02 11:15:02 -05001322 filter.addAction(Intent.ACTION_SCREEN_ON);
1323 filter.addAction(Intent.ACTION_SCREEN_OFF);
Daniel Sandlere96ffb12010-03-11 13:38:06 -05001324 filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
Mike Lockwood63b5ad92011-08-30 09:55:30 -04001325 filter.addAction(Intent.ACTION_USER_PRESENT);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001326 filter.addAction(Intent.ACTION_USER_STOPPED);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001327 filter.addAction(Intent.ACTION_USER_SWITCHED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 mContext.registerReceiver(mIntentReceiver, filter);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001329 IntentFilter pkgFilter = new IntentFilter();
Chris Wren3da73022013-05-10 14:41:21 -04001330 pkgFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001331 pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
Daniel Sandleraac0eb02011-08-06 22:51:56 -04001332 pkgFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001333 pkgFilter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
1334 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
1335 pkgFilter.addDataScheme("package");
1336 mContext.registerReceiver(mIntentReceiver, pkgFilter);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001337 IntentFilter sdFilter = new IntentFilter(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001338 mContext.registerReceiver(mIntentReceiver, sdFilter);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001339
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001340 mSettingsObserver = new SettingsObserver(mHandler);
1341 mSettingsObserver.observe();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 }
1343
Daniel Sandler4a900acd2013-01-30 14:04:10 -05001344 /**
1345 * Read the old XML-based app block database and import those blockages into the AppOps system.
1346 */
1347 private void importOldBlockDb() {
1348 loadBlockDb();
1349
1350 PackageManager pm = mContext.getPackageManager();
1351 for (String pkg : mBlockedPackages) {
1352 PackageInfo info = null;
1353 try {
1354 info = pm.getPackageInfo(pkg, 0);
1355 setNotificationsEnabledForPackage(pkg, info.applicationInfo.uid, false);
1356 } catch (NameNotFoundException e) {
1357 // forget you
1358 }
1359 }
1360 mBlockedPackages.clear();
1361 if (mPolicyFile != null) {
1362 mPolicyFile.delete();
1363 }
1364 }
1365
Joe Onorato30275482009-07-08 17:09:14 -07001366 void systemReady() {
Jeff Sharkey098d5802012-04-26 17:30:34 -07001367 mAudioService = IAudioService.Stub.asInterface(
1368 ServiceManager.getService(Context.AUDIO_SERVICE));
1369
Joe Onorato30275482009-07-08 17:09:14 -07001370 // no beeping until we're basically done booting
1371 mSystemReady = true;
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001372
1373 // make sure our listener services are properly bound
1374 rebindListenerServices();
Joe Onorato30275482009-07-08 17:09:14 -07001375 }
1376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 // Toasts
1378 // ============================================================================
1379 public void enqueueToast(String pkg, ITransientNotification callback, int duration)
1380 {
Daniel Sandlera7035902010-03-30 15:45:31 -04001381 if (DBG) Slog.i(TAG, "enqueueToast pkg=" + pkg + " callback=" + callback + " duration=" + duration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382
1383 if (pkg == null || callback == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001384 Slog.e(TAG, "Not doing toast. pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 return ;
1386 }
1387
Daniel Sandler0da673f2012-04-11 12:33:16 -04001388 final boolean isSystemToast = ("android".equals(pkg));
1389
Daniel Sandler4a900acd2013-01-30 14:04:10 -05001390 if (ENABLE_BLOCKED_TOASTS && !noteNotificationOp(pkg, Binder.getCallingUid())) {
1391 if (!isSystemToast) {
1392 Slog.e(TAG, "Suppressing toast from package " + pkg + " by user request.");
1393 return;
1394 }
Daniel Sandler0da673f2012-04-11 12:33:16 -04001395 }
1396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 synchronized (mToastQueue) {
1398 int callingPid = Binder.getCallingPid();
1399 long callingId = Binder.clearCallingIdentity();
1400 try {
1401 ToastRecord record;
1402 int index = indexOfToastLocked(pkg, callback);
1403 // If it's already in the queue, we update it in place, we don't
1404 // move it to the end of the queue.
1405 if (index >= 0) {
1406 record = mToastQueue.get(index);
1407 record.update(duration);
1408 } else {
Vairavan Srinivasanf9eb06c2011-01-21 18:08:36 -08001409 // Limit the number of toasts that any given package except the android
1410 // package can enqueue. Prevents DOS attacks and deals with leaks.
Daniel Sandler0da673f2012-04-11 12:33:16 -04001411 if (!isSystemToast) {
Vairavan Srinivasanf9eb06c2011-01-21 18:08:36 -08001412 int count = 0;
1413 final int N = mToastQueue.size();
1414 for (int i=0; i<N; i++) {
1415 final ToastRecord r = mToastQueue.get(i);
1416 if (r.pkg.equals(pkg)) {
1417 count++;
1418 if (count >= MAX_PACKAGE_NOTIFICATIONS) {
1419 Slog.e(TAG, "Package has already posted " + count
1420 + " toasts. Not showing more. Package=" + pkg);
1421 return;
1422 }
1423 }
1424 }
1425 }
1426
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 record = new ToastRecord(callingPid, pkg, callback, duration);
1428 mToastQueue.add(record);
1429 index = mToastQueue.size() - 1;
1430 keepProcessAliveLocked(callingPid);
1431 }
1432 // If it's at index 0, it's the current toast. It doesn't matter if it's
1433 // new or just been updated. Call back and tell it to show itself.
1434 // If the callback fails, this will remove it from the list, so don't
1435 // assume that it's valid after this.
1436 if (index == 0) {
1437 showNextToastLocked();
1438 }
1439 } finally {
1440 Binder.restoreCallingIdentity(callingId);
1441 }
1442 }
1443 }
1444
1445 public void cancelToast(String pkg, ITransientNotification callback) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001446 Slog.i(TAG, "cancelToast pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447
1448 if (pkg == null || callback == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001449 Slog.e(TAG, "Not cancelling notification. pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 return ;
1451 }
1452
1453 synchronized (mToastQueue) {
1454 long callingId = Binder.clearCallingIdentity();
1455 try {
1456 int index = indexOfToastLocked(pkg, callback);
1457 if (index >= 0) {
1458 cancelToastLocked(index);
1459 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001460 Slog.w(TAG, "Toast already cancelled. pkg=" + pkg + " callback=" + callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001461 }
1462 } finally {
1463 Binder.restoreCallingIdentity(callingId);
1464 }
1465 }
1466 }
1467
1468 private void showNextToastLocked() {
1469 ToastRecord record = mToastQueue.get(0);
1470 while (record != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001471 if (DBG) Slog.d(TAG, "Show pkg=" + record.pkg + " callback=" + record.callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 try {
1473 record.callback.show();
1474 scheduleTimeoutLocked(record, false);
1475 return;
1476 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001477 Slog.w(TAG, "Object died trying to show notification " + record.callback
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001478 + " in package " + record.pkg);
1479 // remove it from the list and let the process die
1480 int index = mToastQueue.indexOf(record);
1481 if (index >= 0) {
1482 mToastQueue.remove(index);
1483 }
1484 keepProcessAliveLocked(record.pid);
1485 if (mToastQueue.size() > 0) {
1486 record = mToastQueue.get(0);
1487 } else {
1488 record = null;
1489 }
1490 }
1491 }
1492 }
1493
1494 private void cancelToastLocked(int index) {
1495 ToastRecord record = mToastQueue.get(index);
1496 try {
1497 record.callback.hide();
1498 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001499 Slog.w(TAG, "Object died trying to hide notification " + record.callback
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 + " in package " + record.pkg);
1501 // don't worry about this, we're about to remove it from
1502 // the list anyway
1503 }
1504 mToastQueue.remove(index);
1505 keepProcessAliveLocked(record.pid);
1506 if (mToastQueue.size() > 0) {
1507 // Show the next one. If the callback fails, this will remove
1508 // it from the list, so don't assume that the list hasn't changed
1509 // after this point.
1510 showNextToastLocked();
1511 }
1512 }
1513
1514 private void scheduleTimeoutLocked(ToastRecord r, boolean immediate)
1515 {
1516 Message m = Message.obtain(mHandler, MESSAGE_TIMEOUT, r);
1517 long delay = immediate ? 0 : (r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY);
1518 mHandler.removeCallbacksAndMessages(r);
1519 mHandler.sendMessageDelayed(m, delay);
1520 }
1521
1522 private void handleTimeout(ToastRecord record)
1523 {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001524 if (DBG) Slog.d(TAG, "Timeout pkg=" + record.pkg + " callback=" + record.callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 synchronized (mToastQueue) {
1526 int index = indexOfToastLocked(record.pkg, record.callback);
1527 if (index >= 0) {
1528 cancelToastLocked(index);
1529 }
1530 }
1531 }
1532
1533 // lock on mToastQueue
1534 private int indexOfToastLocked(String pkg, ITransientNotification callback)
1535 {
1536 IBinder cbak = callback.asBinder();
1537 ArrayList<ToastRecord> list = mToastQueue;
1538 int len = list.size();
1539 for (int i=0; i<len; i++) {
1540 ToastRecord r = list.get(i);
1541 if (r.pkg.equals(pkg) && r.callback.asBinder() == cbak) {
1542 return i;
1543 }
1544 }
1545 return -1;
1546 }
1547
1548 // lock on mToastQueue
1549 private void keepProcessAliveLocked(int pid)
1550 {
1551 int toastCount = 0; // toasts from this pid
1552 ArrayList<ToastRecord> list = mToastQueue;
1553 int N = list.size();
1554 for (int i=0; i<N; i++) {
1555 ToastRecord r = list.get(i);
1556 if (r.pid == pid) {
1557 toastCount++;
1558 }
1559 }
1560 try {
1561 mAm.setProcessForeground(mForegroundToken, pid, toastCount > 0);
1562 } catch (RemoteException e) {
1563 // Shouldn't happen.
1564 }
1565 }
1566
1567 private final class WorkerHandler extends Handler
1568 {
1569 @Override
1570 public void handleMessage(Message msg)
1571 {
1572 switch (msg.what)
1573 {
1574 case MESSAGE_TIMEOUT:
1575 handleTimeout((ToastRecord)msg.obj);
1576 break;
1577 }
1578 }
1579 }
1580
1581
1582 // Notifications
1583 // ============================================================================
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001584 public void enqueueNotificationWithTag(String pkg, String basePkg, String tag, int id,
1585 Notification notification, int[] idOut, int userId)
Fred Quintana6ecaff12009-09-25 14:23:13 -07001586 {
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001587 enqueueNotificationInternal(pkg, basePkg, Binder.getCallingUid(), Binder.getCallingPid(),
Dianne Hackborn41203752012-08-31 14:05:51 -07001588 tag, id, notification, idOut, userId);
Daniel Sandlerd0a2f862010-08-03 15:29:31 -04001589 }
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001590
1591 private final static int clamp(int x, int low, int high) {
1592 return (x < low) ? low : ((x > high) ? high : x);
Daniel Sandlere40451a2011-02-03 14:51:35 -05001593 }
1594
Daniel Sandlerd0a2f862010-08-03 15:29:31 -04001595 // Not exposed via Binder; for system use only (otherwise malicious apps could spoof the
1596 // uid/pid of another application)
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001597 public void enqueueNotificationInternal(String pkg, String basePkg, int callingUid,
1598 int callingPid, String tag, int id, Notification notification, int[] idOut, int userId)
Daniel Sandlerd0a2f862010-08-03 15:29:31 -04001599 {
Daniel Sandler0da673f2012-04-11 12:33:16 -04001600 if (DBG) {
1601 Slog.v(TAG, "enqueueNotificationInternal: pkg=" + pkg + " id=" + id + " notification=" + notification);
1602 }
1603 checkCallerIsSystemOrSameApp(pkg);
1604 final boolean isSystemNotification = ("android".equals(pkg));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001605
Dianne Hackborn41203752012-08-31 14:05:51 -07001606 userId = ActivityManager.handleIncomingUser(callingPid,
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07001607 callingUid, userId, true, false, "enqueueNotification", pkg);
Jeff Sharkey65c4a2b2012-09-25 17:22:27 -07001608 final UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001609
Joe Onoratobd73d012010-06-04 11:44:54 -07001610 // Limit the number of notifications that any given package except the android
1611 // package can enqueue. Prevents DOS attacks and deals with leaks.
Daniel Sandler0da673f2012-04-11 12:33:16 -04001612 if (!isSystemNotification) {
Joe Onoratobd73d012010-06-04 11:44:54 -07001613 synchronized (mNotificationList) {
1614 int count = 0;
1615 final int N = mNotificationList.size();
1616 for (int i=0; i<N; i++) {
1617 final NotificationRecord r = mNotificationList.get(i);
Daniel Sandler4f91efd2013-04-25 16:38:41 -04001618 if (r.sbn.getPackageName().equals(pkg) && r.sbn.getUserId() == userId) {
Joe Onoratobd73d012010-06-04 11:44:54 -07001619 count++;
1620 if (count >= MAX_PACKAGE_NOTIFICATIONS) {
1621 Slog.e(TAG, "Package has already posted " + count
1622 + " notifications. Not showing more. package=" + pkg);
1623 return;
1624 }
1625 }
1626 }
1627 }
1628 }
1629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 // This conditional is a dirty hack to limit the logging done on
1631 // behalf of the download manager without affecting other apps.
1632 if (!pkg.equals("com.android.providers.downloads")
1633 || Log.isLoggable("DownloadManager", Log.VERBOSE)) {
Daniel Sandler321e9c52012-10-12 10:59:26 -07001634 EventLog.writeEvent(EventLogTags.NOTIFICATION_ENQUEUE, pkg, id, tag, userId,
Daniel Sandlerb64cb882011-11-29 23:48:29 -05001635 notification.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 }
1637
1638 if (pkg == null || notification == null) {
1639 throw new IllegalArgumentException("null not allowed: pkg=" + pkg
1640 + " id=" + id + " notification=" + notification);
1641 }
1642 if (notification.icon != 0) {
1643 if (notification.contentView == null) {
1644 throw new IllegalArgumentException("contentView required: pkg=" + pkg
1645 + " id=" + id + " notification=" + notification);
1646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 }
1648
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001649 // === Scoring ===
Daniel Sandler0da673f2012-04-11 12:33:16 -04001650
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001651 // 0. Sanitize inputs
1652 notification.priority = clamp(notification.priority, Notification.PRIORITY_MIN, Notification.PRIORITY_MAX);
1653 // Migrate notification flags to scores
1654 if (0 != (notification.flags & Notification.FLAG_HIGH_PRIORITY)) {
1655 if (notification.priority < Notification.PRIORITY_MAX) notification.priority = Notification.PRIORITY_MAX;
Daniel Sandler49a2ad12012-03-28 15:46:39 -04001656 } else if (SCORE_ONGOING_HIGHER && 0 != (notification.flags & Notification.FLAG_ONGOING_EVENT)) {
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001657 if (notification.priority < Notification.PRIORITY_HIGH) notification.priority = Notification.PRIORITY_HIGH;
1658 }
Daniel Sandler0da673f2012-04-11 12:33:16 -04001659
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001660 // 1. initial score: buckets of 10, around the app
Daniel Sandler0da673f2012-04-11 12:33:16 -04001661 int score = notification.priority * NOTIFICATION_PRIORITY_MULTIPLIER; //[-20..20]
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001662
Daniel Sandler0da673f2012-04-11 12:33:16 -04001663 // 2. Consult external heuristics (TBD)
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001664
Daniel Sandler0da673f2012-04-11 12:33:16 -04001665 // 3. Apply local rules
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001666
1667 // blocked apps
Daniel Sandler4a900acd2013-01-30 14:04:10 -05001668 if (ENABLE_BLOCKED_NOTIFICATIONS && !noteNotificationOp(pkg, callingUid)) {
1669 if (!isSystemNotification) {
1670 score = JUNK_SCORE;
1671 Slog.e(TAG, "Suppressing notification from package " + pkg + " by user request.");
1672 }
Daniel Sandler0da673f2012-04-11 12:33:16 -04001673 }
1674
1675 if (DBG) {
1676 Slog.v(TAG, "Assigned score=" + score + " to " + notification);
1677 }
1678
1679 if (score < SCORE_DISPLAY_THRESHOLD) {
1680 // Notification will be blocked because the score is too low.
1681 return;
Daniel Sandler2561b0b2012-02-13 21:04:12 -05001682 }
1683
Daniel Sandler526fa0e2012-12-04 14:51:50 -05001684 // Should this notification make noise, vibe, or use the LED?
1685 final boolean canInterrupt = (score >= SCORE_INTERRUPTION_THRESHOLD);
1686
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 synchronized (mNotificationList) {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001688 final StatusBarNotification n = new StatusBarNotification(
1689 pkg, id, tag, callingUid, callingPid, score, notification, user);
1690 NotificationRecord r = new NotificationRecord(n);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 NotificationRecord old = null;
1692
Dianne Hackborn41203752012-08-31 14:05:51 -07001693 int index = indexOfNotificationLocked(pkg, tag, id, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 if (index < 0) {
1695 mNotificationList.add(r);
1696 } else {
1697 old = mNotificationList.remove(index);
1698 mNotificationList.add(index, r);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001699 // Make sure we don't lose the foreground service state.
1700 if (old != null) {
1701 notification.flags |=
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001702 old.getNotification().flags&Notification.FLAG_FOREGROUND_SERVICE;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001705
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001706 // Ensure if this is a foreground service that the proper additional
1707 // flags are set.
1708 if ((notification.flags&Notification.FLAG_FOREGROUND_SERVICE) != 0) {
1709 notification.flags |= Notification.FLAG_ONGOING_EVENT
1710 | Notification.FLAG_NO_CLEAR;
1711 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001712
Svetoslav Ganovc31ed392012-10-10 14:58:28 -07001713 final int currentUser;
1714 final long token = Binder.clearCallingIdentity();
1715 try {
1716 currentUser = ActivityManager.getCurrentUser();
1717 } finally {
1718 Binder.restoreCallingIdentity(token);
1719 }
1720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 if (notification.icon != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 if (old != null && old.statusBarKey != null) {
1723 r.statusBarKey = old.statusBarKey;
1724 long identity = Binder.clearCallingIdentity();
1725 try {
Joe Onorato18e69df2010-05-17 22:26:12 -07001726 mStatusBar.updateNotification(r.statusBarKey, n);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 }
1728 finally {
1729 Binder.restoreCallingIdentity(identity);
1730 }
1731 } else {
1732 long identity = Binder.clearCallingIdentity();
1733 try {
Joe Onorato18e69df2010-05-17 22:26:12 -07001734 r.statusBarKey = mStatusBar.addNotification(n);
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04001735 if ((n.getNotification().flags & Notification.FLAG_SHOW_LIGHTS) != 0
Daniel Sandler526fa0e2012-12-04 14:51:50 -05001736 && canInterrupt) {
Mike Lockwoodece18ef2012-02-13 20:42:19 -08001737 mAttentionLight.pulse();
1738 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 }
1740 finally {
1741 Binder.restoreCallingIdentity(identity);
1742 }
1743 }
Svetoslav Ganovc31ed392012-10-10 14:58:28 -07001744 // Send accessibility events only for the current user.
1745 if (currentUser == userId) {
1746 sendAccessibilityEvent(notification, pkg);
1747 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001748
Daniel Sandler09a247e2013-02-14 10:24:17 -05001749 notifyPostedLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 } else {
Daniel Sandlere40451a2011-02-03 14:51:35 -05001751 Slog.e(TAG, "Ignoring notification with icon==0: " + notification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 if (old != null && old.statusBarKey != null) {
1753 long identity = Binder.clearCallingIdentity();
1754 try {
Joe Onorato0cbda992010-05-02 16:28:15 -07001755 mStatusBar.removeNotification(old.statusBarKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 }
1757 finally {
1758 Binder.restoreCallingIdentity(identity);
1759 }
Daniel Sandler09a247e2013-02-14 10:24:17 -05001760
1761 notifyRemovedLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001763 return; // do not play sounds, show lights, etc. for invalid notifications
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 }
1765
1766 // If we're not supposed to beep, vibrate, etc. then don't.
1767 if (((mDisabledNotifications & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) == 0)
1768 && (!(old != null
Joe Onorato30275482009-07-08 17:09:14 -07001769 && (notification.flags & Notification.FLAG_ONLY_ALERT_ONCE) != 0 ))
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001770 && (r.getUserId() == UserHandle.USER_ALL ||
1771 (r.getUserId() == userId && r.getUserId() == currentUser))
Daniel Sandler526fa0e2012-12-04 14:51:50 -05001772 && canInterrupt
Joe Onorato30275482009-07-08 17:09:14 -07001773 && mSystemReady) {
Eric Laurent524dc042009-11-27 05:07:55 -08001774
1775 final AudioManager audioManager = (AudioManager) mContext
1776 .getSystemService(Context.AUDIO_SERVICE);
Daniel Sandlerd4d2de22012-11-14 11:25:46 -08001777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 // sound
Daniel Sandler31475232013-04-17 00:17:22 -04001779
1780 // should we use the default notification sound? (indicated either by DEFAULT_SOUND
1781 // or because notification.sound is pointing at Settings.System.NOTIFICATION_SOUND)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 final boolean useDefaultSound =
Daniel Sandler31475232013-04-17 00:17:22 -04001783 (notification.defaults & Notification.DEFAULT_SOUND) != 0
1784 || Settings.System.DEFAULT_NOTIFICATION_URI.equals(notification.sound);
Daniel Sandlerd4d2de22012-11-14 11:25:46 -08001785
1786 Uri soundUri = null;
1787 boolean hasValidSound = false;
1788
1789 if (useDefaultSound) {
1790 soundUri = Settings.System.DEFAULT_NOTIFICATION_URI;
1791
1792 // check to see if the default notification sound is silent
1793 ContentResolver resolver = mContext.getContentResolver();
1794 hasValidSound = Settings.System.getString(resolver,
1795 Settings.System.NOTIFICATION_SOUND) != null;
1796 } else if (notification.sound != null) {
1797 soundUri = notification.sound;
1798 hasValidSound = (soundUri != null);
1799 }
1800
1801 if (hasValidSound) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 boolean looping = (notification.flags & Notification.FLAG_INSISTENT) != 0;
1803 int audioStreamType;
1804 if (notification.audioStreamType >= 0) {
1805 audioStreamType = notification.audioStreamType;
1806 } else {
1807 audioStreamType = DEFAULT_STREAM_TYPE;
1808 }
1809 mSoundNotification = r;
Eric Laurent524dc042009-11-27 05:07:55 -08001810 // do not play notifications if stream volume is 0
Jean-Michel Trivid6770542012-10-10 12:03:41 -07001811 // (typically because ringer mode is silent) or if speech recognition is active.
1812 if ((audioManager.getStreamVolume(audioStreamType) != 0)
1813 && !audioManager.isSpeechRecognitionActive()) {
Jeff Sharkey098d5802012-04-26 17:30:34 -07001814 final long identity = Binder.clearCallingIdentity();
Eric Laurent524dc042009-11-27 05:07:55 -08001815 try {
Jeff Sharkey098d5802012-04-26 17:30:34 -07001816 final IRingtonePlayer player = mAudioService.getRingtonePlayer();
1817 if (player != null) {
Daniel Sandlerd4d2de22012-11-14 11:25:46 -08001818 player.playAsync(soundUri, user, looping, audioStreamType);
Jeff Sharkey098d5802012-04-26 17:30:34 -07001819 }
1820 } catch (RemoteException e) {
1821 } finally {
Eric Laurent524dc042009-11-27 05:07:55 -08001822 Binder.restoreCallingIdentity(identity);
1823 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 }
1825 }
1826
1827 // vibrate
Daniel Sandleredbb3802012-11-13 20:49:47 -08001828 // Does the notification want to specify its own vibration?
1829 final boolean hasCustomVibrate = notification.vibrate != null;
1830
David Agnew71789e12012-11-09 23:03:26 -05001831 // new in 4.2: if there was supposed to be a sound and we're in vibrate mode,
Daniel Sandler4a7a9b92012-11-20 12:59:41 -05001832 // and no other vibration is specified, we fall back to vibration
David Agnew71789e12012-11-09 23:03:26 -05001833 final boolean convertSoundToVibration =
Daniel Sandleredbb3802012-11-13 20:49:47 -08001834 !hasCustomVibrate
Daniel Sandlerd4d2de22012-11-14 11:25:46 -08001835 && hasValidSound
David Agnew71789e12012-11-09 23:03:26 -05001836 && (audioManager.getRingerMode() == AudioManager.RINGER_MODE_VIBRATE);
1837
Daniel Sandler4a7a9b92012-11-20 12:59:41 -05001838 // The DEFAULT_VIBRATE flag trumps any custom vibration AND the fallback.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 final boolean useDefaultVibrate =
Daniel Sandleredbb3802012-11-13 20:49:47 -08001840 (notification.defaults & Notification.DEFAULT_VIBRATE) != 0;
David Agnew71789e12012-11-09 23:03:26 -05001841
Daniel Sandleredbb3802012-11-13 20:49:47 -08001842 if ((useDefaultVibrate || convertSoundToVibration || hasCustomVibrate)
Eric Laurentbffc3d12012-05-07 17:43:49 -07001843 && !(audioManager.getRingerMode() == AudioManager.RINGER_MODE_SILENT)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 mVibrateNotification = r;
1845
Daniel Sandleredbb3802012-11-13 20:49:47 -08001846 if (useDefaultVibrate || convertSoundToVibration) {
1847 // Escalate privileges so we can use the vibrator even if the notifying app
1848 // does not have the VIBRATE permission.
1849 long identity = Binder.clearCallingIdentity();
1850 try {
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04001851 mVibrator.vibrate(r.sbn.getUid(), r.sbn.getBasePkg(),
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001852 useDefaultVibrate ? mDefaultVibrationPattern
1853 : mFallbackVibrationPattern,
Daniel Sandleredbb3802012-11-13 20:49:47 -08001854 ((notification.flags & Notification.FLAG_INSISTENT) != 0) ? 0: -1);
1855 } finally {
1856 Binder.restoreCallingIdentity(identity);
1857 }
1858 } else if (notification.vibrate.length > 1) {
1859 // If you want your own vibration pattern, you need the VIBRATE permission
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04001860 mVibrator.vibrate(r.sbn.getUid(), r.sbn.getBasePkg(), notification.vibrate,
Daniel Sandleredbb3802012-11-13 20:49:47 -08001861 ((notification.flags & Notification.FLAG_INSISTENT) != 0) ? 0: -1);
1862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863 }
1864 }
1865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 // light
1867 // the most recent thing gets the light
1868 mLights.remove(old);
1869 if (mLedNotification == old) {
1870 mLedNotification = null;
1871 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08001872 //Slog.i(TAG, "notification.lights="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 // + ((old.notification.lights.flags & Notification.FLAG_SHOW_LIGHTS) != 0));
Daniel Sandler526fa0e2012-12-04 14:51:50 -05001874 if ((notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0
1875 && canInterrupt) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 mLights.add(r);
1877 updateLightsLocked();
1878 } else {
1879 if (old != null
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001880 && ((old.getFlags() & Notification.FLAG_SHOW_LIGHTS) != 0)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 updateLightsLocked();
1882 }
1883 }
1884 }
1885
1886 idOut[0] = id;
1887 }
1888
Joe Onorato30275482009-07-08 17:09:14 -07001889 private void sendAccessibilityEvent(Notification notification, CharSequence packageName) {
svetoslavganov75986cf2009-05-14 22:28:01 -07001890 AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
1891 if (!manager.isEnabled()) {
1892 return;
1893 }
1894
1895 AccessibilityEvent event =
1896 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED);
1897 event.setPackageName(packageName);
1898 event.setClassName(Notification.class.getName());
1899 event.setParcelableData(notification);
1900 CharSequence tickerText = notification.tickerText;
1901 if (!TextUtils.isEmpty(tickerText)) {
1902 event.getText().add(tickerText);
1903 }
1904
1905 manager.sendAccessibilityEvent(event);
1906 }
1907
Joe Onorato46439ce2010-11-19 13:56:21 -08001908 private void cancelNotificationLocked(NotificationRecord r, boolean sendDelete) {
1909 // tell the app
1910 if (sendDelete) {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001911 if (r.getNotification().deleteIntent != null) {
Joe Onorato46439ce2010-11-19 13:56:21 -08001912 try {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001913 r.getNotification().deleteIntent.send();
Joe Onorato46439ce2010-11-19 13:56:21 -08001914 } catch (PendingIntent.CanceledException ex) {
1915 // do nothing - there's no relevant way to recover, and
1916 // no reason to let this propagate
Daniel Sandler4f91efd2013-04-25 16:38:41 -04001917 Slog.w(TAG, "canceled PendingIntent for " + r.sbn.getPackageName(), ex);
Joe Onorato46439ce2010-11-19 13:56:21 -08001918 }
1919 }
1920 }
1921
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001922 // status bar
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001923 if (r.getNotification().icon != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 long identity = Binder.clearCallingIdentity();
1925 try {
Joe Onorato0cbda992010-05-02 16:28:15 -07001926 mStatusBar.removeNotification(r.statusBarKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 }
1928 finally {
1929 Binder.restoreCallingIdentity(identity);
1930 }
1931 r.statusBarKey = null;
Daniel Sandler09a247e2013-02-14 10:24:17 -05001932 notifyRemovedLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 }
1934
1935 // sound
1936 if (mSoundNotification == r) {
1937 mSoundNotification = null;
Jeff Sharkey098d5802012-04-26 17:30:34 -07001938 final long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 try {
Jeff Sharkey098d5802012-04-26 17:30:34 -07001940 final IRingtonePlayer player = mAudioService.getRingtonePlayer();
1941 if (player != null) {
1942 player.stopAsync();
1943 }
1944 } catch (RemoteException e) {
1945 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 Binder.restoreCallingIdentity(identity);
1947 }
1948 }
1949
1950 // vibrate
1951 if (mVibrateNotification == r) {
1952 mVibrateNotification = null;
1953 long identity = Binder.clearCallingIdentity();
1954 try {
1955 mVibrator.cancel();
1956 }
1957 finally {
1958 Binder.restoreCallingIdentity(identity);
1959 }
1960 }
1961
1962 // light
1963 mLights.remove(r);
1964 if (mLedNotification == r) {
1965 mLedNotification = null;
1966 }
Daniel Sandler23d7c702013-03-07 16:32:06 -05001967
1968 // Save it for users of getHistoricalNotifications()
1969 mArchive.record(r.sbn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 }
1971
1972 /**
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001973 * Cancels a notification ONLY if it has all of the {@code mustHaveFlags}
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001974 * and none of the {@code mustNotHaveFlags}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 */
Fred Quintana6ecaff12009-09-25 14:23:13 -07001976 private void cancelNotification(String pkg, String tag, int id, int mustHaveFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07001977 int mustNotHaveFlags, boolean sendDelete, int userId) {
Daniel Sandler321e9c52012-10-12 10:59:26 -07001978 EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL, pkg, id, tag, userId,
Daniel Sandlerb64cb882011-11-29 23:48:29 -05001979 mustHaveFlags, mustNotHaveFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980
1981 synchronized (mNotificationList) {
Dianne Hackborn41203752012-08-31 14:05:51 -07001982 int index = indexOfNotificationLocked(pkg, tag, id, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001983 if (index >= 0) {
Fred Quintana6ecaff12009-09-25 14:23:13 -07001984 NotificationRecord r = mNotificationList.get(index);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001985
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001986 if ((r.getNotification().flags & mustHaveFlags) != mustHaveFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 return;
1988 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001989 if ((r.getNotification().flags & mustNotHaveFlags) != 0) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07001990 return;
1991 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001992
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 mNotificationList.remove(index);
1994
Joe Onorato46439ce2010-11-19 13:56:21 -08001995 cancelNotificationLocked(r, sendDelete);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 updateLightsLocked();
1997 }
1998 }
1999 }
2000
2001 /**
Daniel Sandler321e9c52012-10-12 10:59:26 -07002002 * Determine whether the userId applies to the notification in question, either because
2003 * they match exactly, or one of them is USER_ALL (which is treated as a wildcard).
2004 */
2005 private boolean notificationMatchesUserId(NotificationRecord r, int userId) {
2006 return
2007 // looking for USER_ALL notifications? match everything
2008 userId == UserHandle.USER_ALL
2009 // a notification sent to USER_ALL matches any query
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002010 || r.getUserId() == UserHandle.USER_ALL
Daniel Sandler321e9c52012-10-12 10:59:26 -07002011 // an exact user match
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002012 || r.getUserId() == userId;
Daniel Sandler321e9c52012-10-12 10:59:26 -07002013 }
2014
2015 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 * Cancels all notifications from a given package that have all of the
2017 * {@code mustHaveFlags}.
2018 */
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002019 boolean cancelAllNotificationsInt(String pkg, int mustHaveFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002020 int mustNotHaveFlags, boolean doit, int userId) {
Daniel Sandler321e9c52012-10-12 10:59:26 -07002021 EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL_ALL, pkg, userId,
2022 mustHaveFlags, mustNotHaveFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023
2024 synchronized (mNotificationList) {
2025 final int N = mNotificationList.size();
2026 boolean canceledSomething = false;
2027 for (int i = N-1; i >= 0; --i) {
2028 NotificationRecord r = mNotificationList.get(i);
Daniel Sandler321e9c52012-10-12 10:59:26 -07002029 if (!notificationMatchesUserId(r, userId)) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002030 continue;
2031 }
Amith Yamasani5ec00e92012-11-07 16:58:30 -08002032 // Don't remove notifications to all, if there's no package name specified
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002033 if (r.getUserId() == UserHandle.USER_ALL && pkg == null) {
Amith Yamasani5ec00e92012-11-07 16:58:30 -08002034 continue;
2035 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002036 if ((r.getFlags() & mustHaveFlags) != mustHaveFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 continue;
2038 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002039 if ((r.getFlags() & mustNotHaveFlags) != 0) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002040 continue;
2041 }
Daniel Sandler4f91efd2013-04-25 16:38:41 -04002042 if (pkg != null && !r.sbn.getPackageName().equals(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002043 continue;
2044 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002045 canceledSomething = true;
2046 if (!doit) {
2047 return true;
2048 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002049 mNotificationList.remove(i);
Joe Onorato46439ce2010-11-19 13:56:21 -08002050 cancelNotificationLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 }
2052 if (canceledSomething) {
2053 updateLightsLocked();
2054 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002055 return canceledSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 }
2057 }
2058
Dianne Hackborn41203752012-08-31 14:05:51 -07002059 public void cancelNotificationWithTag(String pkg, String tag, int id, int userId) {
Daniel Sandler0da673f2012-04-11 12:33:16 -04002060 checkCallerIsSystemOrSameApp(pkg);
Dianne Hackborn41203752012-08-31 14:05:51 -07002061 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07002062 Binder.getCallingUid(), userId, true, false, "cancelNotificationWithTag", pkg);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002063 // Don't allow client applications to cancel foreground service notis.
Fred Quintana6ecaff12009-09-25 14:23:13 -07002064 cancelNotification(pkg, tag, id, 0,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002065 Binder.getCallingUid() == Process.SYSTEM_UID
Dianne Hackborn41203752012-08-31 14:05:51 -07002066 ? 0 : Notification.FLAG_FOREGROUND_SERVICE, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002067 }
2068
Dianne Hackborn41203752012-08-31 14:05:51 -07002069 public void cancelAllNotifications(String pkg, int userId) {
Daniel Sandler0da673f2012-04-11 12:33:16 -04002070 checkCallerIsSystemOrSameApp(pkg);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002071
Dianne Hackborn41203752012-08-31 14:05:51 -07002072 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
Amith Yamasani2c7ebea2012-10-30 15:28:27 -07002073 Binder.getCallingUid(), userId, true, false, "cancelAllNotifications", pkg);
Dianne Hackborn41203752012-08-31 14:05:51 -07002074
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002075 // Calling from user space, don't allow the canceling of actively
2076 // running foreground services.
Dianne Hackborn41203752012-08-31 14:05:51 -07002077 cancelAllNotificationsInt(pkg, 0, Notification.FLAG_FOREGROUND_SERVICE, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078 }
2079
Daniel Sandler0da673f2012-04-11 12:33:16 -04002080 void checkCallerIsSystem() {
2081 int uid = Binder.getCallingUid();
Dianne Hackborn0c380492012-08-20 17:23:30 -07002082 if (UserHandle.getAppId(uid) == Process.SYSTEM_UID || uid == 0) {
Daniel Sandler0da673f2012-04-11 12:33:16 -04002083 return;
2084 }
2085 throw new SecurityException("Disallowed call for uid " + uid);
2086 }
2087
2088 void checkCallerIsSystemOrSameApp(String pkg) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002089 int uid = Binder.getCallingUid();
Dianne Hackborn0c380492012-08-20 17:23:30 -07002090 if (UserHandle.getAppId(uid) == Process.SYSTEM_UID || uid == 0) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002091 return;
2092 }
2093 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07002094 ApplicationInfo ai = AppGlobals.getPackageManager().getApplicationInfo(
2095 pkg, 0, UserHandle.getCallingUserId());
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002096 if (!UserHandle.isSameApp(ai.uid, uid)) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002097 throw new SecurityException("Calling uid " + uid + " gave package"
2098 + pkg + " which is owned by uid " + ai.uid);
2099 }
Amith Yamasanif203aee2012-08-29 18:41:53 -07002100 } catch (RemoteException re) {
2101 throw new SecurityException("Unknown package " + pkg + "\n" + re);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002102 }
2103 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002104
Dianne Hackborn41203752012-08-31 14:05:51 -07002105 void cancelAll(int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106 synchronized (mNotificationList) {
2107 final int N = mNotificationList.size();
2108 for (int i=N-1; i>=0; i--) {
2109 NotificationRecord r = mNotificationList.get(i);
2110
Daniel Sandler321e9c52012-10-12 10:59:26 -07002111 if (!notificationMatchesUserId(r, userId)) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002112 continue;
2113 }
2114
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002115 if ((r.getFlags() & (Notification.FLAG_ONGOING_EVENT
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002116 | Notification.FLAG_NO_CLEAR)) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 mNotificationList.remove(i);
Joe Onorato46439ce2010-11-19 13:56:21 -08002118 cancelNotificationLocked(r, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002119 }
2120 }
2121
2122 updateLightsLocked();
2123 }
2124 }
2125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 // lock on mNotificationList
2127 private void updateLightsLocked()
2128 {
The Android Open Source Project10592532009-03-18 17:39:46 -07002129 // handle notification lights
2130 if (mLedNotification == null) {
2131 // get next notification, if any
2132 int n = mLights.size();
2133 if (n > 0) {
2134 mLedNotification = mLights.get(n-1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 }
2136 }
Mike Lockwoodc22404a2009-12-02 11:15:02 -05002137
Mike Lockwood63b5ad92011-08-30 09:55:30 -04002138 // Don't flash while we are in a call or screen is on
2139 if (mLedNotification == null || mInCall || mScreenOn) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002140 mNotificationLight.turnOff();
The Android Open Source Project10592532009-03-18 17:39:46 -07002141 } else {
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04002142 final Notification ledno = mLedNotification.sbn.getNotification();
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002143 int ledARGB = ledno.ledARGB;
2144 int ledOnMS = ledno.ledOnMS;
2145 int ledOffMS = ledno.ledOffMS;
2146 if ((ledno.defaults & Notification.DEFAULT_LIGHTS) != 0) {
Mike Lockwood670f9322010-01-20 12:13:36 -05002147 ledARGB = mDefaultNotificationColor;
2148 ledOnMS = mDefaultNotificationLedOn;
2149 ledOffMS = mDefaultNotificationLedOff;
2150 }
2151 if (mNotificationPulseEnabled) {
2152 // pulse repeatedly
2153 mNotificationLight.setFlashing(ledARGB, LightsService.LIGHT_FLASH_TIMED,
2154 ledOnMS, ledOffMS);
Mike Lockwood670f9322010-01-20 12:13:36 -05002155 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002157 }
2158
2159 // lock on mNotificationList
Dianne Hackborn41203752012-08-31 14:05:51 -07002160 private int indexOfNotificationLocked(String pkg, String tag, int id, int userId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 {
2162 ArrayList<NotificationRecord> list = mNotificationList;
2163 final int len = list.size();
2164 for (int i=0; i<len; i++) {
2165 NotificationRecord r = list.get(i);
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04002166 if (!notificationMatchesUserId(r, userId) || r.sbn.getId() != id) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002167 continue;
2168 }
Fred Quintana6ecaff12009-09-25 14:23:13 -07002169 if (tag == null) {
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04002170 if (r.sbn.getTag() != null) {
Fred Quintana6ecaff12009-09-25 14:23:13 -07002171 continue;
2172 }
2173 } else {
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04002174 if (!tag.equals(r.sbn.getTag())) {
Fred Quintana6ecaff12009-09-25 14:23:13 -07002175 continue;
2176 }
2177 }
Daniel Sandler4f91efd2013-04-25 16:38:41 -04002178 if (r.sbn.getPackageName().equals(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179 return i;
2180 }
2181 }
2182 return -1;
2183 }
2184
Mike Lockwoodc22404a2009-12-02 11:15:02 -05002185 private void updateNotificationPulse() {
2186 synchronized (mNotificationList) {
2187 updateLightsLocked();
2188 }
2189 }
2190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002191 // ======================================================================
2192 @Override
2193 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2194 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2195 != PackageManager.PERMISSION_GRANTED) {
2196 pw.println("Permission Denial: can't dump NotificationManager from from pid="
2197 + Binder.getCallingPid()
2198 + ", uid=" + Binder.getCallingUid());
2199 return;
2200 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 pw.println("Current Notification Manager state:");
2203
Daniel Sandler5feceeb2013-03-22 18:29:23 -07002204 pw.println(" Listeners (" + mEnabledListenersForCurrentUser.size()
2205 + ") enabled for current user:");
2206 for (ComponentName cmpt : mEnabledListenersForCurrentUser) {
2207 pw.println(" " + cmpt);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04002208 }
Daniel Sandler4b749ef2013-03-18 21:53:04 -04002209
Daniel Sandler5feceeb2013-03-22 18:29:23 -07002210 pw.println(" Live listeners (" + mListeners.size() + "):");
Daniel Sandler4b749ef2013-03-18 21:53:04 -04002211 for (NotificationListenerInfo info : mListeners) {
Daniel Sandler5feceeb2013-03-22 18:29:23 -07002212 pw.println(" " + info.component
2213 + " (user " + info.userid + "): " + info.listener
2214 + (info.isSystem?" SYSTEM":""));
Daniel Sandler4b749ef2013-03-18 21:53:04 -04002215 }
2216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002217 int N;
2218
2219 synchronized (mToastQueue) {
2220 N = mToastQueue.size();
2221 if (N > 0) {
2222 pw.println(" Toast Queue:");
2223 for (int i=0; i<N; i++) {
2224 mToastQueue.get(i).dump(pw, " ");
2225 }
2226 pw.println(" ");
2227 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002229 }
2230
2231 synchronized (mNotificationList) {
2232 N = mNotificationList.size();
2233 if (N > 0) {
2234 pw.println(" Notification List:");
2235 for (int i=0; i<N; i++) {
2236 mNotificationList.get(i).dump(pw, " ", mContext);
2237 }
2238 pw.println(" ");
2239 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002241 N = mLights.size();
2242 if (N > 0) {
2243 pw.println(" Lights List:");
2244 for (int i=0; i<N; i++) {
Daniel Sandlerf45564e2013-04-15 15:05:08 -04002245 pw.println(" " + mLights.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002246 }
2247 pw.println(" ");
2248 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 pw.println(" mSoundNotification=" + mSoundNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002251 pw.println(" mVibrateNotification=" + mVibrateNotification);
Joe Onorato39f5b6a2009-07-23 12:29:19 -04002252 pw.println(" mDisabledNotifications=0x" + Integer.toHexString(mDisabledNotifications));
2253 pw.println(" mSystemReady=" + mSystemReady);
Daniel Sandler5e62e3a2013-04-15 20:57:02 -04002254 pw.println(" mArchive=" + mArchive.toString());
2255 Iterator<StatusBarNotification> iter = mArchive.descendingIterator();
2256 int i=0;
2257 while (iter.hasNext()) {
2258 pw.println(" " + iter.next());
2259 if (++i >= 5) {
2260 if (iter.hasNext()) pw.println(" ...");
2261 break;
2262 }
2263 }
2264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002265 }
2266 }
2267}