How to stop and restart an activity in an android instrumentation test?

android, android-testing, testing

Solution

By calling (or trigger a screen orientation change):

activity.finish(); // old activity instance is destroyed and shut down.
activity = getActivity(); // new activity instance is launched and created.

Causing the activity go through the complete recreation life cycle:

onPause() -> onStop() -> onDestroy() -> onCreate()

What you need is:

onPause() -> onStop() -> onRestart()

I exposed the Instrumentation API recently and found plenty of interesting activity life cycle trigger method callActivityOnXXX(), the following single line of code should do the tricky:

MyActivity myActivity = getActivity();
// make activity falling into restart phase:
getInstrumentation().callActivityOnRestart(myActivity);

Activity life cycle diagram quoting from official dev guide:

Problem

I'm trying to write an Android activity instrumentation test that stops (`onPause()`, then `onStop()`) and restarts the current activity. I tried ``` activity.finish(); activity = getActivity(); ``` ...but that doesn't seem to work properly. The goal of the test is to assert that form data is stored during the `onPause()` method and re-read during the `onStart()` method. It works when doing it manually, but the test fails, from which I draw the conclusion that `activity.finish()` seems to be the wrong way to stop and restart an activity. Edit: My main problem seems to have been a synchronization issue. After restarting the activity, the test runner didn't wait for all event handlers to finish. The following line halts the test execution until the activity is idle: ``` getInstrumentation().waitForIdleSync() ``` Besides that, take a look at the accepted answer for more valuable information about the lifecycle.

Original source