Android -- 修复Android系统软件盘带来的泄露问题

android 在使用软键盘之后, 可能会导致这个activity无法释放,造成泄露,提供一个解决办法

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public static void fixInputMethodManagerLeak(Context context) {
if (context == null) {
return;
}
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm == null) {
return;
}
String[] arr = new String[]{"mCurRootView", "mServedView", "mNextServedView"};
Field f = null;
Object obj = null;
for (int i = 0; i < arr.length; i++) {
String param = arr[i];
try {
f = imm.getClass().getDeclaredField(param);
if (f.isAccessible() == false) {
f.setAccessible(true);
}
obj = f.get(imm);
if (obj != null && obj instanceof View) {
View vGet = (View) obj;
if (vGet.getContext() == context) {
f.set(imm, null);
} else {
break;
}
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}