blob: db4cf31d7dadfd021a982ab549092da77d412be4 [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
Adam Lesinski182f73f2013-12-05 16:48:06 -080017package com.android.server.notification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080018
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 Sandler4a900ac2013-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 Sandler4a900ac2013-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.IRingtonePlayer;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.os.Binder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.os.IBinder;
55import android.os.Message;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070056import android.os.Process;
svetoslavganov75986cf2009-05-14 22:28:01 -070057import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070058import android.os.UserHandle;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.os.Vibrator;
60import android.provider.Settings;
Daniel Sandler5feceeb2013-03-22 18:29:23 -070061import android.service.notification.INotificationListener;
62import android.service.notification.NotificationListenerService;
63import android.service.notification.StatusBarNotification;
Daniel Sandlere96ffb12010-03-11 13:38:06 -050064import android.telephony.TelephonyManager;
svetoslavganov75986cf2009-05-14 22:28:01 -070065import android.text.TextUtils;
Dianne Hackborn39606a02012-07-31 17:54:35 -070066import android.util.AtomicFile;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.util.EventLog;
68import android.util.Log;
Andy Stadler110988c2010-12-03 14:29:16 -080069import android.util.Slog;
Daniel Sandler0da673f2012-04-11 12:33:16 -040070import android.util.Xml;
svetoslavganov75986cf2009-05-14 22:28:01 -070071import android.view.accessibility.AccessibilityEvent;
72import android.view.accessibility.AccessibilityManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.widget.Toast;
74
Scott Greenwald9a05b312013-06-28 00:37:54 -040075import com.android.internal.R;
76
77import com.android.internal.notification.NotificationScorer;
Adam Lesinski182f73f2013-12-05 16:48:06 -080078import com.android.server.EventLogTags;
79import com.android.server.statusbar.StatusBarManagerInternal;
80import com.android.server.SystemService;
81import com.android.server.lights.Light;
82import com.android.server.lights.LightsManager;
83
Jeff Sharkey098d5802012-04-26 17:30:34 -070084import org.xmlpull.v1.XmlPullParser;
85import org.xmlpull.v1.XmlPullParserException;
Jeff Sharkey098d5802012-04-26 17:30:34 -070086
Daniel Sandler0da673f2012-04-11 12:33:16 -040087import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import java.io.FileDescriptor;
Daniel Sandler0da673f2012-04-11 12:33:16 -040089import java.io.FileInputStream;
90import java.io.FileNotFoundException;
Daniel Sandler0da673f2012-04-11 12:33:16 -040091import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import java.io.PrintWriter;
Daniel Sandlerf45564e2013-04-15 15:05:08 -040093import java.lang.reflect.Array;
Daniel Sandlerfde19b12013-01-17 00:21:05 -050094import java.util.ArrayDeque;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import java.util.ArrayList;
96import java.util.Arrays;
Daniel Sandler0da673f2012-04-11 12:33:16 -040097import java.util.HashSet;
Daniel Sandlerfde19b12013-01-17 00:21:05 -050098import java.util.Iterator;
Chris Wrenae9bb572013-05-15 14:50:28 -040099import java.util.List;
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500100import java.util.NoSuchElementException;
Chris Wrenae9bb572013-05-15 14:50:28 -0400101import java.util.Set;
Daniel Sandler0da673f2012-04-11 12:33:16 -0400102
103import libcore.io.IoUtils;
104
Daniel Sandlerd0a2f862010-08-03 15:29:31 -0400105/** {@hide} */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800106public class NotificationManagerService extends SystemService {
107 static final String TAG = "NotificationService";
108 static final boolean DBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109
Adam Lesinski182f73f2013-12-05 16:48:06 -0800110 static final int MAX_PACKAGE_NOTIFICATIONS = 50;
Joe Onoratobd73d012010-06-04 11:44:54 -0700111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 // message codes
Adam Lesinski182f73f2013-12-05 16:48:06 -0800113 static final int MESSAGE_TIMEOUT = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114
Adam Lesinski182f73f2013-12-05 16:48:06 -0800115 static final int LONG_DELAY = 3500; // 3.5 seconds
116 static final int SHORT_DELAY = 2000; // 2 seconds
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800117
Adam Lesinski182f73f2013-12-05 16:48:06 -0800118 static final long[] DEFAULT_VIBRATE_PATTERN = {0, 250, 250, 250};
119 static final int VIBRATE_PATTERN_MAXLEN = 8 * 2 + 1; // up to eight bumps
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120
Adam Lesinski182f73f2013-12-05 16:48:06 -0800121 static final int DEFAULT_STREAM_TYPE = AudioManager.STREAM_NOTIFICATION;
122 static final boolean SCORE_ONGOING_HIGHER = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123
Adam Lesinski182f73f2013-12-05 16:48:06 -0800124 static final int JUNK_SCORE = -1000;
125 static final int NOTIFICATION_PRIORITY_MULTIPLIER = 10;
126 static final int SCORE_DISPLAY_THRESHOLD = Notification.PRIORITY_MIN * NOTIFICATION_PRIORITY_MULTIPLIER;
Daniel Sandler0da673f2012-04-11 12:33:16 -0400127
Daniel Sandler526fa0e2012-12-04 14:51:50 -0500128 // Notifications with scores below this will not interrupt the user, either via LED or
129 // sound or vibration
Adam Lesinski182f73f2013-12-05 16:48:06 -0800130 static final int SCORE_INTERRUPTION_THRESHOLD =
Daniel Sandler526fa0e2012-12-04 14:51:50 -0500131 Notification.PRIORITY_LOW * NOTIFICATION_PRIORITY_MULTIPLIER;
132
Adam Lesinski182f73f2013-12-05 16:48:06 -0800133 static final boolean ENABLE_BLOCKED_NOTIFICATIONS = true;
134 static final boolean ENABLE_BLOCKED_TOASTS = true;
Daniel Sandler0da673f2012-04-11 12:33:16 -0400135
Adam Lesinski182f73f2013-12-05 16:48:06 -0800136 static final String ENABLED_NOTIFICATION_LISTENERS_SEPARATOR = ":";
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700137
Adam Lesinski182f73f2013-12-05 16:48:06 -0800138 private IActivityManager mAm;
139 AudioManager mAudioManager;
140 StatusBarManagerInternal mStatusBar;
141 Vibrator mVibrator;
142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143 final IBinder mForegroundToken = new Binder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144 private WorkerHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145
Adam Lesinski182f73f2013-12-05 16:48:06 -0800146 private Light mNotificationLight;
147 Light mAttentionLight;
Mike Lockwood670f9322010-01-20 12:13:36 -0500148 private int mDefaultNotificationColor;
149 private int mDefaultNotificationLedOn;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800150
Mike Lockwood670f9322010-01-20 12:13:36 -0500151 private int mDefaultNotificationLedOff;
Daniel Sandleredbb3802012-11-13 20:49:47 -0800152 private long[] mDefaultVibrationPattern;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800153
Daniel Sandleredbb3802012-11-13 20:49:47 -0800154 private long[] mFallbackVibrationPattern;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800155 boolean mSystemReady;
Daniel Sandleredbb3802012-11-13 20:49:47 -0800156
Adam Lesinski182f73f2013-12-05 16:48:06 -0800157 int mDisabledNotifications;
158 NotificationRecord mSoundNotification;
159 NotificationRecord mVibrateNotification;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160
Mike Lockwoodc22404a2009-12-02 11:15:02 -0500161 // for enabling and disabling notification pulse behavior
Mike Lockwood63b5ad92011-08-30 09:55:30 -0400162 private boolean mScreenOn = true;
Daniel Sandlere96ffb12010-03-11 13:38:06 -0500163 private boolean mInCall = false;
Mike Lockwoodc22404a2009-12-02 11:15:02 -0500164 private boolean mNotificationPulseEnabled;
165
Daniel Sandler09a247e2013-02-14 10:24:17 -0500166 // used as a mutex for access to all active notifications & listeners
Adam Lesinski182f73f2013-12-05 16:48:06 -0800167 final ArrayList<NotificationRecord> mNotificationList =
Fred Quintana6ecaff12009-09-25 14:23:13 -0700168 new ArrayList<NotificationRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169
Adam Lesinski182f73f2013-12-05 16:48:06 -0800170 final ArrayList<ToastRecord> mToastQueue = new ArrayList<ToastRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171
Adam Lesinski182f73f2013-12-05 16:48:06 -0800172 ArrayList<NotificationRecord> mLights = new ArrayList<NotificationRecord>();
173 NotificationRecord mLedNotification;
svetoslavganov75986cf2009-05-14 22:28:01 -0700174
Adam Lesinski182f73f2013-12-05 16:48:06 -0800175 private AppOpsManager mAppOps;
Daniel Sandler4a900ac2013-01-30 14:04:10 -0500176
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700177 // contains connections to all connected listeners, including app services
178 // and system listeners
179 private ArrayList<NotificationListenerInfo> mListeners
180 = new ArrayList<NotificationListenerInfo>();
181 // things that will be put into mListeners as soon as they're ready
182 private ArrayList<String> mServicesBinding = new ArrayList<String>();
183 // lists the component names of all enabled (and therefore connected) listener
184 // app services for the current user only
185 private HashSet<ComponentName> mEnabledListenersForCurrentUser
186 = new HashSet<ComponentName>();
187 // Just the packages from mEnabledListenersForCurrentUser
188 private HashSet<String> mEnabledListenerPackageNames = new HashSet<String>();
Daniel Sandler09a247e2013-02-14 10:24:17 -0500189
Daniel Sandler0da673f2012-04-11 12:33:16 -0400190 // Notification control database. For now just contains disabled packages.
191 private AtomicFile mPolicyFile;
192 private HashSet<String> mBlockedPackages = new HashSet<String>();
193
194 private static final int DB_VERSION = 1;
195
196 private static final String TAG_BODY = "notification-policy";
197 private static final String ATTR_VERSION = "version";
198
199 private static final String TAG_BLOCKED_PKGS = "blocked-packages";
200 private static final String TAG_PACKAGE = "package";
201 private static final String ATTR_NAME = "name";
202
Adam Lesinski182f73f2013-12-05 16:48:06 -0800203 final ArrayList<NotificationScorer> mScorers = new ArrayList<NotificationScorer>();
Scott Greenwald9a05b312013-06-28 00:37:54 -0400204
Adam Lesinski182f73f2013-12-05 16:48:06 -0800205 private class NotificationListenerInfo implements IBinder.DeathRecipient {
Daniel Sandler09a247e2013-02-14 10:24:17 -0500206 INotificationListener listener;
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700207 ComponentName component;
Daniel Sandler09a247e2013-02-14 10:24:17 -0500208 int userid;
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400209 boolean isSystem;
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700210 ServiceConnection connection;
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400211
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700212 public NotificationListenerInfo(INotificationListener listener, ComponentName component,
213 int userid, boolean isSystem) {
Daniel Sandler09a247e2013-02-14 10:24:17 -0500214 this.listener = listener;
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700215 this.component = component;
Daniel Sandler09a247e2013-02-14 10:24:17 -0500216 this.userid = userid;
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400217 this.isSystem = isSystem;
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700218 this.connection = null;
219 }
220
221 public NotificationListenerInfo(INotificationListener listener, ComponentName component,
222 int userid, ServiceConnection connection) {
223 this.listener = listener;
224 this.component = component;
225 this.userid = userid;
226 this.isSystem = false;
227 this.connection = connection;
Daniel Sandler09a247e2013-02-14 10:24:17 -0500228 }
229
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400230 boolean enabledAndUserMatches(StatusBarNotification sbn) {
231 final int nid = sbn.getUserId();
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700232 if (!isEnabledForCurrentUser()) {
233 return false;
234 }
Daniel Sandler21ca44d2013-03-07 13:58:00 -0500235 if (this.userid == UserHandle.USER_ALL) return true;
Daniel Sandler21ca44d2013-03-07 13:58:00 -0500236 return (nid == UserHandle.USER_ALL || nid == this.userid);
237 }
238
Daniel Sandler09a247e2013-02-14 10:24:17 -0500239 public void notifyPostedIfUserMatch(StatusBarNotification sbn) {
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700240 if (!enabledAndUserMatches(sbn)) {
241 return;
242 }
Daniel Sandler09a247e2013-02-14 10:24:17 -0500243 try {
244 listener.onNotificationPosted(sbn);
245 } catch (RemoteException ex) {
Daniel Sandler1a497d32013-04-18 14:52:45 -0400246 Log.e(TAG, "unable to notify listener (posted): " + listener, ex);
Daniel Sandler09a247e2013-02-14 10:24:17 -0500247 }
248 }
249
250 public void notifyRemovedIfUserMatch(StatusBarNotification sbn) {
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400251 if (!enabledAndUserMatches(sbn)) return;
Daniel Sandler09a247e2013-02-14 10:24:17 -0500252 try {
253 listener.onNotificationRemoved(sbn);
254 } catch (RemoteException ex) {
Daniel Sandler1a497d32013-04-18 14:52:45 -0400255 Log.e(TAG, "unable to notify listener (removed): " + listener, ex);
Daniel Sandler09a247e2013-02-14 10:24:17 -0500256 }
257 }
258
259 @Override
260 public void binderDied() {
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700261 if (connection == null) {
262 // This is not a service; it won't be recreated. We can give up this connection.
Adam Lesinski182f73f2013-12-05 16:48:06 -0800263 unregisterListenerImpl(this.listener, this.userid);
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700264 }
Daniel Sandler09a247e2013-02-14 10:24:17 -0500265 }
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400266
267 /** convenience method for looking in mEnabledListenersForCurrentUser */
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700268 public boolean isEnabledForCurrentUser() {
269 if (this.isSystem) return true;
270 if (this.connection == null) return false;
271 return mEnabledListenersForCurrentUser.contains(this.component);
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400272 }
Daniel Sandler09a247e2013-02-14 10:24:17 -0500273 }
274
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500275 private static class Archive {
Daniel Sandler5e62e3a2013-04-15 20:57:02 -0400276 static final int BUFFER_SIZE = 250;
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500277 ArrayDeque<StatusBarNotification> mBuffer = new ArrayDeque<StatusBarNotification>(BUFFER_SIZE);
278
279 public Archive() {
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500280 }
Jeff Sharkey0c1baf92013-04-03 13:08:52 -0700281
Daniel Sandler5e62e3a2013-04-15 20:57:02 -0400282 public String toString() {
283 final StringBuilder sb = new StringBuilder();
284 final int N = mBuffer.size();
285 sb.append("Archive (");
286 sb.append(N);
287 sb.append(" notification");
288 sb.append((N==1)?")":"s)");
289 return sb.toString();
290 }
291
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500292 public void record(StatusBarNotification nr) {
293 if (mBuffer.size() == BUFFER_SIZE) {
294 mBuffer.removeFirst();
295 }
Daniel Sandler26b81d52013-05-20 20:56:43 -0400296
297 // We don't want to store the heavy bits of the notification in the archive,
298 // but other clients in the system process might be using the object, so we
299 // store a (lightened) copy.
300 mBuffer.addLast(nr.cloneLight());
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500301 }
302
Daniel Sandler5e62e3a2013-04-15 20:57:02 -0400303
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500304 public void clear() {
305 mBuffer.clear();
306 }
307
308 public Iterator<StatusBarNotification> descendingIterator() {
309 return mBuffer.descendingIterator();
310 }
311 public Iterator<StatusBarNotification> ascendingIterator() {
312 return mBuffer.iterator();
313 }
314 public Iterator<StatusBarNotification> filter(
315 final Iterator<StatusBarNotification> iter, final String pkg, final int userId) {
316 return new Iterator<StatusBarNotification>() {
317 StatusBarNotification mNext = findNext();
318
319 private StatusBarNotification findNext() {
320 while (iter.hasNext()) {
321 StatusBarNotification nr = iter.next();
Daniel Sandler4f91efd2013-04-25 16:38:41 -0400322 if ((pkg == null || nr.getPackageName() == pkg)
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500323 && (userId == UserHandle.USER_ALL || nr.getUserId() == userId)) {
324 return nr;
325 }
326 }
327 return null;
328 }
329
330 @Override
331 public boolean hasNext() {
332 return mNext == null;
333 }
334
335 @Override
336 public StatusBarNotification next() {
337 StatusBarNotification next = mNext;
338 if (next == null) {
339 throw new NoSuchElementException();
340 }
341 mNext = findNext();
342 return next;
343 }
344
345 @Override
346 public void remove() {
347 iter.remove();
348 }
349 };
350 }
Daniel Sandler78d0d252013-02-12 08:14:52 -0500351
352 public StatusBarNotification[] getArray(int count) {
353 if (count == 0) count = Archive.BUFFER_SIZE;
354 final StatusBarNotification[] a
355 = new StatusBarNotification[Math.min(count, mBuffer.size())];
356 Iterator<StatusBarNotification> iter = descendingIterator();
357 int i=0;
358 while (iter.hasNext() && i < count) {
359 a[i++] = iter.next();
360 }
361 return a;
362 }
363
364 public StatusBarNotification[] getArray(int count, String pkg, int userId) {
365 if (count == 0) count = Archive.BUFFER_SIZE;
366 final StatusBarNotification[] a
367 = new StatusBarNotification[Math.min(count, mBuffer.size())];
368 Iterator<StatusBarNotification> iter = filter(descendingIterator(), pkg, userId);
369 int i=0;
370 while (iter.hasNext() && i < count) {
371 a[i++] = iter.next();
372 }
373 return a;
374 }
375
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500376 }
377
378 Archive mArchive = new Archive();
379
Daniel Sandler0da673f2012-04-11 12:33:16 -0400380 private void loadBlockDb() {
381 synchronized(mBlockedPackages) {
382 if (mPolicyFile == null) {
383 File dir = new File("/data/system");
384 mPolicyFile = new AtomicFile(new File(dir, "notification_policy.xml"));
385
386 mBlockedPackages.clear();
387
388 FileInputStream infile = null;
389 try {
390 infile = mPolicyFile.openRead();
391 final XmlPullParser parser = Xml.newPullParser();
392 parser.setInput(infile, null);
393
394 int type;
395 String tag;
396 int version = DB_VERSION;
397 while ((type = parser.next()) != END_DOCUMENT) {
398 tag = parser.getName();
399 if (type == START_TAG) {
400 if (TAG_BODY.equals(tag)) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800401 version = Integer.parseInt(
402 parser.getAttributeValue(null, ATTR_VERSION));
Daniel Sandler0da673f2012-04-11 12:33:16 -0400403 } else if (TAG_BLOCKED_PKGS.equals(tag)) {
404 while ((type = parser.next()) != END_DOCUMENT) {
405 tag = parser.getName();
406 if (TAG_PACKAGE.equals(tag)) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800407 mBlockedPackages.add(
408 parser.getAttributeValue(null, ATTR_NAME));
Daniel Sandler0da673f2012-04-11 12:33:16 -0400409 } else if (TAG_BLOCKED_PKGS.equals(tag) && type == END_TAG) {
410 break;
411 }
412 }
413 }
414 }
415 }
416 } catch (FileNotFoundException e) {
417 // No data yet
418 } catch (IOException e) {
419 Log.wtf(TAG, "Unable to read blocked notifications database", e);
420 } catch (NumberFormatException e) {
421 Log.wtf(TAG, "Unable to parse blocked notifications database", e);
422 } catch (XmlPullParserException e) {
423 Log.wtf(TAG, "Unable to parse blocked notifications database", e);
424 } finally {
425 IoUtils.closeQuietly(infile);
426 }
427 }
428 }
429 }
430
Daniel Sandler4a900ac2013-01-30 14:04:10 -0500431 /** Use this when you actually want to post a notification or toast.
432 *
433 * Unchecked. Not exposed via Binder, but can be called in the course of enqueue*().
434 */
435 private boolean noteNotificationOp(String pkg, int uid) {
436 if (mAppOps.noteOpNoThrow(AppOpsManager.OP_POST_NOTIFICATION, uid, pkg)
437 != AppOpsManager.MODE_ALLOWED) {
438 Slog.v(TAG, "notifications are disabled by AppOps for " + pkg);
439 return false;
Daniel Sandler0da673f2012-04-11 12:33:16 -0400440 }
Daniel Sandler4a900ac2013-01-30 14:04:10 -0500441 return true;
Daniel Sandler0da673f2012-04-11 12:33:16 -0400442 }
443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800444 private static String idDebugString(Context baseContext, String packageName, int id) {
445 Context c = null;
446
447 if (packageName != null) {
448 try {
449 c = baseContext.createPackageContext(packageName, 0);
450 } catch (NameNotFoundException e) {
451 c = baseContext;
452 }
453 } else {
454 c = baseContext;
455 }
456
457 String pkg;
458 String type;
459 String name;
460
461 Resources r = c.getResources();
462 try {
463 return r.getResourceName(id);
464 } catch (Resources.NotFoundException e) {
465 return "<name unknown>";
466 }
467 }
468
Daniel Sandler78d0d252013-02-12 08:14:52 -0500469
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700470 /**
Chris Wrenae9bb572013-05-15 14:50:28 -0400471 * Remove notification access for any services that no longer exist.
472 */
473 void disableNonexistentListeners() {
474 int currentUser = ActivityManager.getCurrentUser();
475 String flatIn = Settings.Secure.getStringForUser(
Adam Lesinski182f73f2013-12-05 16:48:06 -0800476 getContext().getContentResolver(),
Chris Wrenae9bb572013-05-15 14:50:28 -0400477 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
478 currentUser);
479 if (!TextUtils.isEmpty(flatIn)) {
480 if (DBG) Slog.v(TAG, "flat before: " + flatIn);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800481 PackageManager pm = getContext().getPackageManager();
Chris Wrenae9bb572013-05-15 14:50:28 -0400482 List<ResolveInfo> installedServices = pm.queryIntentServicesAsUser(
483 new Intent(NotificationListenerService.SERVICE_INTERFACE),
484 PackageManager.GET_SERVICES | PackageManager.GET_META_DATA,
485 currentUser);
486
487 Set<ComponentName> installed = new HashSet<ComponentName>();
488 for (int i = 0, count = installedServices.size(); i < count; i++) {
489 ResolveInfo resolveInfo = installedServices.get(i);
490 ServiceInfo info = resolveInfo.serviceInfo;
491
492 if (!android.Manifest.permission.BIND_NOTIFICATION_LISTENER_SERVICE.equals(
493 info.permission)) {
494 Slog.w(TAG, "Skipping notification listener service "
495 + info.packageName + "/" + info.name
496 + ": it does not require the permission "
497 + android.Manifest.permission.BIND_NOTIFICATION_LISTENER_SERVICE);
498 continue;
499 }
500 installed.add(new ComponentName(info.packageName, info.name));
501 }
502
503 String flatOut = "";
504 if (!installed.isEmpty()) {
505 String[] enabled = flatIn.split(ENABLED_NOTIFICATION_LISTENERS_SEPARATOR);
506 ArrayList<String> remaining = new ArrayList<String>(enabled.length);
507 for (int i = 0; i < enabled.length; i++) {
508 ComponentName enabledComponent = ComponentName.unflattenFromString(enabled[i]);
509 if (installed.contains(enabledComponent)) {
510 remaining.add(enabled[i]);
511 }
512 }
513 flatOut = TextUtils.join(ENABLED_NOTIFICATION_LISTENERS_SEPARATOR, remaining);
514 }
515 if (DBG) Slog.v(TAG, "flat after: " + flatOut);
516 if (!flatIn.equals(flatOut)) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800517 Settings.Secure.putStringForUser(getContext().getContentResolver(),
Chris Wrenae9bb572013-05-15 14:50:28 -0400518 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
519 flatOut, currentUser);
520 }
521 }
522 }
523
524 /**
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700525 * Called whenever packages change, the user switches, or ENABLED_NOTIFICATION_LISTENERS
526 * is altered. (For example in response to USER_SWITCHED in our broadcast receiver)
527 */
528 void rebindListenerServices() {
John Spurlock3ec4e702013-05-16 13:42:38 -0400529 final int currentUser = ActivityManager.getCurrentUser();
530 String flat = Settings.Secure.getStringForUser(
Adam Lesinski182f73f2013-12-05 16:48:06 -0800531 getContext().getContentResolver(),
John Spurlock3ec4e702013-05-16 13:42:38 -0400532 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
533 currentUser);
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700534
535 NotificationListenerInfo[] toRemove = new NotificationListenerInfo[mListeners.size()];
536 final ArrayList<ComponentName> toAdd;
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700537
538 synchronized (mNotificationList) {
539 // unbind and remove all existing listeners
540 toRemove = mListeners.toArray(toRemove);
541
542 toAdd = new ArrayList<ComponentName>();
543 final HashSet<ComponentName> newEnabled = new HashSet<ComponentName>();
544 final HashSet<String> newPackages = new HashSet<String>();
545
546 // decode the list of components
547 if (flat != null) {
548 String[] components = flat.split(ENABLED_NOTIFICATION_LISTENERS_SEPARATOR);
549 for (int i=0; i<components.length; i++) {
550 final ComponentName component
551 = ComponentName.unflattenFromString(components[i]);
552 if (component != null) {
553 newEnabled.add(component);
554 toAdd.add(component);
555 newPackages.add(component.getPackageName());
556 }
557 }
558
559 mEnabledListenersForCurrentUser = newEnabled;
560 mEnabledListenerPackageNames = newPackages;
561 }
562 }
563
564 for (NotificationListenerInfo info : toRemove) {
565 final ComponentName component = info.component;
566 final int oldUser = info.userid;
567 Slog.v(TAG, "disabling notification listener for user " + oldUser + ": " + component);
568 unregisterListenerService(component, info.userid);
569 }
570
571 final int N = toAdd.size();
572 for (int i=0; i<N; i++) {
573 final ComponentName component = toAdd.get(i);
574 Slog.v(TAG, "enabling notification listener for user " + currentUser + ": "
575 + component);
576 registerListenerService(component, currentUser);
577 }
Daniel Sandler4b749ef2013-03-18 21:53:04 -0400578 }
579
Daniel Sandler09a247e2013-02-14 10:24:17 -0500580
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700581 /**
582 * Version of registerListener that takes the name of a
583 * {@link android.service.notification.NotificationListenerService} to bind to.
584 *
585 * This is the mechanism by which third parties may subscribe to notifications.
586 */
587 private void registerListenerService(final ComponentName name, final int userid) {
588 checkCallerIsSystem();
589
590 if (DBG) Slog.v(TAG, "registerListenerService: " + name + " u=" + userid);
591
592 synchronized (mNotificationList) {
593 final String servicesBindingTag = name.toString() + "/" + userid;
594 if (mServicesBinding.contains(servicesBindingTag)) {
595 // stop registering this thing already! we're working on it
596 return;
597 }
598 mServicesBinding.add(servicesBindingTag);
599
600 final int N = mListeners.size();
601 for (int i=N-1; i>=0; i--) {
602 final NotificationListenerInfo info = mListeners.get(i);
603 if (name.equals(info.component)
604 && info.userid == userid) {
605 // cut old connections
606 if (DBG) Slog.v(TAG, " disconnecting old listener: " + info.listener);
607 mListeners.remove(i);
608 if (info.connection != null) {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800609 getContext().unbindService(info.connection);
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700610 }
611 }
612 }
613
614 Intent intent = new Intent(NotificationListenerService.SERVICE_INTERFACE);
615 intent.setComponent(name);
616
617 intent.putExtra(Intent.EXTRA_CLIENT_LABEL,
Scott Greenwald9a05b312013-06-28 00:37:54 -0400618 R.string.notification_listener_binding_label);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800619
620 final PendingIntent pendingIntent = PendingIntent.getActivity(
621 getContext(), 0, new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS), 0);
622 intent.putExtra(Intent.EXTRA_CLIENT_INTENT, pendingIntent);
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700623
624 try {
625 if (DBG) Slog.v(TAG, "binding: " + intent);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800626 if (!getContext().bindServiceAsUser(intent,
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700627 new ServiceConnection() {
628 INotificationListener mListener;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800629
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700630 @Override
631 public void onServiceConnected(ComponentName name, IBinder service) {
632 synchronized (mNotificationList) {
633 mServicesBinding.remove(servicesBindingTag);
634 try {
635 mListener = INotificationListener.Stub.asInterface(service);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800636 NotificationListenerInfo info
637 = new NotificationListenerInfo(
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700638 mListener, name, userid, this);
639 service.linkToDeath(info, 0);
640 mListeners.add(info);
641 } catch (RemoteException e) {
642 // already dead
643 }
644 }
645 }
646
647 @Override
648 public void onServiceDisconnected(ComponentName name) {
649 Slog.v(TAG, "notification listener connection lost: " + name);
650 }
651 },
652 Context.BIND_AUTO_CREATE,
653 new UserHandle(userid)))
654 {
655 mServicesBinding.remove(servicesBindingTag);
656 Slog.w(TAG, "Unable to bind listener service: " + intent);
657 return;
658 }
659 } catch (SecurityException ex) {
660 Slog.e(TAG, "Unable to bind listener service: " + intent, ex);
661 return;
662 }
663 }
664 }
665
Daniel Sandler09a247e2013-02-14 10:24:17 -0500666
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700667 /**
668 * Remove a listener service for the given user by ComponentName
669 */
670 private void unregisterListenerService(ComponentName name, int userid) {
671 checkCallerIsSystem();
672
673 synchronized (mNotificationList) {
674 final int N = mListeners.size();
675 for (int i=N-1; i>=0; i--) {
676 final NotificationListenerInfo info = mListeners.get(i);
677 if (name.equals(info.component)
678 && info.userid == userid) {
679 mListeners.remove(i);
680 if (info.connection != null) {
Daniel Sandlerc1b49bd2013-05-07 13:53:47 -0400681 try {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800682 getContext().unbindService(info.connection);
Daniel Sandlerc1b49bd2013-05-07 13:53:47 -0400683 } catch (IllegalArgumentException ex) {
684 // something happened to the service: we think we have a connection
685 // but it's bogus.
686 Slog.e(TAG, "Listener " + name + " could not be unbound: " + ex);
687 }
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700688 }
689 }
690 }
691 }
692 }
693
694 /**
695 * asynchronously notify all listeners about a new notification
696 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800697 void notifyPostedLocked(NotificationRecord n) {
Daniel Sandler1a497d32013-04-18 14:52:45 -0400698 // make a copy in case changes are made to the underlying Notification object
699 final StatusBarNotification sbn = n.sbn.clone();
Daniel Sandler09a247e2013-02-14 10:24:17 -0500700 for (final NotificationListenerInfo info : mListeners) {
701 mHandler.post(new Runnable() {
702 @Override
703 public void run() {
704 info.notifyPostedIfUserMatch(sbn);
705 }});
706 }
707 }
708
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700709 /**
710 * asynchronously notify all listeners about a removed notification
711 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800712 void notifyRemovedLocked(NotificationRecord n) {
Daniel Sandler1a497d32013-04-18 14:52:45 -0400713 // make a copy in case changes are made to the underlying Notification object
714 // NOTE: this copy is lightweight: it doesn't include heavyweight parts of the notification
715 final StatusBarNotification sbn_light = n.sbn.cloneLight();
716
Daniel Sandler09a247e2013-02-14 10:24:17 -0500717 for (final NotificationListenerInfo info : mListeners) {
718 mHandler.post(new Runnable() {
719 @Override
720 public void run() {
Daniel Sandler1a497d32013-04-18 14:52:45 -0400721 info.notifyRemovedIfUserMatch(sbn_light);
Daniel Sandler09a247e2013-02-14 10:24:17 -0500722 }});
723 }
724 }
725
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700726 // -- APIs to support listeners clicking/clearing notifications --
727
728 private NotificationListenerInfo checkListenerToken(INotificationListener listener) {
729 final IBinder token = listener.asBinder();
730 final int N = mListeners.size();
731 for (int i=0; i<N; i++) {
732 final NotificationListenerInfo info = mListeners.get(i);
733 if (info.listener.asBinder() == token) return info;
734 }
735 throw new SecurityException("Disallowed call from unknown listener: " + listener);
736 }
737
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700738
Daniel Sandler25cf8ce2013-04-24 15:34:57 -0400739
Daniel Sandler5feceeb2013-03-22 18:29:23 -0700740 // -- end of listener APIs --
741
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500742 public static final class NotificationRecord
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 {
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500744 final StatusBarNotification sbn;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 IBinder statusBarKey;
746
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500747 NotificationRecord(StatusBarNotification sbn)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 {
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500749 this.sbn = sbn;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 }
Fred Quintana6ecaff12009-09-25 14:23:13 -0700751
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400752 public Notification getNotification() { return sbn.getNotification(); }
753 public int getFlags() { return sbn.getNotification().flags; }
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500754 public int getUserId() { return sbn.getUserId(); }
755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 void dump(PrintWriter pw, String prefix, Context baseContext) {
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400757 final Notification notification = sbn.getNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 pw.println(prefix + this);
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400759 pw.println(prefix + " uid=" + sbn.getUid() + " userId=" + sbn.getUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 pw.println(prefix + " icon=0x" + Integer.toHexString(notification.icon)
Daniel Sandler4f91efd2013-04-25 16:38:41 -0400761 + " / " + idDebugString(baseContext, sbn.getPackageName(), notification.icon));
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -0400762 pw.println(prefix + " pri=" + notification.priority + " score=" + sbn.getScore());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 pw.println(prefix + " contentIntent=" + notification.contentIntent);
764 pw.println(prefix + " deleteIntent=" + notification.deleteIntent);
765 pw.println(prefix + " tickerText=" + notification.tickerText);
766 pw.println(prefix + " contentView=" + notification.contentView);
Daniel Sandlerf45564e2013-04-15 15:05:08 -0400767 pw.println(prefix + String.format(" defaults=0x%08x flags=0x%08x",
768 notification.defaults, notification.flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 pw.println(prefix + " sound=" + notification.sound);
770 pw.println(prefix + " vibrate=" + Arrays.toString(notification.vibrate));
Daniel Sandlerf45564e2013-04-15 15:05:08 -0400771 pw.println(prefix + String.format(" led=0x%08x onMs=%d offMs=%d",
772 notification.ledARGB, notification.ledOnMS, notification.ledOffMS));
773 if (notification.actions != null && notification.actions.length > 0) {
774 pw.println(prefix + " actions={");
775 final int N = notification.actions.length;
776 for (int i=0; i<N; i++) {
777 final Notification.Action action = notification.actions[i];
778 pw.println(String.format("%s [%d] \"%s\" -> %s",
779 prefix,
780 i,
781 action.title,
782 action.actionIntent.toString()
783 ));
784 }
785 pw.println(prefix + " }");
786 }
787 if (notification.extras != null && notification.extras.size() > 0) {
788 pw.println(prefix + " extras={");
789 for (String key : notification.extras.keySet()) {
790 pw.print(prefix + " " + key + "=");
791 Object val = notification.extras.get(key);
792 if (val == null) {
793 pw.println("null");
794 } else {
795 pw.print(val.toString());
796 if (val instanceof Bitmap) {
797 pw.print(String.format(" (%dx%d)",
798 ((Bitmap) val).getWidth(),
799 ((Bitmap) val).getHeight()));
800 } else if (val.getClass().isArray()) {
801 pw.println(" {");
802 final int N = Array.getLength(val);
803 for (int i=0; i<N; i++) {
804 if (i > 0) pw.println(",");
805 pw.print(prefix + " " + Array.get(val, i));
806 }
807 pw.print("\n" + prefix + " }");
808 }
809 pw.println();
810 }
811 }
812 pw.println(prefix + " }");
813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 @Override
Daniel Sandlerfde19b12013-01-17 00:21:05 -0500817 public final String toString() {
818 return String.format(
819 "NotificationRecord(0x%08x: pkg=%s user=%s id=%d tag=%s score=%d: %s)",
820 System.identityHashCode(this),
Adam Lesinski182f73f2013-12-05 16:48:06 -0800821 this.sbn.getPackageName(), this.sbn.getUser(), this.sbn.getId(),
822 this.sbn.getTag(), this.sbn.getScore(), this.sbn.getNotification());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 }
824 }
825
826 private static final class ToastRecord
827 {
828 final int pid;
829 final String pkg;
830 final ITransientNotification callback;
831 int duration;
832
833 ToastRecord(int pid, String pkg, ITransientNotification callback, int duration)
834 {
835 this.pid = pid;
836 this.pkg = pkg;
837 this.callback = callback;
838 this.duration = duration;
839 }
840
841 void update(int duration) {
842 this.duration = duration;
843 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 void dump(PrintWriter pw, String prefix) {
846 pw.println(prefix + this);
847 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 @Override
850 public final String toString()
851 {
852 return "ToastRecord{"
853 + Integer.toHexString(System.identityHashCode(this))
854 + " pkg=" + pkg
855 + " callback=" + callback
856 + " duration=" + duration;
857 }
858 }
859
Adam Lesinski182f73f2013-12-05 16:48:06 -0800860 private final NotificationDelegate mNotificationDelegate = new NotificationDelegate() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861
Adam Lesinski182f73f2013-12-05 16:48:06 -0800862 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 public void onSetDisabled(int status) {
864 synchronized (mNotificationList) {
865 mDisabledNotifications = status;
866 if ((mDisabledNotifications & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) != 0) {
867 // cancel whatever's going on
868 long identity = Binder.clearCallingIdentity();
869 try {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800870 final IRingtonePlayer player = mAudioManager.getRingtonePlayer();
Jeff Sharkey098d5802012-04-26 17:30:34 -0700871 if (player != null) {
872 player.stopAsync();
873 }
874 } catch (RemoteException e) {
875 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 Binder.restoreCallingIdentity(identity);
877 }
878
879 identity = Binder.clearCallingIdentity();
880 try {
881 mVibrator.cancel();
Jeff Sharkey098d5802012-04-26 17:30:34 -0700882 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 Binder.restoreCallingIdentity(identity);
884 }
885 }
886 }
887 }
888
Adam Lesinski182f73f2013-12-05 16:48:06 -0800889 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 public void onClearAll() {
Dianne Hackborn41203752012-08-31 14:05:51 -0700891 // XXX to be totally correct, the caller should tell us which user
892 // this is for.
893 cancelAll(ActivityManager.getCurrentUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 }
895
Adam Lesinski182f73f2013-12-05 16:48:06 -0800896 @Override
Fred Quintana6ecaff12009-09-25 14:23:13 -0700897 public void onNotificationClick(String pkg, String tag, int id) {
Dianne Hackborn41203752012-08-31 14:05:51 -0700898 // XXX to be totally correct, the caller should tell us which user
899 // this is for.
Fred Quintana6ecaff12009-09-25 14:23:13 -0700900 cancelNotification(pkg, tag, id, Notification.FLAG_AUTO_CANCEL,
Dianne Hackborn41203752012-08-31 14:05:51 -0700901 Notification.FLAG_FOREGROUND_SERVICE, false,
902 ActivityManager.getCurrentUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 }
904
Adam Lesinski182f73f2013-12-05 16:48:06 -0800905 @Override
Daniel Sandler0f0b11c2010-08-04 15:54:58 -0400906 public void onNotificationClear(String pkg, String tag, int id) {
Dianne Hackborn41203752012-08-31 14:05:51 -0700907 // XXX to be totally correct, the caller should tell us which user
908 // this is for.
Joe Onorato46439ce2010-11-19 13:56:21 -0800909 cancelNotification(pkg, tag, id, 0,
910 Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE,
Dianne Hackborn41203752012-08-31 14:05:51 -0700911 true, ActivityManager.getCurrentUser());
Daniel Sandler0f0b11c2010-08-04 15:54:58 -0400912 }
913
Adam Lesinski182f73f2013-12-05 16:48:06 -0800914 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 public void onPanelRevealed() {
916 synchronized (mNotificationList) {
917 // sound
918 mSoundNotification = null;
Jeff Sharkey098d5802012-04-26 17:30:34 -0700919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 long identity = Binder.clearCallingIdentity();
921 try {
Adam Lesinski182f73f2013-12-05 16:48:06 -0800922 final IRingtonePlayer player = mAudioManager.getRingtonePlayer();
Jeff Sharkey098d5802012-04-26 17:30:34 -0700923 if (player != null) {
924 player.stopAsync();
925 }
926 } catch (RemoteException e) {
927 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 Binder.restoreCallingIdentity(identity);
929 }
930
931 // vibrate
932 mVibrateNotification = null;
933 identity = Binder.clearCallingIdentity();
934 try {
935 mVibrator.cancel();
Jeff Sharkey098d5802012-04-26 17:30:34 -0700936 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 Binder.restoreCallingIdentity(identity);
938 }
939
940 // light
941 mLights.clear();
942 mLedNotification = null;
943 updateLightsLocked();
944 }
945 }
Joe Onorato005847b2010-06-04 16:08:02 -0400946
Adam Lesinski182f73f2013-12-05 16:48:06 -0800947 @Override
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700948 public void onNotificationError(String pkg, String tag, int id,
949 int uid, int initialPid, String message) {
Daniel Sandlerd0a2f862010-08-03 15:29:31 -0400950 Slog.d(TAG, "onNotification error pkg=" + pkg + " tag=" + tag + " id=" + id
951 + "; will crashApplication(uid=" + uid + ", pid=" + initialPid + ")");
Dianne Hackborn41203752012-08-31 14:05:51 -0700952 // XXX to be totally correct, the caller should tell us which user
953 // this is for.
954 cancelNotification(pkg, tag, id, 0, 0, false, UserHandle.getUserId(uid));
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -0700955 long ident = Binder.clearCallingIdentity();
956 try {
957 ActivityManagerNative.getDefault().crashApplication(uid, initialPid, pkg,
958 "Bad notification posted from package " + pkg
959 + ": " + message);
960 } catch (RemoteException e) {
961 }
962 Binder.restoreCallingIdentity(ident);
Joe Onorato005847b2010-06-04 16:08:02 -0400963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 };
965
966 private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
967 @Override
968 public void onReceive(Context context, Intent intent) {
969 String action = intent.getAction();
970
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800971 boolean queryRestart = false;
Chris Wrenae9bb572013-05-15 14:50:28 -0400972 boolean queryRemove = false;
Daniel Sandler26ece572012-06-01 15:38:46 -0400973 boolean packageChanged = false;
John Spurlock79f78922013-05-16 09:10:05 -0400974 boolean cancelNotifications = true;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800975
Chris Wren3da73022013-05-10 14:41:21 -0400976 if (action.equals(Intent.ACTION_PACKAGE_ADDED)
Chris Wrenae9bb572013-05-15 14:50:28 -0400977 || (queryRemove=action.equals(Intent.ACTION_PACKAGE_REMOVED))
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800978 || action.equals(Intent.ACTION_PACKAGE_RESTARTED)
Daniel Sandler26ece572012-06-01 15:38:46 -0400979 || (packageChanged=action.equals(Intent.ACTION_PACKAGE_CHANGED))
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800980 || (queryRestart=action.equals(Intent.ACTION_QUERY_PACKAGE_RESTART))
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800981 || action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800982 String pkgList[] = null;
Chris Wrenae9bb572013-05-15 14:50:28 -0400983 boolean queryReplace = queryRemove &&
984 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
985 if (DBG) Slog.i(TAG, "queryReplace=" + queryReplace);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -0800986 if (action.equals(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800987 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -0800988 } else if (queryRestart) {
989 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -0800990 } else {
991 Uri uri = intent.getData();
992 if (uri == null) {
993 return;
994 }
995 String pkgName = uri.getSchemeSpecificPart();
996 if (pkgName == null) {
997 return;
998 }
Daniel Sandler26ece572012-06-01 15:38:46 -0400999 if (packageChanged) {
1000 // We cancel notifications for packages which have just been disabled
Christopher Tate06e5fed2013-10-09 14:39:15 -07001001 try {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001002 final int enabled = getContext().getPackageManager()
Christopher Tate06e5fed2013-10-09 14:39:15 -07001003 .getApplicationEnabledSetting(pkgName);
1004 if (enabled == PackageManager.COMPONENT_ENABLED_STATE_ENABLED
1005 || enabled == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
1006 cancelNotifications = false;
1007 }
1008 } catch (IllegalArgumentException e) {
1009 // Package doesn't exist; probably racing with uninstall.
1010 // cancelNotifications is already true, so nothing to do here.
1011 if (DBG) {
1012 Slog.i(TAG, "Exception trying to look up app enabled setting", e);
1013 }
Daniel Sandler26ece572012-06-01 15:38:46 -04001014 }
1015 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001016 pkgList = new String[]{pkgName};
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 }
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001018
1019 boolean anyListenersInvolved = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001020 if (pkgList != null && (pkgList.length > 0)) {
1021 for (String pkgName : pkgList) {
John Spurlock79f78922013-05-16 09:10:05 -04001022 if (cancelNotifications) {
1023 cancelAllNotificationsInt(pkgName, 0, 0, !queryRestart,
1024 UserHandle.USER_ALL);
1025 }
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001026 if (mEnabledListenerPackageNames.contains(pkgName)) {
1027 anyListenersInvolved = true;
1028 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08001029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 }
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001031
1032 if (anyListenersInvolved) {
Chris Wrenae9bb572013-05-15 14:50:28 -04001033 // if we're not replacing a package, clean up orphaned bits
1034 if (!queryReplace) {
1035 disableNonexistentListeners();
1036 }
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001037 // make sure we're still bound to any of our
1038 // listeners who may have just upgraded
1039 rebindListenerServices();
1040 }
Mike Lockwood63b5ad92011-08-30 09:55:30 -04001041 } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
1042 // Keep track of screen on/off state, but do not turn off the notification light
1043 // until user passes through the lock screen or views the notification.
1044 mScreenOn = true;
1045 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
1046 mScreenOn = false;
Daniel Sandlere96ffb12010-03-11 13:38:06 -05001047 } else if (action.equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
Mike Lockwood63b5ad92011-08-30 09:55:30 -04001048 mInCall = (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
1049 TelephonyManager.EXTRA_STATE_OFFHOOK));
Daniel Sandlere96ffb12010-03-11 13:38:06 -05001050 updateNotificationPulse();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001051 } else if (action.equals(Intent.ACTION_USER_STOPPED)) {
1052 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
1053 if (userHandle >= 0) {
Dianne Hackborn41203752012-08-31 14:05:51 -07001054 cancelAllNotificationsInt(null, 0, 0, true, userHandle);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001055 }
Mike Lockwood63b5ad92011-08-30 09:55:30 -04001056 } else if (action.equals(Intent.ACTION_USER_PRESENT)) {
1057 // turn off LED when user passes through lock screen
1058 mNotificationLight.turnOff();
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001059 } else if (action.equals(Intent.ACTION_USER_SWITCHED)) {
1060 // reload per-user settings
1061 mSettingsObserver.update(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 }
1063 }
1064 };
1065
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001066 class SettingsObserver extends ContentObserver {
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001067 private final Uri NOTIFICATION_LIGHT_PULSE_URI
1068 = Settings.System.getUriFor(Settings.System.NOTIFICATION_LIGHT_PULSE);
1069
1070 private final Uri ENABLED_NOTIFICATION_LISTENERS_URI
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001071 = Settings.Secure.getUriFor(Settings.Secure.ENABLED_NOTIFICATION_LISTENERS);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001072
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001073 SettingsObserver(Handler handler) {
1074 super(handler);
1075 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001076
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001077 void observe() {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001078 ContentResolver resolver = getContext().getContentResolver();
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001079 resolver.registerContentObserver(NOTIFICATION_LIGHT_PULSE_URI,
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001080 false, this, UserHandle.USER_ALL);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001081 resolver.registerContentObserver(ENABLED_NOTIFICATION_LISTENERS_URI,
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001082 false, this, UserHandle.USER_ALL);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001083 update(null);
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001084 }
1085
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001086 @Override public void onChange(boolean selfChange, Uri uri) {
1087 update(uri);
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001088 }
1089
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001090 public void update(Uri uri) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001091 ContentResolver resolver = getContext().getContentResolver();
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001092 if (uri == null || NOTIFICATION_LIGHT_PULSE_URI.equals(uri)) {
1093 boolean pulseEnabled = Settings.System.getInt(resolver,
1094 Settings.System.NOTIFICATION_LIGHT_PULSE, 0) != 0;
1095 if (mNotificationPulseEnabled != pulseEnabled) {
1096 mNotificationPulseEnabled = pulseEnabled;
1097 updateNotificationPulse();
1098 }
1099 }
1100 if (uri == null || ENABLED_NOTIFICATION_LISTENERS_URI.equals(uri)) {
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001101 rebindListenerServices();
Mike Lockwoodc22404a2009-12-02 11:15:02 -05001102 }
Dianne Hackborn1dac2772009-06-26 18:16:48 -07001103 }
1104 }
Mike Lockwoodc22404a2009-12-02 11:15:02 -05001105
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001106 private SettingsObserver mSettingsObserver;
1107
Daniel Sandleredbb3802012-11-13 20:49:47 -08001108 static long[] getLongArray(Resources r, int resid, int maxlen, long[] def) {
1109 int[] ar = r.getIntArray(resid);
1110 if (ar == null) {
1111 return def;
1112 }
1113 final int len = ar.length > maxlen ? maxlen : ar.length;
1114 long[] out = new long[len];
1115 for (int i=0; i<len; i++) {
1116 out[i] = ar[i];
1117 }
1118 return out;
1119 }
1120
Adam Lesinski182f73f2013-12-05 16:48:06 -08001121 @Override
1122 public void onStart() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 mAm = ActivityManagerNative.getDefault();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001124 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
1125 mVibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE);
San Mehat3ee13172010-02-04 20:54:43 -08001126
Adam Lesinski182f73f2013-12-05 16:48:06 -08001127 mHandler = new WorkerHandler();
Daniel Sandler4a900ac2013-01-30 14:04:10 -05001128
1129 importOldBlockDb();
Daniel Sandler0da673f2012-04-11 12:33:16 -04001130
Adam Lesinski182f73f2013-12-05 16:48:06 -08001131 mStatusBar = getLocalService(StatusBarManagerInternal.class);
1132 mStatusBar.setNotificationDelegate(mNotificationDelegate);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133
Adam Lesinski182f73f2013-12-05 16:48:06 -08001134 final LightsManager lights = getLocalService(LightsManager.class);
1135 mNotificationLight = lights.getLight(LightsManager.LIGHT_ID_NOTIFICATIONS);
1136 mAttentionLight = lights.getLight(LightsManager.LIGHT_ID_ATTENTION);
Mike Lockwood3cb67a32009-11-27 14:25:58 -05001137
Adam Lesinski182f73f2013-12-05 16:48:06 -08001138 Resources resources = getContext().getResources();
Mike Lockwood670f9322010-01-20 12:13:36 -05001139 mDefaultNotificationColor = resources.getColor(
Scott Greenwald9a05b312013-06-28 00:37:54 -04001140 R.color.config_defaultNotificationColor);
Mike Lockwood670f9322010-01-20 12:13:36 -05001141 mDefaultNotificationLedOn = resources.getInteger(
Scott Greenwald9a05b312013-06-28 00:37:54 -04001142 R.integer.config_defaultNotificationLedOn);
Mike Lockwood670f9322010-01-20 12:13:36 -05001143 mDefaultNotificationLedOff = resources.getInteger(
Scott Greenwald9a05b312013-06-28 00:37:54 -04001144 R.integer.config_defaultNotificationLedOff);
Mike Lockwood670f9322010-01-20 12:13:36 -05001145
Daniel Sandleredbb3802012-11-13 20:49:47 -08001146 mDefaultVibrationPattern = getLongArray(resources,
Scott Greenwald9a05b312013-06-28 00:37:54 -04001147 R.array.config_defaultNotificationVibePattern,
Daniel Sandleredbb3802012-11-13 20:49:47 -08001148 VIBRATE_PATTERN_MAXLEN,
1149 DEFAULT_VIBRATE_PATTERN);
1150
1151 mFallbackVibrationPattern = getLongArray(resources,
Scott Greenwald9a05b312013-06-28 00:37:54 -04001152 R.array.config_notificationFallbackVibePattern,
Daniel Sandleredbb3802012-11-13 20:49:47 -08001153 VIBRATE_PATTERN_MAXLEN,
1154 DEFAULT_VIBRATE_PATTERN);
1155
Joe Onorato39f5b6a2009-07-23 12:29:19 -04001156 // Don't start allowing notifications until the setup wizard has run once.
1157 // After that, including subsequent boots, init with notifications turned on.
1158 // This works on the first boot because the setup wizard will toggle this
1159 // flag at least once and we'll go back to 0 after that.
Adam Lesinski182f73f2013-12-05 16:48:06 -08001160 if (0 == Settings.Global.getInt(getContext().getContentResolver(),
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001161 Settings.Global.DEVICE_PROVISIONED, 0)) {
Joe Onorato39f5b6a2009-07-23 12:29:19 -04001162 mDisabledNotifications = StatusBarManager.DISABLE_NOTIFICATION_ALERTS;
1163 }
1164
Mike Lockwood35e16bf2010-11-30 19:53:36 -05001165 // register for various Intents
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 IntentFilter filter = new IntentFilter();
Mike Lockwoodc22404a2009-12-02 11:15:02 -05001167 filter.addAction(Intent.ACTION_SCREEN_ON);
1168 filter.addAction(Intent.ACTION_SCREEN_OFF);
Daniel Sandlere96ffb12010-03-11 13:38:06 -05001169 filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
Mike Lockwood63b5ad92011-08-30 09:55:30 -04001170 filter.addAction(Intent.ACTION_USER_PRESENT);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001171 filter.addAction(Intent.ACTION_USER_STOPPED);
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001172 filter.addAction(Intent.ACTION_USER_SWITCHED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001173 getContext().registerReceiver(mIntentReceiver, filter);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001174 IntentFilter pkgFilter = new IntentFilter();
Chris Wren3da73022013-05-10 14:41:21 -04001175 pkgFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001176 pkgFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
Daniel Sandleraac0eb02011-08-06 22:51:56 -04001177 pkgFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001178 pkgFilter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
1179 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
1180 pkgFilter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08001181 getContext().registerReceiver(mIntentReceiver, pkgFilter);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08001182 IntentFilter sdFilter = new IntentFilter(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001183 getContext().registerReceiver(mIntentReceiver, sdFilter);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001184
Daniel Sandler4b749ef2013-03-18 21:53:04 -04001185 mSettingsObserver = new SettingsObserver(mHandler);
1186 mSettingsObserver.observe();
Scott Greenwald9a05b312013-06-28 00:37:54 -04001187
1188 // spin up NotificationScorers
1189 String[] notificationScorerNames = resources.getStringArray(
1190 R.array.config_notificationScorers);
1191 for (String scorerName : notificationScorerNames) {
1192 try {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001193 Class<?> scorerClass = getContext().getClassLoader().loadClass(scorerName);
Scott Greenwald9a05b312013-06-28 00:37:54 -04001194 NotificationScorer scorer = (NotificationScorer) scorerClass.newInstance();
Adam Lesinski182f73f2013-12-05 16:48:06 -08001195 scorer.initialize(getContext());
Scott Greenwald9a05b312013-06-28 00:37:54 -04001196 mScorers.add(scorer);
1197 } catch (ClassNotFoundException e) {
1198 Slog.w(TAG, "Couldn't find scorer " + scorerName + ".", e);
1199 } catch (InstantiationException e) {
1200 Slog.w(TAG, "Couldn't instantiate scorer " + scorerName + ".", e);
1201 } catch (IllegalAccessException e) {
1202 Slog.w(TAG, "Problem accessing scorer " + scorerName + ".", e);
1203 }
1204 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001205
1206 publishBinderService(Context.NOTIFICATION_SERVICE, mService);
1207 publishLocalService(NotificationManagerInternal.class, mInternalService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 }
1209
Daniel Sandler4a900ac2013-01-30 14:04:10 -05001210 /**
1211 * Read the old XML-based app block database and import those blockages into the AppOps system.
1212 */
1213 private void importOldBlockDb() {
1214 loadBlockDb();
1215
Adam Lesinski182f73f2013-12-05 16:48:06 -08001216 PackageManager pm = getContext().getPackageManager();
Daniel Sandler4a900ac2013-01-30 14:04:10 -05001217 for (String pkg : mBlockedPackages) {
1218 PackageInfo info = null;
1219 try {
1220 info = pm.getPackageInfo(pkg, 0);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001221 setNotificationsEnabledForPackageImpl(pkg, info.applicationInfo.uid, false);
Daniel Sandler4a900ac2013-01-30 14:04:10 -05001222 } catch (NameNotFoundException e) {
1223 // forget you
1224 }
1225 }
1226 mBlockedPackages.clear();
1227 if (mPolicyFile != null) {
1228 mPolicyFile.delete();
1229 }
1230 }
1231
Adam Lesinski182f73f2013-12-05 16:48:06 -08001232 @Override
1233 public void onBootPhase(int phase) {
1234 if (phase == SystemService.PHASE_SYSTEM_SERVICES_READY) {
1235 // no beeping until we're basically done booting
1236 mSystemReady = true;
Jeff Sharkey098d5802012-04-26 17:30:34 -07001237
Adam Lesinski182f73f2013-12-05 16:48:06 -08001238 // Grab our optional AudioService
1239 mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
Daniel Sandler5feceeb2013-03-22 18:29:23 -07001240
Adam Lesinski182f73f2013-12-05 16:48:06 -08001241 // make sure our listener services are properly bound
1242 rebindListenerServices();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 }
1244 }
1245
Adam Lesinski182f73f2013-12-05 16:48:06 -08001246 void setNotificationsEnabledForPackageImpl(String pkg, int uid, boolean enabled) {
1247 Slog.v(TAG, (enabled?"en":"dis") + "abling notifications for " + pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248
Adam Lesinski182f73f2013-12-05 16:48:06 -08001249 mAppOps.setMode(AppOpsManager.OP_POST_NOTIFICATION, uid, pkg,
1250 enabled ? AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251
Adam Lesinski182f73f2013-12-05 16:48:06 -08001252 // Now, cancel any outstanding notifications that are part of a just-disabled app
1253 if (ENABLE_BLOCKED_NOTIFICATIONS && !enabled) {
1254 cancelAllNotificationsInt(pkg, 0, 0, true, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 }
1256 }
1257
Adam Lesinski182f73f2013-12-05 16:48:06 -08001258 private final IBinder mService = new INotificationManager.Stub() {
1259 // Toasts
1260 // ============================================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001263 public void enqueueToast(String pkg, ITransientNotification callback, int duration)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001265 if (DBG) {
1266 Slog.i(TAG, "enqueueToast pkg=" + pkg + " callback=" + callback
1267 + " duration=" + duration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001269
1270 if (pkg == null || callback == null) {
1271 Slog.e(TAG, "Not doing toast. pkg=" + pkg + " callback=" + callback);
1272 return ;
1273 }
1274
1275 final boolean isSystemToast = isCallerSystem() || ("android".equals(pkg));
1276
1277 if (ENABLE_BLOCKED_TOASTS && !noteNotificationOp(pkg, Binder.getCallingUid())) {
1278 if (!isSystemToast) {
1279 Slog.e(TAG, "Suppressing toast from package " + pkg + " by user request.");
1280 return;
1281 }
1282 }
1283
1284 synchronized (mToastQueue) {
1285 int callingPid = Binder.getCallingPid();
1286 long callingId = Binder.clearCallingIdentity();
1287 try {
1288 ToastRecord record;
1289 int index = indexOfToastLocked(pkg, callback);
1290 // If it's already in the queue, we update it in place, we don't
1291 // move it to the end of the queue.
1292 if (index >= 0) {
1293 record = mToastQueue.get(index);
1294 record.update(duration);
1295 } else {
1296 // Limit the number of toasts that any given package except the android
1297 // package can enqueue. Prevents DOS attacks and deals with leaks.
1298 if (!isSystemToast) {
1299 int count = 0;
1300 final int N = mToastQueue.size();
1301 for (int i=0; i<N; i++) {
1302 final ToastRecord r = mToastQueue.get(i);
1303 if (r.pkg.equals(pkg)) {
1304 count++;
1305 if (count >= MAX_PACKAGE_NOTIFICATIONS) {
1306 Slog.e(TAG, "Package has already posted " + count
1307 + " toasts. Not showing more. Package=" + pkg);
1308 return;
1309 }
1310 }
1311 }
1312 }
1313
1314 record = new ToastRecord(callingPid, pkg, callback, duration);
1315 mToastQueue.add(record);
1316 index = mToastQueue.size() - 1;
1317 keepProcessAliveLocked(callingPid);
1318 }
1319 // If it's at index 0, it's the current toast. It doesn't matter if it's
1320 // new or just been updated. Call back and tell it to show itself.
1321 // If the callback fails, this will remove it from the list, so don't
1322 // assume that it's valid after this.
1323 if (index == 0) {
1324 showNextToastLocked();
1325 }
1326 } finally {
1327 Binder.restoreCallingIdentity(callingId);
1328 }
1329 }
1330 }
1331
1332 @Override
1333 public void cancelToast(String pkg, ITransientNotification callback) {
1334 Slog.i(TAG, "cancelToast pkg=" + pkg + " callback=" + callback);
1335
1336 if (pkg == null || callback == null) {
1337 Slog.e(TAG, "Not cancelling notification. pkg=" + pkg + " callback=" + callback);
1338 return ;
1339 }
1340
1341 synchronized (mToastQueue) {
1342 long callingId = Binder.clearCallingIdentity();
1343 try {
1344 int index = indexOfToastLocked(pkg, callback);
1345 if (index >= 0) {
1346 cancelToastLocked(index);
1347 } else {
1348 Slog.w(TAG, "Toast already cancelled. pkg=" + pkg
1349 + " callback=" + callback);
1350 }
1351 } finally {
1352 Binder.restoreCallingIdentity(callingId);
1353 }
1354 }
1355 }
1356
1357 @Override
1358 public void enqueueNotificationWithTag(String pkg, String basePkg, String tag, int id,
1359 Notification notification, int[] idOut, int userId) throws RemoteException {
1360 enqueueNotificationInternal(pkg, basePkg, Binder.getCallingUid(),
1361 Binder.getCallingPid(), tag, id, notification, idOut, userId);
1362 }
1363
1364 @Override
1365 public void cancelNotificationWithTag(String pkg, String tag, int id, int userId) {
1366 checkCallerIsSystemOrSameApp(pkg);
1367 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1368 Binder.getCallingUid(), userId, true, false, "cancelNotificationWithTag", pkg);
1369 // Don't allow client applications to cancel foreground service notis.
1370 cancelNotification(pkg, tag, id, 0,
1371 Binder.getCallingUid() == Process.SYSTEM_UID
1372 ? 0 : Notification.FLAG_FOREGROUND_SERVICE, false, userId);
1373 }
1374
1375 @Override
1376 public void cancelAllNotifications(String pkg, int userId) {
1377 checkCallerIsSystemOrSameApp(pkg);
1378
1379 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1380 Binder.getCallingUid(), userId, true, false, "cancelAllNotifications", pkg);
1381
1382 // Calling from user space, don't allow the canceling of actively
1383 // running foreground services.
1384 cancelAllNotificationsInt(pkg, 0, Notification.FLAG_FOREGROUND_SERVICE, true, userId);
1385 }
1386
1387 @Override
1388 public void setNotificationsEnabledForPackage(String pkg, int uid, boolean enabled) {
1389 checkCallerIsSystem();
1390
1391 setNotificationsEnabledForPackageImpl(pkg, uid, enabled);
1392 }
1393
1394 /**
1395 * Use this when you just want to know if notifications are OK for this package.
1396 */
1397 @Override
1398 public boolean areNotificationsEnabledForPackage(String pkg, int uid) {
1399 checkCallerIsSystem();
1400 return (mAppOps.checkOpNoThrow(AppOpsManager.OP_POST_NOTIFICATION, uid, pkg)
1401 == AppOpsManager.MODE_ALLOWED);
1402 }
1403
1404 /**
1405 * System-only API for getting a list of current (i.e. not cleared) notifications.
1406 *
1407 * Requires ACCESS_NOTIFICATIONS which is signature|system.
1408 */
1409 @Override
1410 public StatusBarNotification[] getActiveNotifications(String callingPkg) {
1411 // enforce() will ensure the calling uid has the correct permission
1412 getContext().enforceCallingOrSelfPermission(
1413 android.Manifest.permission.ACCESS_NOTIFICATIONS,
1414 "NotificationManagerService.getActiveNotifications");
1415
1416 StatusBarNotification[] tmp = null;
1417 int uid = Binder.getCallingUid();
1418
1419 // noteOp will check to make sure the callingPkg matches the uid
1420 if (mAppOps.noteOpNoThrow(AppOpsManager.OP_ACCESS_NOTIFICATIONS, uid, callingPkg)
1421 == AppOpsManager.MODE_ALLOWED) {
1422 synchronized (mNotificationList) {
1423 tmp = new StatusBarNotification[mNotificationList.size()];
1424 final int N = mNotificationList.size();
1425 for (int i=0; i<N; i++) {
1426 tmp[i] = mNotificationList.get(i).sbn;
1427 }
1428 }
1429 }
1430 return tmp;
1431 }
1432
1433 /**
1434 * System-only API for getting a list of recent (cleared, no longer shown) notifications.
1435 *
1436 * Requires ACCESS_NOTIFICATIONS which is signature|system.
1437 */
1438 @Override
1439 public StatusBarNotification[] getHistoricalNotifications(String callingPkg, int count) {
1440 // enforce() will ensure the calling uid has the correct permission
1441 getContext().enforceCallingOrSelfPermission(
1442 android.Manifest.permission.ACCESS_NOTIFICATIONS,
1443 "NotificationManagerService.getHistoricalNotifications");
1444
1445 StatusBarNotification[] tmp = null;
1446 int uid = Binder.getCallingUid();
1447
1448 // noteOp will check to make sure the callingPkg matches the uid
1449 if (mAppOps.noteOpNoThrow(AppOpsManager.OP_ACCESS_NOTIFICATIONS, uid, callingPkg)
1450 == AppOpsManager.MODE_ALLOWED) {
1451 synchronized (mArchive) {
1452 tmp = mArchive.getArray(count);
1453 }
1454 }
1455 return tmp;
1456 }
1457
1458 /**
1459 * Register a listener binder directly with the notification manager.
1460 *
1461 * Only works with system callers. Apps should extend
1462 * {@link android.service.notification.NotificationListenerService}.
1463 */
1464 @Override
1465 public void registerListener(final INotificationListener listener,
1466 final ComponentName component, final int userid) {
1467 checkCallerIsSystem();
1468 registerListenerImpl(listener, component, userid);
1469 }
1470
1471 /**
1472 * Remove a listener binder directly
1473 */
1474 @Override
1475 public void unregisterListener(INotificationListener listener, int userid) {
1476 // no need to check permissions; if your listener binder is in the list,
1477 // that's proof that you had permission to add it in the first place
1478 unregisterListenerImpl(listener, userid);
1479 }
1480
1481 /**
1482 * Allow an INotificationListener to simulate a "clear all" operation.
1483 *
1484 * {@see com.android.server.StatusBarManagerService.NotificationCallbacks#onClearAllNotifications}
1485 *
1486 * @param token The binder for the listener, to check that the caller is allowed
1487 */
1488 @Override
1489 public void cancelAllNotificationsFromListener(INotificationListener token) {
1490 NotificationListenerInfo info = checkListenerToken(token);
1491 long identity = Binder.clearCallingIdentity();
1492 try {
1493 cancelAll(info.userid);
1494 } finally {
1495 Binder.restoreCallingIdentity(identity);
1496 }
1497 }
1498
1499 /**
1500 * Allow an INotificationListener to simulate clearing (dismissing) a single notification.
1501 *
1502 * {@see com.android.server.StatusBarManagerService.NotificationCallbacks#onNotificationClear}
1503 *
1504 * @param token The binder for the listener, to check that the caller is allowed
1505 */
1506 @Override
1507 public void cancelNotificationFromListener(INotificationListener token, String pkg,
1508 String tag, int id) {
1509 NotificationListenerInfo info = checkListenerToken(token);
1510 long identity = Binder.clearCallingIdentity();
1511 try {
1512 cancelNotification(pkg, tag, id, 0,
1513 Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE,
1514 true,
1515 info.userid);
1516 } finally {
1517 Binder.restoreCallingIdentity(identity);
1518 }
1519 }
1520
1521 /**
1522 * Allow an INotificationListener to request the list of outstanding notifications seen by
1523 * the current user. Useful when starting up, after which point the listener callbacks
1524 * should be used.
1525 *
1526 * @param token The binder for the listener, to check that the caller is allowed
1527 */
1528 @Override
1529 public StatusBarNotification[] getActiveNotificationsFromListener(
1530 INotificationListener token) {
1531 NotificationListenerInfo info = checkListenerToken(token);
1532
1533 StatusBarNotification[] result = new StatusBarNotification[0];
1534 ArrayList<StatusBarNotification> list = new ArrayList<StatusBarNotification>();
1535 synchronized (mNotificationList) {
1536 final int N = mNotificationList.size();
1537 for (int i=0; i<N; i++) {
1538 StatusBarNotification sbn = mNotificationList.get(i).sbn;
1539 if (info.enabledAndUserMatches(sbn)) {
1540 list.add(sbn);
1541 }
1542 }
1543 }
1544 return list.toArray(result);
1545 }
1546
1547 @Override
1548 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1549 if (getContext().checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
1550 != PackageManager.PERMISSION_GRANTED) {
1551 pw.println("Permission Denial: can't dump NotificationManager from from pid="
1552 + Binder.getCallingPid()
1553 + ", uid=" + Binder.getCallingUid());
1554 return;
1555 }
1556
1557 dumpImpl(pw);
1558 }
1559 };
1560
1561 void dumpImpl(PrintWriter pw) {
1562 pw.println("Current Notification Manager state:");
1563
1564 pw.println(" Listeners (" + mEnabledListenersForCurrentUser.size()
1565 + ") enabled for current user:");
1566 for (ComponentName cmpt : mEnabledListenersForCurrentUser) {
1567 pw.println(" " + cmpt);
1568 }
1569
1570 pw.println(" Live listeners (" + mListeners.size() + "):");
1571 for (NotificationListenerInfo info : mListeners) {
1572 pw.println(" " + info.component
1573 + " (user " + info.userid + "): " + info.listener
1574 + (info.isSystem?" SYSTEM":""));
1575 }
1576
1577 int N;
1578
1579 synchronized (mToastQueue) {
1580 N = mToastQueue.size();
1581 if (N > 0) {
1582 pw.println(" Toast Queue:");
1583 for (int i=0; i<N; i++) {
1584 mToastQueue.get(i).dump(pw, " ");
1585 }
1586 pw.println(" ");
1587 }
1588
1589 }
1590
1591 synchronized (mNotificationList) {
1592 N = mNotificationList.size();
1593 if (N > 0) {
1594 pw.println(" Notification List:");
1595 for (int i=0; i<N; i++) {
1596 mNotificationList.get(i).dump(pw, " ", getContext());
1597 }
1598 pw.println(" ");
1599 }
1600
1601 N = mLights.size();
1602 if (N > 0) {
1603 pw.println(" Lights List:");
1604 for (int i=0; i<N; i++) {
1605 pw.println(" " + mLights.get(i));
1606 }
1607 pw.println(" ");
1608 }
1609
1610 pw.println(" mSoundNotification=" + mSoundNotification);
1611 pw.println(" mVibrateNotification=" + mVibrateNotification);
1612 pw.println(" mDisabledNotifications=0x"
1613 + Integer.toHexString(mDisabledNotifications));
1614 pw.println(" mSystemReady=" + mSystemReady);
1615 pw.println(" mArchive=" + mArchive.toString());
1616 Iterator<StatusBarNotification> iter = mArchive.descendingIterator();
1617 int i=0;
1618 while (iter.hasNext()) {
1619 pw.println(" " + iter.next());
1620 if (++i >= 5) {
1621 if (iter.hasNext()) pw.println(" ...");
1622 break;
1623 }
1624 }
1625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 }
1627 }
1628
Adam Lesinski182f73f2013-12-05 16:48:06 -08001629 /**
1630 * The private API only accessible to the system process.
1631 */
1632 private final NotificationManagerInternal mInternalService = new NotificationManagerInternal() {
1633 @Override
1634 public void enqueueNotification(String pkg, String basePkg, int callingUid, int callingPid,
1635 String tag, int id, Notification notification, int[] idReceived, int userId) {
1636 enqueueNotificationInternal(pkg, basePkg, callingUid, callingPid, tag, id, notification,
1637 idReceived, userId);
1638 }
1639 };
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640
Adam Lesinski182f73f2013-12-05 16:48:06 -08001641 void enqueueNotificationInternal(final String pkg, String basePkg, final int callingUid,
Scott Greenwald9b05c612013-06-25 23:44:05 -04001642 final int callingPid, final String tag, final int id, final Notification notification,
Adam Lesinski182f73f2013-12-05 16:48:06 -08001643 int[] idOut, int incomingUserId) {
Daniel Sandler0da673f2012-04-11 12:33:16 -04001644 if (DBG) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001645 Slog.v(TAG, "enqueueNotificationInternal: pkg=" + pkg + " id=" + id
1646 + " notification=" + notification);
Daniel Sandler0da673f2012-04-11 12:33:16 -04001647 }
1648 checkCallerIsSystemOrSameApp(pkg);
Daniel Sandler9eb434c2013-07-31 20:21:07 -04001649 final boolean isSystemNotification = isUidSystem(callingUid) || ("android".equals(pkg));
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001650
Scott Greenwald9b05c612013-06-25 23:44:05 -04001651 final int userId = ActivityManager.handleIncomingUser(callingPid,
1652 callingUid, incomingUserId, true, false, "enqueueNotification", pkg);
Jeff Sharkey65c4a2b2012-09-25 17:22:27 -07001653 final UserHandle user = new UserHandle(userId);
Dianne Hackborn41203752012-08-31 14:05:51 -07001654
Joe Onoratobd73d012010-06-04 11:44:54 -07001655 // Limit the number of notifications that any given package except the android
1656 // package can enqueue. Prevents DOS attacks and deals with leaks.
Daniel Sandler0da673f2012-04-11 12:33:16 -04001657 if (!isSystemNotification) {
Joe Onoratobd73d012010-06-04 11:44:54 -07001658 synchronized (mNotificationList) {
1659 int count = 0;
1660 final int N = mNotificationList.size();
1661 for (int i=0; i<N; i++) {
1662 final NotificationRecord r = mNotificationList.get(i);
Daniel Sandler4f91efd2013-04-25 16:38:41 -04001663 if (r.sbn.getPackageName().equals(pkg) && r.sbn.getUserId() == userId) {
Joe Onoratobd73d012010-06-04 11:44:54 -07001664 count++;
1665 if (count >= MAX_PACKAGE_NOTIFICATIONS) {
1666 Slog.e(TAG, "Package has already posted " + count
1667 + " notifications. Not showing more. package=" + pkg);
1668 return;
1669 }
1670 }
1671 }
1672 }
1673 }
1674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 // This conditional is a dirty hack to limit the logging done on
1676 // behalf of the download manager without affecting other apps.
1677 if (!pkg.equals("com.android.providers.downloads")
1678 || Log.isLoggable("DownloadManager", Log.VERBOSE)) {
Daniel Sandler321e9c52012-10-12 10:59:26 -07001679 EventLog.writeEvent(EventLogTags.NOTIFICATION_ENQUEUE, pkg, id, tag, userId,
Daniel Sandlerb64cb882011-11-29 23:48:29 -05001680 notification.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 }
1682
1683 if (pkg == null || notification == null) {
1684 throw new IllegalArgumentException("null not allowed: pkg=" + pkg
1685 + " id=" + id + " notification=" + notification);
1686 }
1687 if (notification.icon != 0) {
1688 if (notification.contentView == null) {
1689 throw new IllegalArgumentException("contentView required: pkg=" + pkg
1690 + " id=" + id + " notification=" + notification);
1691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 }
1693
Scott Greenwald9b05c612013-06-25 23:44:05 -04001694 mHandler.post(new Runnable() {
1695 @Override
1696 public void run() {
Daniel Sandler0da673f2012-04-11 12:33:16 -04001697
Scott Greenwald9b05c612013-06-25 23:44:05 -04001698 // === Scoring ===
Daniel Sandler0da673f2012-04-11 12:33:16 -04001699
Scott Greenwald9b05c612013-06-25 23:44:05 -04001700 // 0. Sanitize inputs
1701 notification.priority = clamp(notification.priority, Notification.PRIORITY_MIN,
1702 Notification.PRIORITY_MAX);
1703 // Migrate notification flags to scores
1704 if (0 != (notification.flags & Notification.FLAG_HIGH_PRIORITY)) {
1705 if (notification.priority < Notification.PRIORITY_MAX) {
1706 notification.priority = Notification.PRIORITY_MAX;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 }
Scott Greenwald9b05c612013-06-25 23:44:05 -04001708 } else if (SCORE_ONGOING_HIGHER &&
1709 0 != (notification.flags & Notification.FLAG_ONGOING_EVENT)) {
1710 if (notification.priority < Notification.PRIORITY_HIGH) {
1711 notification.priority = Notification.PRIORITY_HIGH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 }
1713 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05001714
Scott Greenwald9b05c612013-06-25 23:44:05 -04001715 // 1. initial score: buckets of 10, around the app
1716 int score = notification.priority * NOTIFICATION_PRIORITY_MULTIPLIER; //[-20..20]
1717
1718 // 2. Consult external heuristics (TBD)
1719
1720 // 3. Apply local rules
1721
Scott Greenwald9a05b312013-06-28 00:37:54 -04001722 int initialScore = score;
1723 if (!mScorers.isEmpty()) {
1724 if (DBG) Slog.v(TAG, "Initial score is " + score + ".");
1725 for (NotificationScorer scorer : mScorers) {
1726 try {
1727 score = scorer.getScore(notification, score);
1728 } catch (Throwable t) {
1729 Slog.w(TAG, "Scorer threw on .getScore.", t);
1730 }
1731 }
1732 if (DBG) Slog.v(TAG, "Final score is " + score + ".");
1733 }
1734
1735 // add extra to indicate score modified by NotificationScorer
1736 notification.extras.putBoolean(Notification.EXTRA_SCORE_MODIFIED,
1737 score != initialScore);
1738
Scott Greenwald9b05c612013-06-25 23:44:05 -04001739 // blocked apps
1740 if (ENABLE_BLOCKED_NOTIFICATIONS && !noteNotificationOp(pkg, callingUid)) {
1741 if (!isSystemNotification) {
1742 score = JUNK_SCORE;
1743 Slog.e(TAG, "Suppressing notification from package " + pkg
1744 + " by user request.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 }
Daniel Sandlerd4d2de22012-11-14 11:25:46 -08001746 }
1747
Scott Greenwald9b05c612013-06-25 23:44:05 -04001748 if (DBG) {
1749 Slog.v(TAG, "Assigned score=" + score + " to " + notification);
1750 }
1751
1752 if (score < SCORE_DISPLAY_THRESHOLD) {
1753 // Notification will be blocked because the score is too low.
1754 return;
1755 }
1756
1757 // Should this notification make noise, vibe, or use the LED?
1758 final boolean canInterrupt = (score >= SCORE_INTERRUPTION_THRESHOLD);
1759
1760 synchronized (mNotificationList) {
1761 final StatusBarNotification n = new StatusBarNotification(
1762 pkg, id, tag, callingUid, callingPid, score, notification, user);
1763 NotificationRecord r = new NotificationRecord(n);
1764 NotificationRecord old = null;
1765
1766 int index = indexOfNotificationLocked(pkg, tag, id, userId);
1767 if (index < 0) {
1768 mNotificationList.add(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 } else {
Scott Greenwald9b05c612013-06-25 23:44:05 -04001770 old = mNotificationList.remove(index);
1771 mNotificationList.add(index, r);
1772 // Make sure we don't lose the foreground service state.
1773 if (old != null) {
1774 notification.flags |=
1775 old.getNotification().flags & Notification.FLAG_FOREGROUND_SERVICE;
1776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 }
Scott Greenwald9b05c612013-06-25 23:44:05 -04001778
1779 // Ensure if this is a foreground service that the proper additional
1780 // flags are set.
1781 if ((notification.flags&Notification.FLAG_FOREGROUND_SERVICE) != 0) {
1782 notification.flags |= Notification.FLAG_ONGOING_EVENT
1783 | Notification.FLAG_NO_CLEAR;
1784 }
1785
1786 final int currentUser;
1787 final long token = Binder.clearCallingIdentity();
1788 try {
1789 currentUser = ActivityManager.getCurrentUser();
1790 } finally {
1791 Binder.restoreCallingIdentity(token);
1792 }
1793
1794 if (notification.icon != 0) {
1795 if (old != null && old.statusBarKey != null) {
1796 r.statusBarKey = old.statusBarKey;
Adam Lesinski182f73f2013-12-05 16:48:06 -08001797 final long identity = Binder.clearCallingIdentity();
Scott Greenwald9b05c612013-06-25 23:44:05 -04001798 try {
1799 mStatusBar.updateNotification(r.statusBarKey, n);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001800 } finally {
Scott Greenwald9b05c612013-06-25 23:44:05 -04001801 Binder.restoreCallingIdentity(identity);
1802 }
1803 } else {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001804 final long identity = Binder.clearCallingIdentity();
Scott Greenwald9b05c612013-06-25 23:44:05 -04001805 try {
1806 r.statusBarKey = mStatusBar.addNotification(n);
1807 if ((n.getNotification().flags & Notification.FLAG_SHOW_LIGHTS) != 0
1808 && canInterrupt) {
1809 mAttentionLight.pulse();
1810 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001811 } finally {
Scott Greenwald9b05c612013-06-25 23:44:05 -04001812 Binder.restoreCallingIdentity(identity);
1813 }
1814 }
1815 // Send accessibility events only for the current user.
1816 if (currentUser == userId) {
1817 sendAccessibilityEvent(notification, pkg);
1818 }
1819
1820 notifyPostedLocked(r);
1821 } else {
1822 Slog.e(TAG, "Not posting notification with icon==0: " + notification);
1823 if (old != null && old.statusBarKey != null) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001824 final long identity = Binder.clearCallingIdentity();
Scott Greenwald9b05c612013-06-25 23:44:05 -04001825 try {
1826 mStatusBar.removeNotification(old.statusBarKey);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001827 } finally {
Scott Greenwald9b05c612013-06-25 23:44:05 -04001828 Binder.restoreCallingIdentity(identity);
1829 }
1830
1831 notifyRemovedLocked(r);
1832 }
1833 // ATTENTION: in a future release we will bail out here
Adam Lesinski182f73f2013-12-05 16:48:06 -08001834 // so that we do not play sounds, show lights, etc. for invalid
1835 // notifications
Scott Greenwald9b05c612013-06-25 23:44:05 -04001836 Slog.e(TAG, "WARNING: In a future release this will crash the app: "
1837 + n.getPackageName());
1838 }
1839
1840 // If we're not supposed to beep, vibrate, etc. then don't.
Adam Lesinski182f73f2013-12-05 16:48:06 -08001841 if (((mDisabledNotifications
1842 & StatusBarManager.DISABLE_NOTIFICATION_ALERTS) == 0)
Scott Greenwald9b05c612013-06-25 23:44:05 -04001843 && (!(old != null
1844 && (notification.flags & Notification.FLAG_ONLY_ALERT_ONCE) != 0 ))
1845 && (r.getUserId() == UserHandle.USER_ALL ||
1846 (r.getUserId() == userId && r.getUserId() == currentUser))
1847 && canInterrupt
Adam Lesinski182f73f2013-12-05 16:48:06 -08001848 && mSystemReady
1849 && mAudioManager != null) {
Scott Greenwald9b05c612013-06-25 23:44:05 -04001850
1851 // sound
1852
1853 // should we use the default notification sound? (indicated either by
1854 // DEFAULT_SOUND or because notification.sound is pointing at
1855 // Settings.System.NOTIFICATION_SOUND)
1856 final boolean useDefaultSound =
1857 (notification.defaults & Notification.DEFAULT_SOUND) != 0 ||
1858 Settings.System.DEFAULT_NOTIFICATION_URI
1859 .equals(notification.sound);
1860
1861 Uri soundUri = null;
1862 boolean hasValidSound = false;
1863
1864 if (useDefaultSound) {
1865 soundUri = Settings.System.DEFAULT_NOTIFICATION_URI;
1866
1867 // check to see if the default notification sound is silent
Adam Lesinski182f73f2013-12-05 16:48:06 -08001868 ContentResolver resolver = getContext().getContentResolver();
Scott Greenwald9b05c612013-06-25 23:44:05 -04001869 hasValidSound = Settings.System.getString(resolver,
1870 Settings.System.NOTIFICATION_SOUND) != null;
1871 } else if (notification.sound != null) {
1872 soundUri = notification.sound;
1873 hasValidSound = (soundUri != null);
1874 }
1875
1876 if (hasValidSound) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001877 boolean looping =
1878 (notification.flags & Notification.FLAG_INSISTENT) != 0;
Scott Greenwald9b05c612013-06-25 23:44:05 -04001879 int audioStreamType;
1880 if (notification.audioStreamType >= 0) {
1881 audioStreamType = notification.audioStreamType;
1882 } else {
1883 audioStreamType = DEFAULT_STREAM_TYPE;
1884 }
1885 mSoundNotification = r;
1886 // do not play notifications if stream volume is 0 (typically because
Jean-Michel Trivi23805662013-07-31 14:19:18 -07001887 // ringer mode is silent) or if there is a user of exclusive audio focus
Adam Lesinski182f73f2013-12-05 16:48:06 -08001888 if ((mAudioManager.getStreamVolume(audioStreamType) != 0)
1889 && !mAudioManager.isAudioFocusExclusive()) {
Scott Greenwald9b05c612013-06-25 23:44:05 -04001890 final long identity = Binder.clearCallingIdentity();
1891 try {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001892 final IRingtonePlayer player =
1893 mAudioManager.getRingtonePlayer();
Scott Greenwald9b05c612013-06-25 23:44:05 -04001894 if (player != null) {
1895 player.playAsync(soundUri, user, looping, audioStreamType);
1896 }
1897 } catch (RemoteException e) {
1898 } finally {
1899 Binder.restoreCallingIdentity(identity);
1900 }
1901 }
1902 }
1903
1904 // vibrate
1905 // Does the notification want to specify its own vibration?
1906 final boolean hasCustomVibrate = notification.vibrate != null;
1907
1908 // new in 4.2: if there was supposed to be a sound and we're in vibrate
1909 // mode, and no other vibration is specified, we fall back to vibration
1910 final boolean convertSoundToVibration =
1911 !hasCustomVibrate
1912 && hasValidSound
Adam Lesinski182f73f2013-12-05 16:48:06 -08001913 && (mAudioManager.getRingerMode()
Scott Greenwald9b05c612013-06-25 23:44:05 -04001914 == AudioManager.RINGER_MODE_VIBRATE);
1915
1916 // The DEFAULT_VIBRATE flag trumps any custom vibration AND the fallback.
1917 final boolean useDefaultVibrate =
1918 (notification.defaults & Notification.DEFAULT_VIBRATE) != 0;
1919
1920 if ((useDefaultVibrate || convertSoundToVibration || hasCustomVibrate)
Adam Lesinski182f73f2013-12-05 16:48:06 -08001921 && !(mAudioManager.getRingerMode()
Scott Greenwald9b05c612013-06-25 23:44:05 -04001922 == AudioManager.RINGER_MODE_SILENT)) {
1923 mVibrateNotification = r;
1924
1925 if (useDefaultVibrate || convertSoundToVibration) {
1926 // Escalate privileges so we can use the vibrator even if the
1927 // notifying app does not have the VIBRATE permission.
1928 long identity = Binder.clearCallingIdentity();
1929 try {
1930 mVibrator.vibrate(r.sbn.getUid(), r.sbn.getBasePkg(),
1931 useDefaultVibrate ? mDefaultVibrationPattern
1932 : mFallbackVibrationPattern,
1933 ((notification.flags & Notification.FLAG_INSISTENT) != 0)
1934 ? 0: -1);
1935 } finally {
1936 Binder.restoreCallingIdentity(identity);
1937 }
1938 } else if (notification.vibrate.length > 1) {
1939 // If you want your own vibration pattern, you need the VIBRATE
1940 // permission
1941 mVibrator.vibrate(r.sbn.getUid(), r.sbn.getBasePkg(),
1942 notification.vibrate,
1943 ((notification.flags & Notification.FLAG_INSISTENT) != 0)
1944 ? 0: -1);
1945 }
1946 }
1947 }
1948
1949 // light
1950 // the most recent thing gets the light
1951 mLights.remove(old);
1952 if (mLedNotification == old) {
1953 mLedNotification = null;
1954 }
1955 //Slog.i(TAG, "notification.lights="
1956 // + ((old.notification.lights.flags & Notification.FLAG_SHOW_LIGHTS)
1957 // != 0));
1958 if ((notification.flags & Notification.FLAG_SHOW_LIGHTS) != 0
1959 && canInterrupt) {
1960 mLights.add(r);
1961 updateLightsLocked();
1962 } else {
1963 if (old != null
1964 && ((old.getFlags() & Notification.FLAG_SHOW_LIGHTS) != 0)) {
1965 updateLightsLocked();
Eric Laurent524dc042009-11-27 05:07:55 -08001966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 }
1968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 }
Scott Greenwald9b05c612013-06-25 23:44:05 -04001970 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971
1972 idOut[0] = id;
1973 }
1974
Adam Lesinski182f73f2013-12-05 16:48:06 -08001975 void registerListenerImpl(final INotificationListener listener,
1976 final ComponentName component, final int userid) {
1977 synchronized (mNotificationList) {
1978 try {
1979 NotificationListenerInfo info
1980 = new NotificationListenerInfo(listener, component, userid, true);
1981 listener.asBinder().linkToDeath(info, 0);
1982 mListeners.add(info);
1983 } catch (RemoteException e) {
1984 // already dead
1985 }
1986 }
1987 }
1988
1989 void unregisterListenerImpl(final INotificationListener listener, final int userid) {
1990 synchronized (mNotificationList) {
1991 final int N = mListeners.size();
1992 for (int i=N-1; i>=0; i--) {
1993 final NotificationListenerInfo info = mListeners.get(i);
1994 if (info.listener.asBinder() == listener.asBinder()
1995 && info.userid == userid) {
1996 mListeners.remove(i);
1997 if (info.connection != null) {
1998 getContext().unbindService(info.connection);
1999 }
2000 }
2001 }
2002 }
2003 }
2004
2005 void showNextToastLocked() {
2006 ToastRecord record = mToastQueue.get(0);
2007 while (record != null) {
2008 if (DBG) Slog.d(TAG, "Show pkg=" + record.pkg + " callback=" + record.callback);
2009 try {
2010 record.callback.show();
2011 scheduleTimeoutLocked(record);
2012 return;
2013 } catch (RemoteException e) {
2014 Slog.w(TAG, "Object died trying to show notification " + record.callback
2015 + " in package " + record.pkg);
2016 // remove it from the list and let the process die
2017 int index = mToastQueue.indexOf(record);
2018 if (index >= 0) {
2019 mToastQueue.remove(index);
2020 }
2021 keepProcessAliveLocked(record.pid);
2022 if (mToastQueue.size() > 0) {
2023 record = mToastQueue.get(0);
2024 } else {
2025 record = null;
2026 }
2027 }
2028 }
2029 }
2030
2031 void cancelToastLocked(int index) {
2032 ToastRecord record = mToastQueue.get(index);
2033 try {
2034 record.callback.hide();
2035 } catch (RemoteException e) {
2036 Slog.w(TAG, "Object died trying to hide notification " + record.callback
2037 + " in package " + record.pkg);
2038 // don't worry about this, we're about to remove it from
2039 // the list anyway
2040 }
2041 mToastQueue.remove(index);
2042 keepProcessAliveLocked(record.pid);
2043 if (mToastQueue.size() > 0) {
2044 // Show the next one. If the callback fails, this will remove
2045 // it from the list, so don't assume that the list hasn't changed
2046 // after this point.
2047 showNextToastLocked();
2048 }
2049 }
2050
2051 private void scheduleTimeoutLocked(ToastRecord r)
2052 {
2053 mHandler.removeCallbacksAndMessages(r);
2054 Message m = Message.obtain(mHandler, MESSAGE_TIMEOUT, r);
2055 long delay = r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY;
2056 mHandler.sendMessageDelayed(m, delay);
2057 }
2058
2059 private void handleTimeout(ToastRecord record)
2060 {
2061 if (DBG) Slog.d(TAG, "Timeout pkg=" + record.pkg + " callback=" + record.callback);
2062 synchronized (mToastQueue) {
2063 int index = indexOfToastLocked(record.pkg, record.callback);
2064 if (index >= 0) {
2065 cancelToastLocked(index);
2066 }
2067 }
2068 }
2069
2070 // lock on mToastQueue
2071 int indexOfToastLocked(String pkg, ITransientNotification callback)
2072 {
2073 IBinder cbak = callback.asBinder();
2074 ArrayList<ToastRecord> list = mToastQueue;
2075 int len = list.size();
2076 for (int i=0; i<len; i++) {
2077 ToastRecord r = list.get(i);
2078 if (r.pkg.equals(pkg) && r.callback.asBinder() == cbak) {
2079 return i;
2080 }
2081 }
2082 return -1;
2083 }
2084
2085 // lock on mToastQueue
2086 void keepProcessAliveLocked(int pid)
2087 {
2088 int toastCount = 0; // toasts from this pid
2089 ArrayList<ToastRecord> list = mToastQueue;
2090 int N = list.size();
2091 for (int i=0; i<N; i++) {
2092 ToastRecord r = list.get(i);
2093 if (r.pid == pid) {
2094 toastCount++;
2095 }
2096 }
2097 try {
2098 mAm.setProcessForeground(mForegroundToken, pid, toastCount > 0);
2099 } catch (RemoteException e) {
2100 // Shouldn't happen.
2101 }
2102 }
2103
2104 private final class WorkerHandler extends Handler
2105 {
2106 @Override
2107 public void handleMessage(Message msg)
2108 {
2109 switch (msg.what)
2110 {
2111 case MESSAGE_TIMEOUT:
2112 handleTimeout((ToastRecord)msg.obj);
2113 break;
2114 }
2115 }
2116 }
2117
2118
2119 // Notifications
2120 // ============================================================================
2121 static int clamp(int x, int low, int high) {
2122 return (x < low) ? low : ((x > high) ? high : x);
2123 }
2124
2125 void sendAccessibilityEvent(Notification notification, CharSequence packageName) {
2126 AccessibilityManager manager = AccessibilityManager.getInstance(getContext());
svetoslavganov75986cf2009-05-14 22:28:01 -07002127 if (!manager.isEnabled()) {
2128 return;
2129 }
2130
2131 AccessibilityEvent event =
2132 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED);
2133 event.setPackageName(packageName);
2134 event.setClassName(Notification.class.getName());
2135 event.setParcelableData(notification);
2136 CharSequence tickerText = notification.tickerText;
2137 if (!TextUtils.isEmpty(tickerText)) {
2138 event.getText().add(tickerText);
2139 }
2140
2141 manager.sendAccessibilityEvent(event);
2142 }
2143
Joe Onorato46439ce2010-11-19 13:56:21 -08002144 private void cancelNotificationLocked(NotificationRecord r, boolean sendDelete) {
2145 // tell the app
2146 if (sendDelete) {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002147 if (r.getNotification().deleteIntent != null) {
Joe Onorato46439ce2010-11-19 13:56:21 -08002148 try {
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002149 r.getNotification().deleteIntent.send();
Joe Onorato46439ce2010-11-19 13:56:21 -08002150 } catch (PendingIntent.CanceledException ex) {
2151 // do nothing - there's no relevant way to recover, and
2152 // no reason to let this propagate
Daniel Sandler4f91efd2013-04-25 16:38:41 -04002153 Slog.w(TAG, "canceled PendingIntent for " + r.sbn.getPackageName(), ex);
Joe Onorato46439ce2010-11-19 13:56:21 -08002154 }
2155 }
2156 }
2157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002158 // status bar
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002159 if (r.getNotification().icon != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002160 final long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 try {
Joe Onorato0cbda992010-05-02 16:28:15 -07002162 mStatusBar.removeNotification(r.statusBarKey);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002163 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 Binder.restoreCallingIdentity(identity);
2165 }
2166 r.statusBarKey = null;
Daniel Sandler09a247e2013-02-14 10:24:17 -05002167 notifyRemovedLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002168 }
2169
2170 // sound
2171 if (mSoundNotification == r) {
2172 mSoundNotification = null;
Jeff Sharkey098d5802012-04-26 17:30:34 -07002173 final long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 try {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002175 final IRingtonePlayer player = mAudioManager.getRingtonePlayer();
Jeff Sharkey098d5802012-04-26 17:30:34 -07002176 if (player != null) {
2177 player.stopAsync();
2178 }
2179 } catch (RemoteException e) {
2180 } finally {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002181 Binder.restoreCallingIdentity(identity);
2182 }
2183 }
2184
2185 // vibrate
2186 if (mVibrateNotification == r) {
2187 mVibrateNotification = null;
2188 long identity = Binder.clearCallingIdentity();
2189 try {
2190 mVibrator.cancel();
2191 }
2192 finally {
2193 Binder.restoreCallingIdentity(identity);
2194 }
2195 }
2196
2197 // light
2198 mLights.remove(r);
2199 if (mLedNotification == r) {
2200 mLedNotification = null;
2201 }
Daniel Sandler23d7c702013-03-07 16:32:06 -05002202
2203 // Save it for users of getHistoricalNotifications()
2204 mArchive.record(r.sbn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 }
2206
2207 /**
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002208 * Cancels a notification ONLY if it has all of the {@code mustHaveFlags}
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002209 * and none of the {@code mustNotHaveFlags}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002210 */
Adam Lesinski182f73f2013-12-05 16:48:06 -08002211 void cancelNotification(final String pkg, final String tag, final int id,
Svetoslav Ganov835835e2013-08-04 20:17:52 -07002212 final int mustHaveFlags, final int mustNotHaveFlags, final boolean sendDelete,
2213 final int userId) {
2214 // In enqueueNotificationInternal notifications are added by scheduling the
2215 // work on the worker handler. Hence, we also schedule the cancel on this
2216 // handler to avoid a scenario where an add notification call followed by a
2217 // remove notification call ends up in not removing the notification.
2218 mHandler.post(new Runnable() {
2219 @Override
2220 public void run() {
2221 EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL, pkg, id, tag, userId,
2222 mustHaveFlags, mustNotHaveFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223
Svetoslav Ganov835835e2013-08-04 20:17:52 -07002224 synchronized (mNotificationList) {
2225 int index = indexOfNotificationLocked(pkg, tag, id, userId);
2226 if (index >= 0) {
2227 NotificationRecord r = mNotificationList.get(index);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002228
Svetoslav Ganov835835e2013-08-04 20:17:52 -07002229 if ((r.getNotification().flags & mustHaveFlags) != mustHaveFlags) {
2230 return;
2231 }
2232 if ((r.getNotification().flags & mustNotHaveFlags) != 0) {
2233 return;
2234 }
2235
2236 mNotificationList.remove(index);
2237
2238 cancelNotificationLocked(r, sendDelete);
2239 updateLightsLocked();
2240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002241 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002242 }
Svetoslav Ganov835835e2013-08-04 20:17:52 -07002243 });
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 }
2245
2246 /**
Daniel Sandler321e9c52012-10-12 10:59:26 -07002247 * Determine whether the userId applies to the notification in question, either because
2248 * they match exactly, or one of them is USER_ALL (which is treated as a wildcard).
2249 */
2250 private boolean notificationMatchesUserId(NotificationRecord r, int userId) {
2251 return
2252 // looking for USER_ALL notifications? match everything
2253 userId == UserHandle.USER_ALL
2254 // a notification sent to USER_ALL matches any query
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002255 || r.getUserId() == UserHandle.USER_ALL
Daniel Sandler321e9c52012-10-12 10:59:26 -07002256 // an exact user match
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002257 || r.getUserId() == userId;
Daniel Sandler321e9c52012-10-12 10:59:26 -07002258 }
2259
2260 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 * Cancels all notifications from a given package that have all of the
2262 * {@code mustHaveFlags}.
2263 */
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002264 boolean cancelAllNotificationsInt(String pkg, int mustHaveFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002265 int mustNotHaveFlags, boolean doit, int userId) {
Daniel Sandler321e9c52012-10-12 10:59:26 -07002266 EventLog.writeEvent(EventLogTags.NOTIFICATION_CANCEL_ALL, pkg, userId,
2267 mustHaveFlags, mustNotHaveFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002268
2269 synchronized (mNotificationList) {
2270 final int N = mNotificationList.size();
2271 boolean canceledSomething = false;
2272 for (int i = N-1; i >= 0; --i) {
2273 NotificationRecord r = mNotificationList.get(i);
Daniel Sandler321e9c52012-10-12 10:59:26 -07002274 if (!notificationMatchesUserId(r, userId)) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002275 continue;
2276 }
Amith Yamasani5ec00e92012-11-07 16:58:30 -08002277 // Don't remove notifications to all, if there's no package name specified
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002278 if (r.getUserId() == UserHandle.USER_ALL && pkg == null) {
Amith Yamasani5ec00e92012-11-07 16:58:30 -08002279 continue;
2280 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002281 if ((r.getFlags() & mustHaveFlags) != mustHaveFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282 continue;
2283 }
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002284 if ((r.getFlags() & mustNotHaveFlags) != 0) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002285 continue;
2286 }
Daniel Sandler4f91efd2013-04-25 16:38:41 -04002287 if (pkg != null && !r.sbn.getPackageName().equals(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002288 continue;
2289 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002290 canceledSomething = true;
2291 if (!doit) {
2292 return true;
2293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002294 mNotificationList.remove(i);
Joe Onorato46439ce2010-11-19 13:56:21 -08002295 cancelNotificationLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002296 }
2297 if (canceledSomething) {
2298 updateLightsLocked();
2299 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08002300 return canceledSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002301 }
2302 }
2303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002305
Daniel Sandler9eb434c2013-07-31 20:21:07 -04002306 // Return true if the UID is a system or phone UID and therefore should not have
Daniel Sandler7c011302013-06-10 12:06:51 -04002307 // any notifications or toasts blocked.
Daniel Sandler9eb434c2013-07-31 20:21:07 -04002308 boolean isUidSystem(int uid) {
Daniel Sandler7c011302013-06-10 12:06:51 -04002309 final int appid = UserHandle.getAppId(uid);
2310 return (appid == Process.SYSTEM_UID || appid == Process.PHONE_UID || uid == 0);
2311 }
2312
Daniel Sandler9eb434c2013-07-31 20:21:07 -04002313 // same as isUidSystem(int, int) for the Binder caller's UID.
2314 boolean isCallerSystem() {
2315 return isUidSystem(Binder.getCallingUid());
2316 }
2317
Daniel Sandler0da673f2012-04-11 12:33:16 -04002318 void checkCallerIsSystem() {
Daniel Sandler7c011302013-06-10 12:06:51 -04002319 if (isCallerSystem()) {
Daniel Sandler0da673f2012-04-11 12:33:16 -04002320 return;
2321 }
Daniel Sandler7c011302013-06-10 12:06:51 -04002322 throw new SecurityException("Disallowed call for uid " + Binder.getCallingUid());
Daniel Sandler0da673f2012-04-11 12:33:16 -04002323 }
2324
2325 void checkCallerIsSystemOrSameApp(String pkg) {
Daniel Sandler7c011302013-06-10 12:06:51 -04002326 if (isCallerSystem()) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002327 return;
2328 }
Daniel Sandler7c011302013-06-10 12:06:51 -04002329 final int uid = Binder.getCallingUid();
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002330 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07002331 ApplicationInfo ai = AppGlobals.getPackageManager().getApplicationInfo(
2332 pkg, 0, UserHandle.getCallingUserId());
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002333 if (!UserHandle.isSameApp(ai.uid, uid)) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002334 throw new SecurityException("Calling uid " + uid + " gave package"
2335 + pkg + " which is owned by uid " + ai.uid);
2336 }
Amith Yamasanif203aee2012-08-29 18:41:53 -07002337 } catch (RemoteException re) {
2338 throw new SecurityException("Unknown package " + pkg + "\n" + re);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -07002339 }
2340 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002341
Dianne Hackborn41203752012-08-31 14:05:51 -07002342 void cancelAll(int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002343 synchronized (mNotificationList) {
2344 final int N = mNotificationList.size();
2345 for (int i=N-1; i>=0; i--) {
2346 NotificationRecord r = mNotificationList.get(i);
2347
Daniel Sandler321e9c52012-10-12 10:59:26 -07002348 if (!notificationMatchesUserId(r, userId)) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002349 continue;
2350 }
2351
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002352 if ((r.getFlags() & (Notification.FLAG_ONGOING_EVENT
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 | Notification.FLAG_NO_CLEAR)) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002354 mNotificationList.remove(i);
Joe Onorato46439ce2010-11-19 13:56:21 -08002355 cancelNotificationLocked(r, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356 }
2357 }
2358
2359 updateLightsLocked();
2360 }
2361 }
2362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 // lock on mNotificationList
Adam Lesinski182f73f2013-12-05 16:48:06 -08002364 void updateLightsLocked()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365 {
The Android Open Source Project10592532009-03-18 17:39:46 -07002366 // handle notification lights
2367 if (mLedNotification == null) {
2368 // get next notification, if any
2369 int n = mLights.size();
2370 if (n > 0) {
2371 mLedNotification = mLights.get(n-1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002372 }
2373 }
Mike Lockwoodc22404a2009-12-02 11:15:02 -05002374
Mike Lockwood63b5ad92011-08-30 09:55:30 -04002375 // Don't flash while we are in a call or screen is on
2376 if (mLedNotification == null || mInCall || mScreenOn) {
Mike Lockwood3cb67a32009-11-27 14:25:58 -05002377 mNotificationLight.turnOff();
The Android Open Source Project10592532009-03-18 17:39:46 -07002378 } else {
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04002379 final Notification ledno = mLedNotification.sbn.getNotification();
Daniel Sandlerfde19b12013-01-17 00:21:05 -05002380 int ledARGB = ledno.ledARGB;
2381 int ledOnMS = ledno.ledOnMS;
2382 int ledOffMS = ledno.ledOffMS;
2383 if ((ledno.defaults & Notification.DEFAULT_LIGHTS) != 0) {
Mike Lockwood670f9322010-01-20 12:13:36 -05002384 ledARGB = mDefaultNotificationColor;
2385 ledOnMS = mDefaultNotificationLedOn;
2386 ledOffMS = mDefaultNotificationLedOff;
2387 }
2388 if (mNotificationPulseEnabled) {
2389 // pulse repeatedly
Adam Lesinski182f73f2013-12-05 16:48:06 -08002390 mNotificationLight.setFlashing(ledARGB, Light.LIGHT_FLASH_TIMED,
Mike Lockwood670f9322010-01-20 12:13:36 -05002391 ledOnMS, ledOffMS);
Mike Lockwood670f9322010-01-20 12:13:36 -05002392 }
The Android Open Source Project10592532009-03-18 17:39:46 -07002393 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394 }
2395
2396 // lock on mNotificationList
Adam Lesinski182f73f2013-12-05 16:48:06 -08002397 int indexOfNotificationLocked(String pkg, String tag, int id, int userId)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002398 {
2399 ArrayList<NotificationRecord> list = mNotificationList;
2400 final int len = list.size();
2401 for (int i=0; i<len; i++) {
2402 NotificationRecord r = list.get(i);
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04002403 if (!notificationMatchesUserId(r, userId) || r.sbn.getId() != id) {
Dianne Hackborn41203752012-08-31 14:05:51 -07002404 continue;
2405 }
Fred Quintana6ecaff12009-09-25 14:23:13 -07002406 if (tag == null) {
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04002407 if (r.sbn.getTag() != null) {
Fred Quintana6ecaff12009-09-25 14:23:13 -07002408 continue;
2409 }
2410 } else {
Daniel Sandlere6f7f2e2013-04-25 15:44:16 -04002411 if (!tag.equals(r.sbn.getTag())) {
Fred Quintana6ecaff12009-09-25 14:23:13 -07002412 continue;
2413 }
2414 }
Daniel Sandler4f91efd2013-04-25 16:38:41 -04002415 if (r.sbn.getPackageName().equals(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002416 return i;
2417 }
2418 }
2419 return -1;
2420 }
2421
Mike Lockwoodc22404a2009-12-02 11:15:02 -05002422 private void updateNotificationPulse() {
2423 synchronized (mNotificationList) {
2424 updateLightsLocked();
2425 }
2426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002427}