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:

scenario.recreate()

So I wrote this function to for restarting the activity:

    @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:

    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).

Leave a Reply

Your email address will not be published. Required fields are marked *