通过Android Profile+MAT定位到InputMethodManager泄漏Activity。
- 解决方案
import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import java.lang.reflect.Field;
/**
* 内存泄漏工具类
* 作者: FebMaple on 26/12/2018.
* 版权: FebMaple
* ====================================================
*/
public class MemoryLeakUtil {
/**
* fix InputMethodManager leak memory
*
* @param context
*/
public static void fixInputMethodMemoryLeak(Context context) {
if (context == null)
return;
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager == null)
return;
String[] viewArr = new String[]{"mCurRootView", "mServedView", "mNextServedView", "mLastSrvView"};
Field field;
Object fieldObj;
for (String view : viewArr) {
try {
field = inputMethodManager.getClass().getDeclaredField(view);
if (!field.isAccessible()) {
field.setAccessible(true);
}
fieldObj = field.get(inputMethodManager);
if (fieldObj != null && fieldObj instanceof View) {
View fieldView = (View) fieldObj;
if (fieldView.getContext() == context) {// 被InputMethodManager持有引用的context是想要目标销毁的
field.set(inputMethodManager, null);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
在泄漏的activity ondestroy内添加
@Override
protected void onDestroy() {
MemoryLeakUtil.fixInputMethodMemoryLeak(this);
super.onDestroy();
}
本文提供了一种解决Android应用中InputMethodManager导致的Activity内存泄漏的方法。通过自定义的MemoryLeakUtil工具类,在Activity的onDestroy方法中调用fixInputMethodMemoryLeak方法,可以断开InputMethodManager对Activity的引用,避免内存泄漏。此方案适用于使用了软键盘输入的Android应用。
2162

被折叠的 条评论
为什么被折叠?



