Skip to content

Instantly share code, notes, and snippets.

@plackemacher
Created September 30, 2015 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plackemacher/a645532b2ceefdde95e7 to your computer and use it in GitHub Desktop.
Save plackemacher/a645532b2ceefdde95e7 to your computer and use it in GitHub Desktop.
Robolectric Activity Leak Fix
@SuppressLint("NewApi")
@After
public void resetWindowManager() {
Class clazz = ReflectionHelpers.loadClass(getClass().getClassLoader(), "android.view.WindowManagerGlobal");
Object instance = ReflectionHelpers.callStaticMethod(clazz, "getInstance");
// We essentially duplicate what's in {@link WindowManagerGlobal#closeAll} with what's below.
// The closeAll method has a bit of a bug where it's iterating through the "roots" but
// bases the number of objects to iterate through by the number of "views." This can result in
// an {@link java.lang.IndexOutOfBoundsException} being thrown.
Object lock = ReflectionHelpers.getField(instance, "mLock");
ArrayList<Object> roots = ReflectionHelpers.getField(instance, "mRoots");
//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized (lock) {
for (int i = 0; i < roots.size(); i++) {
ReflectionHelpers.callInstanceMethod(instance, "removeViewLocked",
ReflectionHelpers.ClassParameter.from(int.class, i),
ReflectionHelpers.ClassParameter.from(boolean.class, false));
}
}
// Views will still be held by this array. We need to clear it out to ensure
// everything is released.
ArraySet<View> dyingViews = ReflectionHelpers.getField(instance, "mDyingViews");
dyingViews.clear();
}
@chenqizheng
Copy link

The problem is in Android M??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment