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

后端 未结 5 459
感情败类
感情败类 2021-02-01 20:43

I\'m trying to write an Android activity instrumentation test that stops (onPause(), then onStop()) and restarts the current activity. I tried

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-01 21:24

    I tried calling .finish(), setActivity(null), getActivity() and it does restart the activity, but for me it was not restoring the state. I tried out all the other answers on SO, and every other method to do this I could find online, and none of them worked for me. After much experimentation I found the following works (nb: requires API level 11+):

        getInstrumentation().runOnMainSync(new Runnable() {
            @Override
            public void run() {
                activity.recreate();
            }
        });
        setActivity(null);
        activity = getActivity();
    

    When I do this a new Activity instance is created, and a new instance of the fragment I had attached to the activity earlier in the test is also created, and both the activity and fragment restore their state in the expected manner.

    I don't know how this works or why this works, I reached this solution through trial and error, and I have only tested it on a Nexus 4 running KitKat. I can't guarantee it correctly simulates an activity recreation, but it worked for my purposes.

    Edit: At a later date I figured out how this works. getActivity() works through registering hooks that receive new Activities being created, which catch the new Activity created by activity.recreate(). setActivity(null) was required to clear the internal cache backing getActivity, otherwise it will return the old one and not look for a new one.

    You can see how this works from examining the source code for the various test case classes one extends from.

提交回复
热议问题