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