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:

Activity currentActivity = null;

public Activity getActivityInstance(){
    getInstrumentation().runOnMainSync(new Runnable() {
        public void run() {
            Collection<Activity> resumedActivities = 
            ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED);
            for (Activity activity: resumedActivities){
                Log.d("Your current activity: ", activity.getClass().getName());
                currentActivity = activity;
                break;
            }
        }
    });

    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.

Update for Espresso 2.0 - you have to add below imports and slightly modify your method:

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;
}