Wednesday, September 10, 2014

Discovering Espresso for Android: how to get current activity?

I see a lot of questions regarding getting current activity while testing with Espresso for Android across multiple activities. Below is the solution:
public Activity getActivityInstance(){
    getInstrumentation().runOnMainSync(new Runnable() {
        public void run() {
            Collection<Activity> resumedActivities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED);
            for (Activity act: resumedActivities){
                Log.d("Your current activity: ", act.getClass().getName());
                currentActivity = act;
                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;
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;
}