Merge "Rate limit notification sounds/vibrations" into oc-dr1-dev

am: 00d83ea50f

Change-Id: I9228a7b79f4c8f438fceb462128d16eddda2b563
This commit is contained in:
Julia Reynolds
2017-07-10 16:02:37 +00:00
committed by android-build-merger
7 changed files with 226 additions and 26 deletions

View File

@@ -10670,7 +10670,7 @@ public final class Settings {
/** /**
* The maximum allowed notification enqueue rate in Hertz. * The maximum allowed notification enqueue rate in Hertz.
* *
* Should be a float, and includes both posts and updates. * Should be a float, and includes updates only.
* @hide * @hide
*/ */
public static final String MAX_NOTIFICATION_ENQUEUE_RATE = "max_notification_enqueue_rate"; public static final String MAX_NOTIFICATION_ENQUEUE_RATE = "max_notification_enqueue_rate";

View File

@@ -0,0 +1,35 @@
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.android.server.notification;
/**
* {@hide}
*/
public class AlertRateLimiter {
static final long ALLOWED_ALERT_INTERVAL = 1000;
private long mLastNotificationMillis = 0;
boolean shouldRateLimitAlert(long now) {
final long millisSinceLast = now - mLastNotificationMillis;
if (millisSinceLast < 0 || millisSinceLast < ALLOWED_ALERT_INTERVAL) {
return true;
}
mLastNotificationMillis = now;
return false;
}
}

View File

@@ -1055,6 +1055,11 @@ public class NotificationManagerService extends SystemService {
mIsTelevision = isTelevision; mIsTelevision = isTelevision;
} }
@VisibleForTesting
void setUsageStats(NotificationUsageStats us) {
mUsageStats = us;
}
// TODO: Tests should call onStart instead once the methods above are removed. // TODO: Tests should call onStart instead once the methods above are removed.
@VisibleForTesting @VisibleForTesting
void init(Looper looper, IPackageManager packageManager, PackageManager packageManagerClient, void init(Looper looper, IPackageManager packageManager, PackageManager packageManagerClient,
@@ -3688,18 +3693,6 @@ public class NotificationManagerService extends SystemService {
// Should this notification make noise, vibe, or use the LED? // Should this notification make noise, vibe, or use the LED?
final boolean aboveThreshold = final boolean aboveThreshold =
record.getImportance() >= NotificationManager.IMPORTANCE_DEFAULT; record.getImportance() >= NotificationManager.IMPORTANCE_DEFAULT;
final boolean canInterrupt = aboveThreshold && !record.isIntercepted();
if (DBG)
Slog.v(TAG,
"pkg=" + record.sbn.getPackageName() + " canInterrupt=" + canInterrupt +
" intercept=" + record.isIntercepted()
);
// If we're not supposed to beep, vibrate, etc. then don't.
final String disableEffects = disableNotificationEffects(record);
if (disableEffects != null) {
ZenLog.traceDisableEffects(record, disableEffects);
}
// Remember if this notification already owns the notification channels. // Remember if this notification already owns the notification channels.
boolean wasBeep = key != null && key.equals(mSoundNotificationKey); boolean wasBeep = key != null && key.equals(mSoundNotificationKey);
@@ -3708,20 +3701,16 @@ public class NotificationManagerService extends SystemService {
boolean hasValidVibrate = false; boolean hasValidVibrate = false;
boolean hasValidSound = false; boolean hasValidSound = false;
if (isNotificationForCurrentUser(record)) { if (aboveThreshold && isNotificationForCurrentUser(record)) {
// If the notification will appear in the status bar, it should send an accessibility // If the notification will appear in the status bar, it should send an accessibility
// event // event
if (!record.isUpdate && record.getImportance() > IMPORTANCE_MIN) { if (!record.isUpdate && record.getImportance() > IMPORTANCE_MIN) {
sendAccessibilityEvent(notification, record.sbn.getPackageName()); sendAccessibilityEvent(notification, record.sbn.getPackageName());
} }
if (mSystemReady && mAudioManager != null) {
if (disableEffects == null
&& canInterrupt
&& mSystemReady
&& mAudioManager != null) {
if (DBG) Slog.v(TAG, "Interrupting!");
Uri soundUri = record.getSound(); Uri soundUri = record.getSound();
hasValidSound = soundUri != null && !Uri.EMPTY.equals(soundUri); hasValidSound = soundUri != null && !Uri.EMPTY.equals(soundUri);
long[] vibration = record.getVibration(); long[] vibration = record.getVibration();
// Demote sound to vibration if vibration missing & phone in vibration mode. // Demote sound to vibration if vibration missing & phone in vibration mode.
if (vibration == null if (vibration == null
@@ -3732,7 +3721,10 @@ public class NotificationManagerService extends SystemService {
} }
hasValidVibrate = vibration != null; hasValidVibrate = vibration != null;
if (!shouldMuteNotificationLocked(record)) { boolean hasAudibleAlert = hasValidSound || hasValidVibrate;
if (hasAudibleAlert && !shouldMuteNotificationLocked(record)) {
if (DBG) Slog.v(TAG, "Interrupting!");
if (hasValidSound) { if (hasValidSound) {
mSoundNotificationKey = key; mSoundNotificationKey = key;
if (mInCall) { if (mInCall) {
@@ -3789,14 +3781,37 @@ public class NotificationManagerService extends SystemService {
@GuardedBy("mNotificationLock") @GuardedBy("mNotificationLock")
boolean shouldMuteNotificationLocked(final NotificationRecord record) { boolean shouldMuteNotificationLocked(final NotificationRecord record) {
// Suppressed because it's a silent update
final Notification notification = record.getNotification(); final Notification notification = record.getNotification();
if(record.isUpdate if(record.isUpdate
&& (notification.flags & Notification.FLAG_ONLY_ALERT_ONCE) != 0) { && (notification.flags & Notification.FLAG_ONLY_ALERT_ONCE) != 0) {
return true; return true;
} }
// Suppressed for being too recently noisy
final String pkg = record.sbn.getPackageName();
if (mUsageStats.isAlertRateLimited(pkg)) {
Slog.e(TAG, "Muting recently noisy " + record.getKey());
return true;
}
// muted by listener
final String disableEffects = disableNotificationEffects(record);
if (disableEffects != null) {
ZenLog.traceDisableEffects(record, disableEffects);
return true;
}
// suppressed due to DND
if (record.isIntercepted()) {
return true;
}
// Suppressed because another notification in its group handles alerting
if (record.sbn.isGroup()) { if (record.sbn.isGroup()) {
return notification.suppressAlertingDueToGrouping(); return notification.suppressAlertingDueToGrouping();
} }
return false; return false;
} }

View File

@@ -114,6 +114,18 @@ public class NotificationUsageStats {
} }
} }
/**
* Called when a notification wants to alert.
*/
public synchronized boolean isAlertRateLimited(String packageName) {
AggregatedStats stats = getOrCreateAggregatedStatsLocked(packageName);
if (stats != null) {
return stats.isAlertRateLimited();
} else {
return false;
}
}
/** /**
* Called when a notification is tentatively enqueued by an app, before rate checking. * Called when a notification is tentatively enqueued by an app, before rate checking.
*/ */
@@ -387,7 +399,9 @@ public class NotificationUsageStats {
public ImportanceHistogram quietImportance; public ImportanceHistogram quietImportance;
public ImportanceHistogram finalImportance; public ImportanceHistogram finalImportance;
public RateEstimator enqueueRate; public RateEstimator enqueueRate;
public AlertRateLimiter alertRate;
public int numRateViolations; public int numRateViolations;
public int numAlertViolations;
public int numQuotaViolations; public int numQuotaViolations;
public long mLastAccessTime; public long mLastAccessTime;
@@ -399,6 +413,7 @@ public class NotificationUsageStats {
quietImportance = new ImportanceHistogram(context, "note_imp_quiet_"); quietImportance = new ImportanceHistogram(context, "note_imp_quiet_");
finalImportance = new ImportanceHistogram(context, "note_importance_"); finalImportance = new ImportanceHistogram(context, "note_importance_");
enqueueRate = new RateEstimator(); enqueueRate = new RateEstimator();
alertRate = new AlertRateLimiter();
} }
public AggregatedStats getPrevious() { public AggregatedStats getPrevious() {
@@ -511,6 +526,7 @@ public class NotificationUsageStats {
maybeCount("note_sub_text", (numWithSubText - previous.numWithSubText)); maybeCount("note_sub_text", (numWithSubText - previous.numWithSubText));
maybeCount("note_info_text", (numWithInfoText - previous.numWithInfoText)); maybeCount("note_info_text", (numWithInfoText - previous.numWithInfoText));
maybeCount("note_over_rate", (numRateViolations - previous.numRateViolations)); maybeCount("note_over_rate", (numRateViolations - previous.numRateViolations));
maybeCount("note_over_alert_rate", (numAlertViolations - previous.numAlertViolations));
maybeCount("note_over_quota", (numQuotaViolations - previous.numQuotaViolations)); maybeCount("note_over_quota", (numQuotaViolations - previous.numQuotaViolations));
noisyImportance.maybeCount(previous.noisyImportance); noisyImportance.maybeCount(previous.noisyImportance);
quietImportance.maybeCount(previous.quietImportance); quietImportance.maybeCount(previous.quietImportance);
@@ -543,6 +559,7 @@ public class NotificationUsageStats {
previous.numWithSubText = numWithSubText; previous.numWithSubText = numWithSubText;
previous.numWithInfoText = numWithInfoText; previous.numWithInfoText = numWithInfoText;
previous.numRateViolations = numRateViolations; previous.numRateViolations = numRateViolations;
previous.numAlertViolations = numAlertViolations;
previous.numQuotaViolations = numQuotaViolations; previous.numQuotaViolations = numQuotaViolations;
noisyImportance.update(previous.noisyImportance); noisyImportance.update(previous.noisyImportance);
quietImportance.update(previous.quietImportance); quietImportance.update(previous.quietImportance);
@@ -577,6 +594,14 @@ public class NotificationUsageStats {
enqueueRate.update(now); enqueueRate.update(now);
} }
public boolean isAlertRateLimited() {
boolean limited = alertRate.shouldRateLimitAlert(SystemClock.elapsedRealtime());
if (limited) {
numAlertViolations++;
}
return limited;
}
private String toStringWithIndent(String indent) { private String toStringWithIndent(String indent) {
StringBuilder output = new StringBuilder(); StringBuilder output = new StringBuilder();
output.append(indent).append("AggregatedStats{\n"); output.append(indent).append("AggregatedStats{\n");
@@ -635,7 +660,11 @@ public class NotificationUsageStats {
output.append("numWithSubText=").append(numWithSubText).append("\n"); output.append("numWithSubText=").append(numWithSubText).append("\n");
output.append(indentPlusTwo); output.append(indentPlusTwo);
output.append("numWithInfoText=").append(numWithInfoText).append("\n"); output.append("numWithInfoText=").append(numWithInfoText).append("\n");
output.append(indentPlusTwo);
output.append("numRateViolations=").append(numRateViolations).append("\n"); output.append("numRateViolations=").append(numRateViolations).append("\n");
output.append(indentPlusTwo);
output.append("numAlertViolations=").append(numAlertViolations).append("\n");
output.append(indentPlusTwo);
output.append("numQuotaViolations=").append(numQuotaViolations).append("\n"); output.append("numQuotaViolations=").append(numQuotaViolations).append("\n");
output.append(indentPlusTwo).append(noisyImportance.toString()).append("\n"); output.append(indentPlusTwo).append(noisyImportance.toString()).append("\n");
output.append(indentPlusTwo).append(quietImportance.toString()).append("\n"); output.append(indentPlusTwo).append(quietImportance.toString()).append("\n");
@@ -678,6 +707,7 @@ public class NotificationUsageStats {
maybePut(dump, "numRateViolations", numRateViolations); maybePut(dump, "numRateViolations", numRateViolations);
maybePut(dump, "numQuotaLViolations", numQuotaViolations); maybePut(dump, "numQuotaLViolations", numQuotaViolations);
maybePut(dump, "notificationEnqueueRate", getEnqueueRate()); maybePut(dump, "notificationEnqueueRate", getEnqueueRate());
maybePut(dump, "numAlertViolations", numAlertViolations);
noisyImportance.maybePut(dump, previous.noisyImportance); noisyImportance.maybePut(dump, previous.noisyImportance);
quietImportance.maybePut(dump, previous.quietImportance); quietImportance.maybePut(dump, previous.quietImportance);
finalImportance.maybePut(dump, previous.finalImportance); finalImportance.maybePut(dump, previous.finalImportance);

View File

@@ -0,0 +1,72 @@
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server.notification;
import static com.android.server.notification.AlertRateLimiter.ALLOWED_ALERT_INTERVAL;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.SmallTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@SmallTest
@RunWith(AndroidJUnit4.class)
public class AlertRateLimiterTest extends NotificationTestCase {
private long mTestStartTime;
private
AlertRateLimiter mLimiter;
@Before
public void setUp() {
mTestStartTime = 1225731600000L;
mLimiter = new AlertRateLimiter();
}
@Test
public void testFirstAlertAllowed() throws Exception {
assertFalse(mLimiter.shouldRateLimitAlert(mTestStartTime));
}
@Test
public void testAllowedAfterSecond() throws Exception {
assertFalse(mLimiter.shouldRateLimitAlert(mTestStartTime));
assertFalse(mLimiter.shouldRateLimitAlert(mTestStartTime + ALLOWED_ALERT_INTERVAL));
}
@Test
public void testAllowedAfterSecondEvenWithBlockedEntries() throws Exception {
assertFalse(mLimiter.shouldRateLimitAlert(mTestStartTime));
assertTrue(mLimiter.shouldRateLimitAlert(mTestStartTime + ALLOWED_ALERT_INTERVAL - 1));
assertFalse(mLimiter.shouldRateLimitAlert(mTestStartTime + ALLOWED_ALERT_INTERVAL));
}
@Test
public void testAllowedDisallowedBeforeSecond() throws Exception {
assertFalse(mLimiter.shouldRateLimitAlert(mTestStartTime));
assertTrue(mLimiter.shouldRateLimitAlert(mTestStartTime + ALLOWED_ALERT_INTERVAL - 1));
}
@Test
public void testDisallowedTimePast() throws Exception {
assertFalse(mLimiter.shouldRateLimitAlert(mTestStartTime));
assertTrue(mLimiter.shouldRateLimitAlert(mTestStartTime - ALLOWED_ALERT_INTERVAL));
}
}

View File

@@ -23,6 +23,7 @@ import static android.app.NotificationManager.IMPORTANCE_HIGH;
import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyObject;
@@ -76,6 +77,8 @@ public class BuzzBeepBlinkTest extends NotificationTestCase {
@Mock android.media.IRingtonePlayer mRingtonePlayer; @Mock android.media.IRingtonePlayer mRingtonePlayer;
@Mock Light mLight; @Mock Light mLight;
@Mock Handler mHandler; @Mock Handler mHandler;
@Mock
NotificationUsageStats mUsageStats;
private NotificationManagerService mService; private NotificationManagerService mService;
private String mPkg = "com.android.server.notification"; private String mPkg = "com.android.server.notification";
@@ -115,6 +118,8 @@ public class BuzzBeepBlinkTest extends NotificationTestCase {
when(mAudioManager.getStreamVolume(anyInt())).thenReturn(10); when(mAudioManager.getStreamVolume(anyInt())).thenReturn(10);
when(mAudioManager.getRingerModeInternal()).thenReturn(AudioManager.RINGER_MODE_NORMAL); when(mAudioManager.getRingerModeInternal()).thenReturn(AudioManager.RINGER_MODE_NORMAL);
when(mUsageStats.isAlertRateLimited(any())).thenReturn(false);
mService = new NotificationManagerService(getContext()); mService = new NotificationManagerService(getContext());
mService.setAudioManager(mAudioManager); mService.setAudioManager(mAudioManager);
mService.setVibrator(mVibrator); mService.setVibrator(mVibrator);
@@ -123,6 +128,7 @@ public class BuzzBeepBlinkTest extends NotificationTestCase {
mService.setLights(mLight); mService.setLights(mLight);
mService.setScreenOn(false); mService.setScreenOn(false);
mService.setFallbackVibrationPattern(FALLBACK_VIBRATION_PATTERN); mService.setFallbackVibrationPattern(FALLBACK_VIBRATION_PATTERN);
mService.setUsageStats(mUsageStats);
} }
// //
@@ -806,6 +812,39 @@ public class BuzzBeepBlinkTest extends NotificationTestCase {
verifyNeverBeep(); verifyNeverBeep();
} }
@Test
public void testRepeatedSoundOverLimitMuted() throws Exception {
when(mUsageStats.isAlertRateLimited(any())).thenReturn(true);
NotificationRecord r = getBeepyNotification();
mService.buzzBeepBlinkLocked(r);
verifyNeverBeep();
}
@Test
public void testPostingSilentNotificationDoesNotAffectRateLimiting() throws Exception {
NotificationRecord r = getQuietNotification();
mService.buzzBeepBlinkLocked(r);
verify(mUsageStats, never()).isAlertRateLimited(any());
}
@Test
public void testCrossUserSoundMuted() throws Exception {
final Notification n = new Builder(getContext(), "test")
.setSmallIcon(android.R.drawable.sym_def_app_icon).build();
int userId = mUser.getIdentifier() + 1;
StatusBarNotification sbn = new StatusBarNotification(mPkg, mPkg, 0, mTag, mUid,
mPid, n, UserHandle.of(userId), null, System.currentTimeMillis());
NotificationRecord r = new NotificationRecord(getContext(), sbn,
new NotificationChannel("test", "test", IMPORTANCE_HIGH));
mService.buzzBeepBlinkLocked(r);
verifyNeverBeep();
}
static class VibrateRepeatMatcher implements ArgumentMatcher<VibrationEffect> { static class VibrateRepeatMatcher implements ArgumentMatcher<VibrationEffect> {
private final int mRepeatIndex; private final int mRepeatIndex;

View File

@@ -51,6 +51,7 @@ import android.content.pm.IPackageManager;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.content.pm.ParceledListSlice; import android.content.pm.ParceledListSlice;
import android.graphics.Color; import android.graphics.Color;
import android.media.AudioManager;
import android.os.Binder; import android.os.Binder;
import android.os.Process; import android.os.Process;
import android.os.UserHandle; import android.os.UserHandle;
@@ -79,7 +80,6 @@ import com.android.server.lights.LightsManager;
@RunWith(AndroidTestingRunner.class) @RunWith(AndroidTestingRunner.class)
@RunWithLooper @RunWithLooper
public class NotificationManagerServiceTest extends NotificationTestCase { public class NotificationManagerServiceTest extends NotificationTestCase {
private static final long WAIT_FOR_IDLE_TIMEOUT = 2;
private static final String TEST_CHANNEL_ID = "NotificationManagerServiceTestChannelId"; private static final String TEST_CHANNEL_ID = "NotificationManagerServiceTestChannelId";
private final int uid = Binder.getCallingUid(); private final int uid = Binder.getCallingUid();
private NotificationManagerService mNotificationManagerService; private NotificationManagerService mNotificationManagerService;
@@ -96,6 +96,8 @@ public class NotificationManagerServiceTest extends NotificationTestCase {
private RankingHelper mRankingHelper; private RankingHelper mRankingHelper;
@Mock @Mock
private NotificationUsageStats mUsageStats; private NotificationUsageStats mUsageStats;
@Mock
private AudioManager mAudioManager;
private NotificationChannel mTestNotificationChannel = new NotificationChannel( private NotificationChannel mTestNotificationChannel = new NotificationChannel(
TEST_CHANNEL_ID, TEST_CHANNEL_ID, NotificationManager.IMPORTANCE_DEFAULT); TEST_CHANNEL_ID, TEST_CHANNEL_ID, NotificationManager.IMPORTANCE_DEFAULT);
@Mock @Mock
@@ -144,16 +146,23 @@ public class NotificationManagerServiceTest extends NotificationTestCase {
.thenReturn(applicationInfo); .thenReturn(applicationInfo);
final LightsManager mockLightsManager = mock(LightsManager.class); final LightsManager mockLightsManager = mock(LightsManager.class);
when(mockLightsManager.getLight(anyInt())).thenReturn(mock(Light.class)); when(mockLightsManager.getLight(anyInt())).thenReturn(mock(Light.class));
when(mAudioManager.getRingerModeInternal()).thenReturn(AudioManager.RINGER_MODE_NORMAL);
// Use this testable looper. // Use this testable looper.
mTestableLooper = TestableLooper.get(this); mTestableLooper = TestableLooper.get(this);
mListener = mNotificationListeners.new ManagedServiceInfo( mListener = mNotificationListeners.new ManagedServiceInfo(
null, new ComponentName(PKG, "test_class"), uid, true, null, 0); null, new ComponentName(PKG, "test_class"), uid, true, null, 0);
when(mNotificationListeners.checkServiceTokenLocked(any())).thenReturn(mListener); when(mNotificationListeners.checkServiceTokenLocked(any())).thenReturn(mListener);
mNotificationManagerService.init(mTestableLooper.getLooper(), mPackageManager, try {
mPackageManagerClient, mockLightsManager, mNotificationListeners, mCompanionMgr, mNotificationManagerService.init(mTestableLooper.getLooper(), mPackageManager,
mSnoozeHelper, mUsageStats); mPackageManagerClient, mockLightsManager, mNotificationListeners,
mCompanionMgr, mSnoozeHelper, mUsageStats);
} catch (SecurityException e) {
if (!e.getMessage().contains("Permission Denial: not allowed to send broadcast")) {
throw e;
}
}
mNotificationManagerService.setAudioManager(mAudioManager);
// Tests call directly into the Binder. // Tests call directly into the Binder.
mBinderService = mNotificationManagerService.getBinderService(); mBinderService = mNotificationManagerService.getBinderService();
mInternalService = mNotificationManagerService.getInternalService(); mInternalService = mNotificationManagerService.getInternalService();