UiUtils.java revision 5d1f7b1de12d16ceb2c938c56701a3e8bfa558f7
1// Copyright 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5package org.chromium.content.browser.test.util;
6
7import android.app.Activity;
8import android.app.Instrumentation;
9
10import junit.framework.Assert;
11
12import static org.chromium.base.test.util.ScalableTimeout.scaleTimeout;
13
14import java.util.concurrent.Semaphore;
15import java.util.concurrent.TimeUnit;
16
17/**
18 * Collection of UI utilities.
19 */
20public class UiUtils {
21    // timeout to wait for runOnUiThread()
22    private static final long WAIT_FOR_RESPONSE_MS = scaleTimeout(10000);
23
24    /**
25     * Runs the runnable on the UI thread.
26     *
27     * @param activity The activity on which the runnable must run.
28     * @param runnable The runnable to run.
29     */
30    public static void runOnUiThread(Activity activity, final Runnable runnable) {
31        final Semaphore finishedSemaphore = new Semaphore(0);
32        activity.runOnUiThread(new Runnable() {
33            @Override
34            public void run() {
35                runnable.run();
36                finishedSemaphore.release();
37            }
38        });
39        try {
40            Assert.assertTrue(finishedSemaphore.tryAcquire(1, WAIT_FOR_RESPONSE_MS,
41                    TimeUnit.MILLISECONDS));
42        } catch (InterruptedException ignored) {
43            Assert.assertTrue("Interrupted while waiting for main thread Runnable", false);
44        }
45    }
46
47    /**
48     * Waits for the UI thread to settle down.
49     * <p>
50     * Waits for an extra period of time after the UI loop is idle.
51     *
52     * @param instrumentation Instrumentation object used by the test.
53     */
54    public static void settleDownUI(Instrumentation instrumentation) throws InterruptedException {
55        instrumentation.waitForIdleSync();
56        Thread.sleep(1000);
57    }
58}
59