1 /* 2 * Copyright (C) 2019 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 package com.android.customization.testutils; 17 18 19 import android.os.SystemClock; 20 21 import org.junit.Assert; 22 23 /** 24 * A utility class for waiting for a condition to be true. 25 */ 26 public class Wait { 27 28 private static final long DEFAULT_SLEEP_MS = 200; 29 atMost(String message, Condition condition, long timeout)30 public static void atMost(String message, Condition condition, long timeout) { 31 atMost(message, condition, timeout, DEFAULT_SLEEP_MS); 32 } 33 atMost(String message, Condition condition, long timeout, long sleepMillis)34 public static void atMost(String message, Condition condition, long timeout, long sleepMillis) { 35 long endTime = SystemClock.uptimeMillis() + timeout; 36 while (SystemClock.uptimeMillis() < endTime) { 37 try { 38 if (condition.isTrue()) { 39 return; 40 } 41 } catch (Throwable t) { 42 throw new RuntimeException(t); 43 } 44 SystemClock.sleep(sleepMillis); 45 } 46 47 // Check once more before returning false. 48 try { 49 if (condition.isTrue()) { 50 return; 51 } 52 } catch (Throwable t) { 53 throw new RuntimeException(t); 54 } 55 Assert.fail(message); 56 } 57 } 58 59