I couldn't get any of the other solutions to work, so I ended up having to do this:
Declare your ActivityTestRule
:
@Rule
public ActivityTestRule<MainActivity> mainActivityTestRule =
new ActivityTestRule<>(MainActivity.class);
Declare a final
Activity array to store your activities:
private final Activity[] currentActivity = new Activity[1];
Add a helper method to register with the application context to get lifecycle updates:
private void monitorCurrentActivity() {
mainActivityTestRule.getActivity().getApplication()
.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(final Activity activity, final Bundle savedInstanceState) { }
@Override
public void onActivityStarted(final Activity activity) { }
@Override
public void onActivityResumed(final Activity activity) {
currentActivity[0] = activity;
}
@Override
public void onActivityPaused(final Activity activity) { }
@Override
public void onActivityStopped(final Activity activity) { }
@Override
public void onActivitySaveInstanceState(final Activity activity, final Bundle outState) { }
@Override
public void onActivityDestroyed(final Activity activity) { }
});
}
Add a helper method to get the current activity
private Activity getCurrentActivity() {
return currentActivity[0];
}
So, once you've launched your first activity, just call monitorCurrentActivity()
and then whenever you need a reference to the current activity you just call getCurrentActivity()