好的,我找到了!它涉及很多 waitForIdleSync(),因为它是多线程的,并且 setActivity(null)。我只能获得相同内存的 +- 30%。我也想感谢 Peter Carpenter,因为他的想法加速了我的应用程序,我从来没有想过这一点!
public void testMemoryLeaks() {
Log.e(TAG, "------------ testMemoryLeaks()");
getInstrumentation().waitForIdleSync();
System.gc();
Main mActivity = getActivity();
Log.d(TAG, "-- Extractor.stop() "+mActivity.getExtractor());
mActivity.getExtractor().stop();
getInstrumentation().waitForIdleSync();
System.gc();
long mem = Runtime.getRuntime().freeMemory();
Log.d(TAG, "-- freeMemory: " + mem);
Log.d(TAG, "-- mActivity.finish()");
mActivity.finish();
getInstrumentation().waitForIdleSync();
Log.d(TAG, "-- setActivity()");
setActivity(null);
getInstrumentation().waitForIdleSync();
System.gc();
Log.d(TAG, "-- getActivity()");
mActivity = getActivity();
assertTrue(mActivity != null);
Log.d(TAG, "-- Extractor.stop() "+mActivity.getExtractor());
mActivity.getExtractor().stop();
getInstrumentation().waitForIdleSync();
System.gc();
long memAfter = Runtime.getRuntime().freeMemory();
Log.d(TAG, "-- freeMemory: " + memAfter);
assertTrue("Memory leak", mem > memAfter * .70 && mem < memAfter * 1.30);
mActivity.finish();
getInstrumentation().waitForIdleSync();
Log.d(TAG, "-- end testMemoryLeaks()");
}