androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry Java Examples
The following examples show how to use
androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RootMatchers.java From android-test with Apache License 2.0 | 6 votes |
private static List<IBinder> getResumedActivityTokens() { ActivityLifecycleMonitor activityLifecycleMonitor = ActivityLifecycleMonitorRegistry.getInstance(); Collection<Activity> resumedActivities = activityLifecycleMonitor.getActivitiesInStage(Stage.RESUMED); if (resumedActivities.isEmpty()) { Log.w( TAG, "suppressed: NoActivityResumedException(\"At least one activity should" + " be in RESUMED stage.\""); } List<IBinder> tokens = Lists.newArrayList(); for (Activity activity : resumedActivities) { tokens.add(activity.getWindow().getDecorView().getApplicationWindowToken()); } return tokens; }
Example #2
Source File: ViewInteractionTest.java From android-test with Apache License 2.0 | 6 votes |
@Before public void setUp() throws Exception { initMocks(this); realLifecycleMonitor = ActivityLifecycleMonitorRegistry.getInstance(); rootView = new View(getInstrumentation().getContext()); targetView = new View(getInstrumentation().getContext()); viewMatcher = is(targetView); actionConstraint = notNullValue(View.class); rootMatcherRef = new AtomicReference<>(RootMatchers.DEFAULT); needsActivity = new AtomicReference<>(false); when(mockAction.getDescription()).thenReturn("A Mock!"); failureHandler = new FailureHandler() { @Override public void handle(Throwable error, Matcher<View> viewMatcher) { throwIfUnchecked(error); throw new RuntimeException(error); } }; when(mockRemoteInteraction.isRemoteProcess()).thenReturn(true); }
Example #3
Source File: MonitoringInstrumentation.java From android-test with Apache License 2.0 | 6 votes |
/** * Ensures all activities launched in this instrumentation are finished before the instrumentation * exits. * * <p>Subclasses who override this method should do their finish processing and then call * super.finish to invoke this logic. Not waiting for all activities to finish() before exiting * can cause device wide instability. */ @Override public void finish(int resultCode, Bundle results) { if (finished) { Log.w(TAG, "finish called 2x!"); return; } else { finished = true; } if (shouldWaitForActivitiesToComplete()) { handlerForMainLooper.post(new ActivityFinisher()); long startTime = System.currentTimeMillis(); waitForActivitiesToComplete(); long endTime = System.currentTimeMillis(); Log.i(TAG, String.format("waitForActivitiesToComplete() took: %sms", endTime - startTime)); } ActivityLifecycleMonitorRegistry.registerInstance(null); restoreUncaughtExceptionHandler(); super.finish(resultCode, results); }
Example #4
Source File: TestUtil.java From prebid-mobile-android with Apache License 2.0 | 5 votes |
static Activity getCurrentActivity() { final Activity[] currentActivity = {null}; getInstrumentation().runOnMainSync(new Runnable() { public void run() { Collection<Activity> resumedActivity = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED); Iterator<Activity> it = resumedActivity.iterator(); currentActivity[0] = it.next(); } }); return currentActivity[0]; }
Example #5
Source File: EspressoUtil.java From LocaleChanger with Apache License 2.0 | 5 votes |
public static Activity getCurrentActivity() { final Activity[] currentActivity = {null}; Collection resumedActivities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(RESUMED); if (resumedActivities.iterator().hasNext()) { currentActivity[0] = (Activity) resumedActivities.iterator().next(); } return currentActivity[0]; }
Example #6
Source File: CloseKeyboardAction.java From android-test with Apache License 2.0 | 5 votes |
private static Activity getRootActivity(UiController uiController) { Collection<Activity> resumedActivities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED); if (resumedActivities.isEmpty()) { uiController.loopMainThreadUntilIdle(); resumedActivities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED); } checkState( resumedActivities.size() == 1, "More than one activity is in RESUMED stage." + " There may have been an error during the activity creation/startup process," + " please check your logs."); return getOnlyElement(resumedActivities); }
Example #7
Source File: KeyEventActionBase.java From android-test with Apache License 2.0 | 5 votes |
static void waitForPendingForegroundActivities(UiController controller, boolean conditional) { ActivityLifecycleMonitor activityLifecycleMonitor = ActivityLifecycleMonitorRegistry.getInstance(); boolean pendingForegroundActivities = false; for (int attempts = 0; attempts < CLEAR_TRANSITIONING_ACTIVITIES_ATTEMPTS; attempts++) { controller.loopMainThreadUntilIdle(); pendingForegroundActivities = hasTransitioningActivities(activityLifecycleMonitor); if (pendingForegroundActivities) { controller.loopMainThreadForAtLeast(CLEAR_TRANSITIONING_ACTIVITIES_MILLIS_DELAY); } else { break; } } // Pressing back can kill the app: log a warning. if (!hasForegroundActivities(activityLifecycleMonitor)) { if (conditional) { throw new NoActivityResumedException("Pressed back and killed the app"); } Log.w(TAG, "Pressed back and hopped to a different process or potentially killed the app"); } if (pendingForegroundActivities) { Log.w( TAG, "Back was pressed and left the application in an inconsistent state even after " + (CLEAR_TRANSITIONING_ACTIVITIES_MILLIS_DELAY * CLEAR_TRANSITIONING_ACTIVITIES_ATTEMPTS) + "ms."); } }
Example #8
Source File: InstrumentationActivityInvoker.java From android-test with Apache License 2.0 | 5 votes |
private static void checkActivityStageIsIn(Activity activity, Set<Stage> expected) { getInstrumentation() .runOnMainSync( () -> { Stage stage = ActivityLifecycleMonitorRegistry.getInstance().getLifecycleStageOf(activity); checkState( expected.contains(stage), "Activity's stage must be %s but was %s", expected, stage); }); }
Example #9
Source File: ActivityScenario.java From android-test with Apache License 2.0 | 5 votes |
/** * An internal helper method to perform initial launch operation for the given scenario instance * along with preconditions checks around device's configuration. * * @param activityOptions activity options bundle to be passed when launching this activity */ private void launchInternal(@Nullable Bundle activityOptions) { checkState( Settings.System.getInt( getInstrumentation().getTargetContext().getContentResolver(), Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0) == 0, "\"Don't keep activities\" developer options must be disabled for ActivityScenario"); checkNotMainThread(); getInstrumentation().waitForIdleSync(); ActivityLifecycleMonitorRegistry.getInstance().addLifecycleCallback(activityLifecycleObserver); // prefer the single argument variant for startActivity for backwards compatibility with older // Robolectric versions if (activityOptions == null) { activityInvoker.startActivity(startActivityIntent); } else { activityInvoker.startActivity(startActivityIntent, activityOptions); } // Accept any steady states. An activity may start another activity in its onCreate method. Such // an activity goes back to created or started state immediately after it is resumed. waitForActivityToBecomeAnyOf(STEADY_STATES.values().toArray(new State[0])); }
Example #10
Source File: ActivityTestRule.java From android-test with Apache License 2.0 | 5 votes |
@Override public void evaluate() throws Throwable { MonitoringInstrumentation instrumentation = ActivityTestRule.this.instrumentation instanceof MonitoringInstrumentation ? (MonitoringInstrumentation) ActivityTestRule.this.instrumentation : null; try { if (activityFactory != null && instrumentation != null) { instrumentation.interceptActivityUsing(activityFactory); } if (launchActivity) { launchActivity(getActivityIntent()); } base.evaluate(); } finally { if (instrumentation != null) { instrumentation.useDefaultInterceptingActivityFactory(); } T hardActivityRef = activity.get(); if (hardActivityRef != null) { finishActivity(); } activityResult = null; ActivityLifecycleMonitorRegistry.getInstance().removeLifecycleCallback(lifecycleCallback); } }
Example #11
Source File: MonitoringInstrumentation.java From android-test with Apache License 2.0 | 5 votes |
/** * Sets up lifecycle monitoring, and argument registry. * * <p>Subclasses must call up to onCreate(). This onCreate method does not call start() it is the * subclasses responsibility to call start if it desires. */ @Override public void onCreate(Bundle arguments) { Log.i(TAG, "Instrumentation started!"); logUncaughtExceptions(); // Multidex must be installed early otherwise we could call into code that has // landed in a different dex split. installMultidex(); InstrumentationRegistry.registerInstance(this, arguments); androidx.test.InstrumentationRegistry.registerInstance(this, arguments); ActivityLifecycleMonitorRegistry.registerInstance(lifecycleMonitor); ApplicationLifecycleMonitorRegistry.registerInstance(applicationMonitor); IntentMonitorRegistry.registerInstance(intentMonitor); handlerForMainLooper = new Handler(Looper.getMainLooper()); final int corePoolSize = 0; final long keepAliveTime = 0L; executorService = new ThreadPoolExecutor( corePoolSize, Integer.MAX_VALUE, keepAliveTime, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new ThreadFactory() { @Override public Thread newThread(Runnable runnable) { Thread thread = Executors.defaultThreadFactory().newThread(runnable); thread.setName(MonitoringInstrumentation.class.getSimpleName()); return thread; } }); Looper.myQueue().addIdleHandler(idleHandler); super.onCreate(arguments); specifyDexMakerCacheProperty(); setupDexmakerClassloader(); useDefaultInterceptingActivityFactory(); }
Example #12
Source File: ActivityScenarioRuleTest.java From android-test with Apache License 2.0 | 4 votes |
private static Stage lastLifeCycleTransition(Activity activity) { return ActivityLifecycleMonitorRegistry.getInstance().getLifecycleStageOf(activity); }
Example #13
Source File: ActivityIdlingResosurce.java From adamant-android with GNU General Public License v3.0 | 4 votes |
public ActivityIdlingResosurce(String activityToWaitClassName) { instance = ActivityLifecycleMonitorRegistry.getInstance(); this.activityToWaitClassName = activityToWaitClassName; }
Example #14
Source File: ActivityScenarioRuleWithCustomIntentTest.java From android-test with Apache License 2.0 | 4 votes |
private static Stage lastLifeCycleTransition(Activity activity) { return ActivityLifecycleMonitorRegistry.getInstance().getLifecycleStageOf(activity); }
Example #15
Source File: ActivityScenarioTest.java From android-test with Apache License 2.0 | 4 votes |
private static Stage lastLifeCycleTransition(Activity activity) { return ActivityLifecycleMonitorRegistry.getInstance().getLifecycleStageOf(activity); }
Example #16
Source File: AndroidJUnitRunnerLifeCycleTest.java From android-test with Apache License 2.0 | 4 votes |
@Override protected void setUp() throws Exception { super.setUp(); monitor = ActivityLifecycleMonitorRegistry.getInstance(); monitor.addLifecycleCallback(callback); }
Example #17
Source File: ViewInteractionTest.java From android-test with Apache License 2.0 | 4 votes |
@After public void tearDown() throws Exception { ActivityLifecycleMonitorRegistry.registerInstance(realLifecycleMonitor); }
Example #18
Source File: EventInjectorTest.java From android-test with Apache License 2.0 | 4 votes |
@Test public void injectMotionEvent_upEventFailure() throws InterruptedException { final CountDownLatch activityStarted = new CountDownLatch(1); ActivityLifecycleCallback callback = new ActivityLifecycleCallback() { @Override public void onActivityLifecycleChanged(Activity activity, Stage stage) { if (Stage.RESUMED == stage && activity instanceof SendActivity) { activityStarted.countDown(); } } }; ActivityLifecycleMonitorRegistry.getInstance().addLifecycleCallback(callback); try { ActivityScenario activityScenario = ActivityScenario.launch(SendActivity.class); assertTrue(activityStarted.await(20, TimeUnit.SECONDS)); final int[] xy = CoordinatesUtil.getCoordinatesInMiddleOfSendButton(activityScenario); getInstrumentation() .runOnMainSync( new Runnable() { @Override public void run() { MotionEvent up = MotionEvent.obtain( SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, xy[0], xy[1], 0); try { injectEventWorked.set(injector.injectMotionEvent(up)); } catch (InjectEventSecurityException e) { Log.e(TAG, "injectEvent threw a SecurityException"); } up.recycle(); latch.countDown(); } }); latch.await(10, TimeUnit.SECONDS); assertFalse(injectEventWorked.get()); } finally { ActivityLifecycleMonitorRegistry.getInstance().removeLifecycleCallback(callback); } }
Example #19
Source File: KeyEventActionBase.java From android-test with Apache License 2.0 | 4 votes |
private static boolean isActivityResumed(Activity activity) { return ActivityLifecycleMonitorRegistry.getInstance().getLifecycleStageOf(activity) == Stage.RESUMED; }
Example #20
Source File: KeyEventActionBase.java From android-test with Apache License 2.0 | 4 votes |
static Activity getCurrentActivity() { Collection<Activity> resumedActivities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED); return getOnlyElement(resumedActivities); }
Example #21
Source File: BaseLayerModule.java From android-test with Apache License 2.0 | 4 votes |
@Provides public ActivityLifecycleMonitor provideLifecycleMonitor() { return ActivityLifecycleMonitorRegistry.getInstance(); }
Example #22
Source File: ActivityScenario.java From android-test with Apache License 2.0 | 3 votes |
/** * Finishes the managed activity and cleans up device's state. This method blocks execution until * the activity becomes {@link State#DESTROYED}. * * <p>It is highly recommended to call this method after you test is done to keep the device state * clean although this is optional. * * <p>You may call this method more than once. If the activity has been finished already, this * method does nothing. * * <p>Avoid calling this method directly. Consider one of the following options instead: * * <pre>{@code * Option 1, use try-with-resources: * * try (ActivityScenario<MyActivity> scenario = ActivityScenario.launch(MyActivity.class)) { * // Your test code goes here. * } * * Option 2, use ActivityScenarioRule: * * }{@literal @Rule} {@code * public ActivityScenarioRule<MyActivity> rule = new ActivityScenarioRule<>(MyActivity.class); * * }{@literal @Test}{@code * public void myTest() { * ActivityScenario<MyActivity> scenario = rule.getScenario(); * // Your test code goes here. * } * }</pre> */ @Override public void close() { moveToState(State.DESTROYED); ActivityLifecycleMonitorRegistry.getInstance() .removeLifecycleCallback(activityLifecycleObserver); }