1 /* 2 * Copyright (C) 2017 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 17 package android.alarmmanager.cts; 18 19 import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP; 20 import static android.app.AppOpsManager.MODE_IGNORED; 21 import static android.app.AppOpsManager.OPSTR_SCHEDULE_EXACT_ALARM; 22 23 import static org.junit.Assert.assertFalse; 24 import static org.junit.Assert.assertTrue; 25 import static org.junit.Assume.assumeTrue; 26 27 import android.alarmmanager.alarmtestapp.cts.TestAlarmReceiver; 28 import android.alarmmanager.alarmtestapp.cts.TestAlarmScheduler; 29 import android.alarmmanager.util.AlarmManagerDeviceConfigHelper; 30 import android.alarmmanager.util.Utils; 31 import android.app.Activity; 32 import android.content.BroadcastReceiver; 33 import android.content.ComponentName; 34 import android.content.Context; 35 import android.content.Intent; 36 import android.content.IntentFilter; 37 import android.os.BatteryManager; 38 import android.os.SystemClock; 39 import android.platform.test.annotations.AppModeFull; 40 import android.support.test.uiautomator.UiDevice; 41 import android.util.Log; 42 import android.util.LongArray; 43 44 import androidx.test.InstrumentationRegistry; 45 import androidx.test.filters.LargeTest; 46 import androidx.test.runner.AndroidJUnit4; 47 48 import com.android.compatibility.common.util.AppOpsUtils; 49 import com.android.compatibility.common.util.AppStandbyUtils; 50 51 import org.junit.After; 52 import org.junit.AfterClass; 53 import org.junit.Before; 54 import org.junit.BeforeClass; 55 import org.junit.Test; 56 import org.junit.runner.RunWith; 57 58 import java.io.IOException; 59 import java.util.concurrent.CountDownLatch; 60 import java.util.concurrent.TimeUnit; 61 import java.util.concurrent.atomic.AtomicInteger; 62 import java.util.function.BooleanSupplier; 63 64 /** 65 * Tests that app standby imposes the appropriate restrictions on alarms 66 */ 67 @AppModeFull 68 @LargeTest 69 @RunWith(AndroidJUnit4.class) 70 public class AppStandbyTests { 71 private static final String TAG = AppStandbyTests.class.getSimpleName(); 72 static final String TEST_APP_PACKAGE = "android.alarmmanager.alarmtestapp.cts"; 73 private static final String TEST_APP_RECEIVER = TEST_APP_PACKAGE + ".TestAlarmScheduler"; 74 75 private static final long DEFAULT_WAIT = 2_000; 76 private static final long POLL_INTERVAL = 200; 77 78 // Tweaked alarm manager constants to facilitate testing 79 private static final long MIN_FUTURITY = 1_000; 80 81 // Not touching ACTIVE and RARE parameters for this test 82 private static final int WORKING_INDEX = 0; 83 private static final int FREQUENT_INDEX = 1; 84 private static final int RARE_INDEX = 2; 85 private static final String[] APP_BUCKET_TAGS = { 86 "working_set", 87 "frequent", 88 "rare", 89 }; 90 91 private static final long APP_STANDBY_WINDOW = 10_000; 92 private static final long MIN_WINDOW = 100; 93 private static final String[] APP_BUCKET_QUOTA_KEYS = { 94 "standby_quota_working", 95 "standby_quota_frequent", 96 "standby_quota_rare", 97 }; 98 private static final int[] APP_STANDBY_QUOTAS = { 99 5, // Working set 100 3, // Frequent 101 1, // Rare 102 }; 103 104 // Save the state before running tests to restore it after we finish testing. 105 private static boolean sOrigAppStandbyEnabled; 106 // Test app's alarm history to help predict when a subsequent alarm is going to get deferred. 107 private static TestAlarmHistory sAlarmHistory; 108 private static Context sContext = InstrumentationRegistry.getTargetContext(); 109 private static UiDevice sUiDevice = UiDevice.getInstance( 110 InstrumentationRegistry.getInstrumentation()); 111 112 private ComponentName mAlarmScheduler; 113 private AtomicInteger mAlarmCount; 114 private AlarmManagerDeviceConfigHelper mConfigHelper = new AlarmManagerDeviceConfigHelper(); 115 116 private final BroadcastReceiver mAlarmStateReceiver = new BroadcastReceiver() { 117 @Override 118 public void onReceive(Context context, Intent intent) { 119 mAlarmCount.getAndAdd(intent.getIntExtra(TestAlarmReceiver.EXTRA_ALARM_COUNT, 1)); 120 final long nowElapsed = SystemClock.elapsedRealtime(); 121 sAlarmHistory.addTime(nowElapsed); 122 Log.d(TAG, "No. of expirations: " + mAlarmCount + " elapsed: " + nowElapsed); 123 } 124 }; 125 126 @BeforeClass setUpTests()127 public static void setUpTests() throws Exception { 128 sAlarmHistory = new TestAlarmHistory(); 129 sOrigAppStandbyEnabled = AppStandbyUtils.isAppStandbyEnabledAtRuntime(); 130 if (!sOrigAppStandbyEnabled) { 131 AppStandbyUtils.setAppStandbyEnabledAtRuntime(true); 132 133 // Give system sometime to initialize itself. 134 Thread.sleep(100); 135 } 136 } 137 138 @Before setUp()139 public void setUp() throws Exception { 140 mAlarmScheduler = new ComponentName(TEST_APP_PACKAGE, TEST_APP_RECEIVER); 141 mAlarmCount = new AtomicInteger(0); 142 updateAlarmManagerConstants(); 143 setBatteryCharging(false); 144 145 // To make sure it doesn't get pinned to working_set on older versions. 146 AppOpsUtils.setUidMode(Utils.getPackageUid(TEST_APP_PACKAGE), OPSTR_SCHEDULE_EXACT_ALARM, 147 MODE_IGNORED); 148 149 final IntentFilter intentFilter = new IntentFilter(); 150 intentFilter.addAction(TestAlarmReceiver.ACTION_REPORT_ALARM_EXPIRED); 151 sContext.registerReceiver(mAlarmStateReceiver, intentFilter); 152 assumeTrue("App Standby not enabled on device", AppStandbyUtils.isAppStandbyEnabled()); 153 } 154 scheduleAlarm(long triggerMillis, long interval)155 private void scheduleAlarm(long triggerMillis, long interval) throws InterruptedException { 156 final Intent setAlarmIntent = new Intent(TestAlarmScheduler.ACTION_SET_ALARM); 157 setAlarmIntent.setComponent(mAlarmScheduler); 158 setAlarmIntent.putExtra(TestAlarmScheduler.EXTRA_TYPE, ELAPSED_REALTIME_WAKEUP); 159 setAlarmIntent.putExtra(TestAlarmScheduler.EXTRA_TRIGGER_TIME, triggerMillis); 160 setAlarmIntent.putExtra(TestAlarmScheduler.EXTRA_WINDOW_LENGTH, MIN_WINDOW); 161 setAlarmIntent.putExtra(TestAlarmScheduler.EXTRA_REPEAT_INTERVAL, interval); 162 setAlarmIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 163 final CountDownLatch resultLatch = new CountDownLatch(1); 164 sContext.sendOrderedBroadcast(setAlarmIntent, null, new BroadcastReceiver() { 165 @Override 166 public void onReceive(Context context, Intent intent) { 167 resultLatch.countDown(); 168 } 169 }, null, Activity.RESULT_CANCELED, null, null); 170 assertTrue("Request did not complete", resultLatch.await(10, TimeUnit.SECONDS)); 171 } 172 testSimpleQuotaDeferral(int bucketIndex)173 public void testSimpleQuotaDeferral(int bucketIndex) throws Exception { 174 setTestAppStandbyBucket(APP_BUCKET_TAGS[bucketIndex]); 175 final int quota = APP_STANDBY_QUOTAS[bucketIndex]; 176 177 long startElapsed = SystemClock.elapsedRealtime(); 178 final long freshWindowPoint = sAlarmHistory.getLast(1) + APP_STANDBY_WINDOW; 179 if (freshWindowPoint > startElapsed) { 180 Thread.sleep(freshWindowPoint - startElapsed); 181 startElapsed = freshWindowPoint; 182 // Now we should have no alarms in the past APP_STANDBY_WINDOW 183 } 184 final long desiredTrigger = startElapsed + APP_STANDBY_WINDOW; 185 final long firstTrigger = startElapsed + 4_000; 186 assertTrue("Quota too large for test", 187 firstTrigger + ((quota - 1) * MIN_FUTURITY) < desiredTrigger); 188 for (int i = 0; i < quota; i++) { 189 final long trigger = firstTrigger + (i * MIN_FUTURITY); 190 scheduleAlarm(trigger, 0); 191 Thread.sleep(trigger - SystemClock.elapsedRealtime()); 192 assertTrue("Alarm within quota not firing as expected", waitForAlarm()); 193 } 194 195 // Now quota is reached, any subsequent alarm should get deferred. 196 scheduleAlarm(desiredTrigger, 0); 197 Thread.sleep(desiredTrigger - SystemClock.elapsedRealtime()); 198 assertFalse("Alarm exceeding quota not deferred", waitForAlarm()); 199 final long minTrigger = firstTrigger + APP_STANDBY_WINDOW; 200 Thread.sleep(minTrigger - SystemClock.elapsedRealtime()); 201 assertTrue("Alarm exceeding quota not delivered after expected delay", waitForAlarm()); 202 } 203 204 @Test testActiveQuota()205 public void testActiveQuota() throws Exception { 206 setTestAppStandbyBucket("active"); 207 long nextTrigger = SystemClock.elapsedRealtime() + MIN_FUTURITY; 208 for (int i = 0; i < 3; i++) { 209 scheduleAlarm(nextTrigger, 0); 210 Thread.sleep(MIN_FUTURITY); 211 assertTrue("Alarm not received as expected when app is in active", waitForAlarm()); 212 nextTrigger += MIN_FUTURITY; 213 } 214 } 215 216 @Test testWorkingQuota()217 public void testWorkingQuota() throws Exception { 218 testSimpleQuotaDeferral(WORKING_INDEX); 219 } 220 221 @Test testFrequentQuota()222 public void testFrequentQuota() throws Exception { 223 testSimpleQuotaDeferral(FREQUENT_INDEX); 224 } 225 226 @Test testRareQuota()227 public void testRareQuota() throws Exception { 228 testSimpleQuotaDeferral(RARE_INDEX); 229 } 230 231 @Test testNeverQuota()232 public void testNeverQuota() throws Exception { 233 setTestAppStandbyBucket("never"); 234 final long expectedTrigger = SystemClock.elapsedRealtime() + MIN_FUTURITY; 235 scheduleAlarm(expectedTrigger, 0); 236 Thread.sleep(10_000); 237 assertFalse("Alarm received when app was in never bucket", waitForAlarm()); 238 } 239 240 @Test testPowerWhitelistedAlarmNotBlocked()241 public void testPowerWhitelistedAlarmNotBlocked() throws Exception { 242 setTestAppStandbyBucket(APP_BUCKET_TAGS[RARE_INDEX]); 243 setPowerWhitelisted(true); 244 final long triggerTime = SystemClock.elapsedRealtime() + MIN_FUTURITY; 245 scheduleAlarm(triggerTime, 0); 246 Thread.sleep(MIN_FUTURITY); 247 assertTrue("Alarm did not go off for whitelisted app in rare bucket", waitForAlarm()); 248 setPowerWhitelisted(false); 249 } 250 251 @After tearDown()252 public void tearDown() throws Exception { 253 setPowerWhitelisted(false); 254 setBatteryCharging(true); 255 mConfigHelper.restoreAll(); 256 final Intent cancelAlarmsIntent = new Intent(TestAlarmScheduler.ACTION_CANCEL_ALL_ALARMS); 257 cancelAlarmsIntent.setComponent(mAlarmScheduler); 258 sContext.sendBroadcast(cancelAlarmsIntent); 259 sContext.unregisterReceiver(mAlarmStateReceiver); 260 // Broadcast unregister may race with the next register in setUp 261 Thread.sleep(500); 262 } 263 264 @AfterClass tearDownTests()265 public static void tearDownTests() throws Exception { 266 if (!sOrigAppStandbyEnabled) { 267 AppStandbyUtils.setAppStandbyEnabledAtRuntime(sOrigAppStandbyEnabled); 268 } 269 } 270 updateAlarmManagerConstants()271 private void updateAlarmManagerConstants() { 272 mConfigHelper.with("min_futurity", MIN_FUTURITY) 273 .with("app_standby_window", APP_STANDBY_WINDOW) 274 .with("min_window", MIN_WINDOW) 275 .with("exact_alarm_deny_list", TEST_APP_PACKAGE); 276 for (int i = 0; i < APP_STANDBY_QUOTAS.length; i++) { 277 mConfigHelper.with(APP_BUCKET_QUOTA_KEYS[i], APP_STANDBY_QUOTAS[i]); 278 } 279 mConfigHelper.commitAndAwaitPropagation(); 280 } 281 setPowerWhitelisted(boolean whitelist)282 private void setPowerWhitelisted(boolean whitelist) throws IOException { 283 final StringBuffer cmd = new StringBuffer("cmd deviceidle whitelist "); 284 cmd.append(whitelist ? "+" : "-"); 285 cmd.append(TEST_APP_PACKAGE); 286 executeAndLog(cmd.toString()); 287 } 288 setTestAppStandbyBucket(String bucket)289 static void setTestAppStandbyBucket(String bucket) throws IOException { 290 executeAndLog("am set-standby-bucket " + TEST_APP_PACKAGE + " " + bucket); 291 } 292 setBatteryCharging(final boolean charging)293 private void setBatteryCharging(final boolean charging) throws Exception { 294 final BatteryManager bm = sContext.getSystemService(BatteryManager.class); 295 if (charging) { 296 executeAndLog("dumpsys battery reset"); 297 } else { 298 executeAndLog("dumpsys battery unplug"); 299 executeAndLog("dumpsys battery set status " + 300 BatteryManager.BATTERY_STATUS_DISCHARGING); 301 assertTrue("Battery could not be unplugged", waitUntil(() -> !bm.isCharging(), 5_000)); 302 } 303 } 304 executeAndLog(String cmd)305 private static String executeAndLog(String cmd) throws IOException { 306 final String output = sUiDevice.executeShellCommand(cmd).trim(); 307 Log.d(TAG, "command: [" + cmd + "], output: [" + output + "]"); 308 return output; 309 } 310 waitForAlarm()311 private boolean waitForAlarm() throws InterruptedException { 312 final boolean success = waitUntil(() -> (mAlarmCount.get() == 1), DEFAULT_WAIT); 313 mAlarmCount.set(0); 314 return success; 315 } 316 waitUntil(BooleanSupplier condition, long timeout)317 private boolean waitUntil(BooleanSupplier condition, long timeout) throws InterruptedException { 318 final long deadLine = SystemClock.uptimeMillis() + timeout; 319 while (!condition.getAsBoolean() && SystemClock.uptimeMillis() < deadLine) { 320 Thread.sleep(POLL_INTERVAL); 321 } 322 return condition.getAsBoolean(); 323 } 324 325 private static final class TestAlarmHistory { 326 private LongArray mHistory = new LongArray(); 327 addTime(long timestamp)328 private synchronized void addTime(long timestamp) { 329 mHistory.add(timestamp); 330 } 331 332 /** 333 * Get the xth alarm time from the end. 334 */ getLast(int x)335 private synchronized long getLast(int x) { 336 if (x == 0 || x > mHistory.size()) { 337 return 0; 338 } 339 return mHistory.get(mHistory.size() - x); 340 } 341 } 342 } 343