內存泄漏問題檢測使用 LeakCanary
多線程操作造成的內存泄漏以及崩潰問題(RxJava2為例)
首先配置BaseActivity
public List<Disposable> disposableList=new ArrayList<>();
@Override
protected void onPause() {
super.onPause();
//在Activity執行onPause的時候取消所有訂閱
if (disposableList.size()>0){
for (int i=0;i<disposableList.size();i++){
if (disposableList.get(i)!=null) {
if (!disposableList.get(i).isDisposed()) {
disposableList.get(i).dispose();
}
}
}
}
}
然后在Activity頁面添加你的邏輯所訂閱的所有Observer
....subscribe(new Observer<RequestResult>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
//記錄訂閱
disposableList.add(d);
}
@Override
public void onNext(@NonNull RequestResult result) {
}
@Override
public void onError(@NonNull Throwable e) {
}
@Override
public void onComplete() {
}
});
Fragment的設置參照BaseActivity的方式
InputMethodManager(輸入法)造成的內存泄漏問題
首先你需要一個方法解決這個內存泄漏
public static void fixInputMethodManagerLeak(Context destContext) {
if (destContext == null) {
return;
}
InputMethodManager imm = (InputMethodManager) destContext.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm == null) {
return;
}
String [] arr = new String[]{"mCurRootView", "mServedView", "mNextServedView"};
Field f = null;
Object obj_get = 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);
} // author: sodino mail:sodino@qq.com
obj_get = f.get(imm);
if (obj_get != null && obj_get instanceof View) {
View v_get = (View) obj_get;
if (v_get.getContext() == destContext) {
// 被InputMethodManager持有引用的context是想要目標銷毀的
f.set(imm, null);
// 置空,破壞掉path to gc節點
} else {
// 不是想要目標銷毀的,即為又進了另一層界面了,不要處理,避免影響原邏輯,也就不用繼續for循環了
break;
}
}
}catch(Throwable t){
t.printStackTrace();
}
}
}
然后需要在合適的時機調用
@Override
protected void onDestroy() {
super.onDestroy();
//Activity銷毀的時候
fixInputMethodManagerLeak(this);
}
EditText,TextView造成的內存泄漏問題
TextView,EditText都有android:hint
屬性,倘若你在每處使用EditText或TextView的地方均設置android:hint
則不再出現內存泄漏
你也可以使用另一種方式,在你使用TextView或者EditText的地方找到ChangeWatcher監聽器,然后取消這個監聽。
https://stackoverflow.com/questions/18348049/android-edittext-memory-leak
https://stackoverflow.com/questions/14135931/memory-leak-through-iclipboarddatapasteeventimpl
https://stackoverflow.com/questions/6217378/place-cursor-at-the-end-of-text-in-edittext