I need to test my apps lifecycle and its destruction and re-creation, because when the keyboard slides in/out (or is rotated), the app is destroyed and re-created. I also need to test for memory leaks when it does this.
I saw in the tutorial http://developer.android.com/tools/testing/activity_test.html#StateManagementTests
Terminate the activity and restart it:
mActivity.finish();
mActivity = this.getActivity();
However this is very simplified. My logging seems to indicate that calling finish() spawns a background thread with a different thread id which then calls onPause(), finish(), onStop(), and onDestroy(). I even tried getInstrumentation().waitForIdleSync(); to try to wait for that background thread to complete, but I still get race conditions when I test for expected values.
Not only that, but when it re-creates the Activity (when the 1st race condition doesn’t occur or I comment out the assert), with getActivity(), then it just returns the exact same object that I just finished! I can tell because I log this in my onXXX…() methods.
This differs from the orientation rotation / keyboard sliding app lifecycle, which always creates a new Activity object.
So how can I test this destruction / reincarnation scenario?
Ok I found it! It involves LOTs of waitForIdleSync() since it is multi-threaded to begin with, and setActivity(null). I could only get within +- 30% of the same memory. I would like to give credit to Peter Carpenter too, because his idea sped up my app and I would never have thought of that!