Android中内存泄漏的原因及消除内存泄漏的方法

来源:互联网 发布:中国吸血鬼网络剧 编辑:程序博客网 时间:2024/05/17 01:02

一.Java内存泄漏引起的原因:

 简单的说就是该被释放的对象没有被释放,一直被某个或某些实例持有却不再使用导致GC不能回收。

 1.资源未关闭

 2.静态成员变量持有类的引用;

 3.非静态内部类持有外部类的应用,使用非静态内部类创建静态变量;

 4.单例引起内存泄漏;

 5.线程生命周期不可控;

 6.handler尽量使用静态,handler中looper存在整个activity周期,其内部messager持有handler引用,而handler又持有内的引用。


二.解决内存泄漏的方法:

 1.使用LeakCanary检测内存泄漏:

    首先在项目的build.gradle里配置的依赖dependncies中引入leakcanary的依赖

debugCompile 'com.squareup.leakcanary:leakcanary-android:1.4-beta2' releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2' testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2'
    其次,在项目中的BaseApplication中加载

 public class BaseApplication extends Application {        private RefWatcher refWatcher;        public static RefWatcher getRefWatcher(Context context) {            BaseApplication application = (BaseApplication) context.getApplicationContext();            return application.refWatcher;        }        @Override        public void onCreate() {            super.onCreate();            refWatcher = LeakCanary.install(this);        }    }
  最后,自定义activity、framgment在Destroy方法中进行内存泄漏的检测

 public class LeakActivity extends Activity {        @Override        protected void onDestroy() {            super.onDestroy();            RefWatcher watcher = BaseApplication.getRefWatcher(this);            watcher.watch(this);        }    }

public class LeakActivity extends Activity {        @Override        protected void onDestroy() {            super.onDestroy();            RefWatcher watcher = BaseApplication.getRefWatcher(this);            watcher.watch(this);        }    }

 2.使用DDSM工具:  

 1.在android studio中打开ddms,选中要检测项目的包名->点击ddms左上角小蓝桶->Cause GC

 2.检测结果导出成hprof文件

 3.将hprof-conv.exe上一步的结果转换

    使用mat打开转换结果。


    

0 0
原创粉丝点击