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.util.Log; 41 import android.util.LongArray; 42 43 import androidx.test.InstrumentationRegistry; 44 import androidx.test.filters.LargeTest; 45 import androidx.test.runner.AndroidJUnit4; 46 47 import com.android.compatibility.common.util.AppOpsUtils; 48 import com.android.compatibility.common.util.AppStandbyUtils; 49 import com.android.compatibility.common.util.SystemUtil; 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 110 private ComponentName mAlarmScheduler; 111 private AtomicInteger mAlarmCount; 112 private AlarmManagerDeviceConfigHelper mConfigHelper = new AlarmManagerDeviceConfigHelper(); 113 114 private final BroadcastReceiver mAlarmStateReceiver = new BroadcastReceiver() { 115 @Override 116 public void onReceive(Context context, Intent intent) { 117 mAlarmCount.getAndAdd(intent.getIntExtra(TestAlarmReceiver.EXTRA_ALARM_COUNT, 1)); 118 final long nowElapsed = SystemClock.elapsedRealtime(); 119 sAlarmHistory.addTime(nowElapsed); 120 Log.d(TAG, "No. of expirations: " + mAlarmCount + " elapsed: " + nowElapsed); 121 } 122 }; 123 124 @BeforeClass setUpTests()125 public static void setUpTests() throws Exception { 126 sAlarmHistory = new TestAlarmHistory(); 127 sOrigAppStandbyEnabled = AppStandbyUtils.isAppStandbyEnabledAtRuntime(); 128 if (!sOrigAppStandbyEnabled) { 129 AppStandbyUtils.setAppStandbyEnabledAtRuntime(true); 130 131 // Give system sometime to initialize itself. 132 Thread.sleep(100); 133 } 134 } 135 136 @Before setUp()137 public void setUp() throws Exception { 138 mAlarmScheduler = new ComponentName(TEST_APP_PACKAGE, TEST_APP_RECEIVER); 139 mAlarmCount = new AtomicInteger(0); 140 141 // To make sure it doesn't get pinned to working_set on older versions. 142 AppOpsUtils.setUidMode(Utils.getPackageUid(TEST_APP_PACKAGE), OPSTR_SCHEDULE_EXACT_ALARM, 143 MODE_IGNORED); 144 145 final IntentFilter intentFilter = new IntentFilter(); 146 intentFilter.addAction(TestAlarmReceiver.ACTION_REPORT_ALARM_EXPIRED); 147 sContext.registerReceiver(mAlarmStateReceiver, intentFilter, 148 Context.RECEIVER_EXPORTED_UNAUDITED); 149 150 setBatteryCharging(false); 151 updateAlarmManagerConstants(); 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 setPowerAllowlisted(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 setPowerAllowlisted(false); 249 } 250 251 @After tearDown()252 public void tearDown() throws Exception { 253 setPowerAllowlisted(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 for (int i = 0; i < APP_STANDBY_QUOTAS.length; i++) { 276 mConfigHelper.with(APP_BUCKET_QUOTA_KEYS[i], APP_STANDBY_QUOTAS[i]); 277 } 278 mConfigHelper.commitAndAwaitPropagation(); 279 } 280 setPowerAllowlisted(boolean whitelist)281 private void setPowerAllowlisted(boolean whitelist) throws IOException { 282 final StringBuffer cmd = new StringBuffer("cmd deviceidle whitelist "); 283 cmd.append(whitelist ? "+" : "-"); 284 cmd.append(TEST_APP_PACKAGE); 285 executeAndLog(cmd.toString()); 286 } 287 setTestAppStandbyBucket(String bucket)288 static void setTestAppStandbyBucket(String bucket) throws IOException { 289 executeAndLog("am set-standby-bucket " + TEST_APP_PACKAGE + " " + bucket); 290 } 291 setBatteryCharging(final boolean charging)292 private void setBatteryCharging(final boolean charging) throws Exception { 293 final BatteryManager bm = sContext.getSystemService(BatteryManager.class); 294 if (charging) { 295 executeAndLog("dumpsys battery reset"); 296 } else { 297 executeAndLog("dumpsys battery unplug"); 298 executeAndLog("dumpsys battery set status " + 299 BatteryManager.BATTERY_STATUS_DISCHARGING); 300 assertTrue("Battery could not be unplugged", waitUntil(() -> !bm.isCharging(), 5_000)); 301 } 302 } 303 executeAndLog(String cmd)304 private static String executeAndLog(String cmd) throws IOException { 305 final String output = SystemUtil.runShellCommand(cmd).trim(); 306 Log.d(TAG, "command: [" + cmd + "], output: [" + output + "]"); 307 return output; 308 } 309 waitForAlarm()310 private boolean waitForAlarm() throws InterruptedException { 311 final boolean success = waitUntil(() -> (mAlarmCount.get() == 1), DEFAULT_WAIT); 312 mAlarmCount.set(0); 313 return success; 314 } 315 waitUntil(BooleanSupplier condition, long timeout)316 private boolean waitUntil(BooleanSupplier condition, long timeout) throws InterruptedException { 317 final long deadLine = SystemClock.uptimeMillis() + timeout; 318 while (!condition.getAsBoolean() && SystemClock.uptimeMillis() < deadLine) { 319 Thread.sleep(POLL_INTERVAL); 320 } 321 return condition.getAsBoolean(); 322 } 323 324 private static final class TestAlarmHistory { 325 private LongArray mHistory = new LongArray(); 326 addTime(long timestamp)327 private synchronized void addTime(long timestamp) { 328 mHistory.add(timestamp); 329 } 330 331 /** 332 * Get the xth alarm time from the end. 333 */ getLast(int x)334 private synchronized long getLast(int x) { 335 if (x == 0 || x > mHistory.size()) { 336 return 0; 337 } 338 return mHistory.get(mHistory.size() - x); 339 } 340 } 341 } 342