1 /*
2  * Copyright 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 package com.android.managedprovisioning.testcommon;
17 
18 import android.app.Activity;
19 
20 import androidx.annotation.WorkerThread;
21 import androidx.test.runner.lifecycle.ActivityLifecycleCallback;
22 import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry;
23 import androidx.test.runner.lifecycle.Stage;
24 
25 import java.util.concurrent.CountDownLatch;
26 import java.util.concurrent.TimeUnit;
27 
28 public class ActivityLifecycleWaiter implements ActivityLifecycleCallback {
29     private final CountDownLatch mLatch = new CountDownLatch(1);
30     private final Activity mActivity;
31     private final Stage mStage;
32 
ActivityLifecycleWaiter(Activity activity, Stage stage)33     public ActivityLifecycleWaiter(Activity activity, Stage stage) {
34         mActivity = activity;
35         mStage = stage;
36         ActivityLifecycleMonitorRegistry.getInstance().addLifecycleCallback(this);
37     }
38 
39     @Override
onActivityLifecycleChanged(Activity activity, Stage stage)40     public void onActivityLifecycleChanged(Activity activity, Stage stage) {
41         if (activity == mActivity && stage == mStage) {
42             mLatch.countDown();
43         }
44     }
45 
46     @WorkerThread
waitForStage()47     public void waitForStage() throws InterruptedException {
48         waitForStage(5000L);
49     }
50 
51     @WorkerThread
waitForStage(long millis)52     public void waitForStage(long millis) throws InterruptedException {
53         try {
54             mLatch.await(millis, TimeUnit.MILLISECONDS);
55         } finally {
56             ActivityLifecycleMonitorRegistry.getInstance().removeLifecycleCallback(this);
57         }
58     }
59 }
60