Restart Android Activity with ActivityScenario
I was writing an instrumentation test which required restarting the activity during a test. As I was trying out the ActivityScenarioRule to replace an ActivityTestRule, the documentation says I can use this method on the ActivityScenario to restart the activity after it has been launched:
1 | scenario.recreate() |
So I wrote this function to for restarting the activity:
1 2 3 4 5 6 7 | @Rule @JvmField var rule = ActivityScenarioRule(MyActivity:: class .java) fun restartActivity() { var scenario = rule.getScenario() scenario.recreate() } |
However I was getting an error message for androidx.test.core.app.InstrumentationActivityInvoker.
In source code for InstrumentationActivityInvoker, looking at the method recreateActivity(), the comments section explains why there may be some indeterminate behaviour depending on the state of the activity and the version of Android being run on.
Recreates the Activity by {@link Activity#recreate}.
Note that {@link Activity#recreate}’s behavior differs by Android framework version. For example, the version P brings Activity’s lifecycle state to the original state after the re-creation. A stopped Activity goes to stopped state after the re-creation in concrete.
Whereas the version O ignores {@link Activity#recreate} method call when the activity is in stopped state. The version N re-creates stopped Activity but brings back to paused state instead of stopped.In short, make sure to set Activity’s state to resumed before calling this method otherwise the behavior is the framework version dependent.
So for my particular test, the recreate() method wasn’t working (although it might have worked for someone else for a different test).
A simple change to my function fixed this problem:
1 2 3 4 5 | fun restartActivity() { var scenario = rule.getScenario() scenario.moveToState(Lifecycle.State.RESUMED) scenario.recreate() } |
Of course it seems that ActivityScenario and ActivityScenarioRule are still a bit of a work in progress for now, so hopefully the documentation will catch up some time (or they may change the code again in future versions).
Published on Java Code Geeks with permission by David Wong, partner at our JCG program. See the original article here: Restart Android Activity with ActivityScenario Opinions expressed by Java Code Geeks contributors are their own. |