Skip to content

Instantly share code, notes, and snippets.

@logcat
Forked from tir38/CurrentActivityUtil.java
Created January 17, 2017 10:35
Show Gist options
  • Save logcat/b1e632e3394e808a23f500f266a76bfd to your computer and use it in GitHub Desktop.
Save logcat/b1e632e3394e808a23f500f266a76bfd to your computer and use it in GitHub Desktop.
import android.app.Activity;
import android.support.annotation.Nullable;
import android.support.test.runner.lifecycle.ActivityLifecycleMonitorRegistry;
import java.util.Collection;
import static android.support.test.InstrumentationRegistry.getInstrumentation;
import static android.support.test.runner.lifecycle.Stage.RESUMED;
public final class CurrentActivityUtil {
@Nullable
public static Activity getCurrentActivity() {
final Activity[] currentActivity = {null};
getInstrumentation().runOnMainSync(() -> {
Collection<Activity> resumedActivities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(RESUMED);
if (resumedActivities.iterator().hasNext()) {
currentActivity[0] = resumedActivities.iterator().next();
}
});
return currentActivity[0];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment