1 /* 2 * Copyright (C) 2024 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 android.app.appsearch.testutil.functions; 17 18 import android.app.Activity; 19 import android.os.Bundle; 20 21 import androidx.annotation.Nullable; 22 23 import java.util.concurrent.CountDownLatch; 24 import java.util.concurrent.TimeUnit; 25 26 /** An activity class that enables waiting for its own creation. */ 27 public class ActivityCreationSynchronizer extends Activity { 28 29 private static volatile CountDownLatch sLatch = new CountDownLatch(1); 30 31 /** 32 * Called within the Activity's onCreate() lifecycle method. 33 * Signals that the Activity has been fully created. 34 */ 35 @Override onCreate(@ullable Bundle savedInstanceState)36 protected void onCreate(@Nullable Bundle savedInstanceState) { 37 super.onCreate(savedInstanceState); 38 sLatch.countDown(); 39 finish(); 40 } 41 42 /** 43 * Resets the latch and enables another wait cycle. Should never call this with 44 * {@link #waitForActivityCreated} in parallel. 45 */ reset()46 public static void reset() { 47 sLatch = new CountDownLatch(1); 48 } 49 50 /** 51 * Blocks the current thread until the Activity is created or the specified timeout elapses. 52 * Should never call this with {@link #reset()} in parallel. 53 * 54 * @param timeout The duration to wait for Activity creation. 55 * @param unit The unit of time for the timeout value. 56 * @return True if the Activity was created within the timeout, false otherwise. 57 * @throws InterruptedException If the current thread is interrupted while waiting. 58 */ waitForActivityCreated(long timeout, TimeUnit unit)59 public static boolean waitForActivityCreated(long timeout, TimeUnit unit) 60 throws InterruptedException { 61 return sLatch.await(timeout, unit); 62 } 63 } 64