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

后端 未结 5 458
感情败类
感情败类 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:19

    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: enter image description here

提交回复
热议问题