Android test automation, Android testing
Discovering Espresso for Android: how to get current activity?
When writing Espresso tests there is always a need of getting current activity while testing with Espresso for Android across multiple activities. Below is the solution:
import static android.support.test.runner.lifecycle.Stage.RESUMED; import android.support.test.internal.runner.lifecycle.ActivityLifecycleMonitorRegistry; Activity currentActivity = null; public Activity getActivityInstance(){ getInstrumentation().runOnMainSync(new Runnable() { public void run() { Collection resumedActivities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(RESUMED); if (resumedActivities.iterator().hasNext()){ currentActivity = resumedActivities.iterator().next(); } } }); return currentActivity; }
The thing is that getActivitiesInStage(Stage.RESUMED)
returns us all activities in RESUMED state, and the activity which is currently displayed on screen, will be the first one in list.