Example usage for android.app Instrumentation addMonitor

List of usage examples for android.app Instrumentation addMonitor

Introduction

In this page you can find the example usage for android.app Instrumentation addMonitor.

Prototype

public void addMonitor(ActivityMonitor monitor) 

Source Link

Document

Add a new ActivityMonitor that will be checked whenever an activity is started.

Usage

From source file:android.arch.lifecycle.TestUtils.java

@SuppressWarnings("unchecked")
static <T extends Activity> T recreateActivity(final T activity, ActivityTestRule rule) throws Throwable {
    ActivityMonitor monitor = new ActivityMonitor(activity.getClass().getCanonicalName(), null, false);
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    instrumentation.addMonitor(monitor);
    rule.runOnUiThread(activity::recreate);
    T result;//from w  w w .j a va2s. co m

    // this guarantee that we will reinstall monitor between notifications about onDestroy
    // and onCreate
    //noinspection SynchronizationOnLocalVariableOrMethodParameter
    synchronized (monitor) {
        do {
            // the documetation says "Block until an Activity is created
            // that matches this monitor." This statement is true, but there are some other
            // true statements like: "Block until an Activity is destoyed" or
            // "Block until an Activity is resumed"...

            // this call will release synchronization monitor's monitor
            result = (T) monitor.waitForActivityWithTimeout(TIMEOUT_MS);
            if (result == null) {
                throw new RuntimeException("Timeout. Failed to recreate an activity");
            }
        } while (result == activity);
    }
    return result;
}