开发者

Android Activity lifecycle testing

开发者 https://www.devze.com 2023-02-07 14:43 出处:网络
I have Activity, which is to save its data in case system decides to kill it while it is in the background.

I have Activity, which is to save its data in case system decides to kill it while it is in the background. So, I’ve got onSaveInstanceState:

@Override
protected void onSaveInstanceState(Bundle outState){
    outState.putString("value", "some_value");
}

I check whether Bundle object is null in on开发者_StackOverflowCreate:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    isRestarted=(savedInstanceState==null);

How do I write test method? I tried

    public void testRecreate(){
    Instrumentation mInstr=this.getInstrumentation();
    mInstr.callActivityOnSaveInstanceState(mActivity, null);
    mActivity.finish();
    mActivity=this.getActivity();
    assertEquals(false, mActivity.isRestarted);
}

but it seems to be wrong.


You can use some hidden API functionality. In your test's setup, call the

android.app.ActivityManagerNative.getDefault().setAlwaysFinish()

method via reflection (because it's a hidden API) and confirm that the value was successfully set using

android.provider.Settings.System.getInt(getContentResolver(), Settings.System.ALWAYS_FINISH_ACTIVITIES, 0)

Then in the test cleanup, set this setting back to false.

Enabling the AlwaysFinish setting causes the system to destroy activities as soon as they are no longer on the screen, immediately triggering the onSaveInstanceState event. For this code to work, you will need the ALWAYS_FINISH and WRITE_SETTINGS permissions.

See the code for the SetAlwaysFinish tool linked in this blog: How to test onSaveInstanceState and onRestoreInstanceState on a real device


For manual testing, this routine works:

  1. Launch the activity you want to test
  2. Hit the home menu button on your device (activity is stopped)
  3. Kill the process from DDMS (activity is still not destroyed)
  4. Bring back your app again from the recent apps list

This should trigger onCreate again on your activity while not restarting the entire application. If you're not saving and loading the state properly, you'll know soon enough.


If you haven't been through it before, I found it worthwhile to do this at least once.


Stuff like that could be easily test using robolectric. Check it out!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号