利用 LeakCanary 来检查 Android 内存泄漏

来源:互联网 发布:java编程思想 新手 编辑:程序博客网 时间:2024/05/18 03:53

LeakCanary简介

  • LeakCanary是一款开源的内存泄露检测工具。开源代码被github托管。地址:https://github.com/SOFTPOWER1991/leakcanarySample_androidStudio
  • 有些对象只有有限的生命周期。当它们的任务完成之后,它们将被垃圾回收。如果在对象的生命周期本该结束的时候,这个对象还被一系列的引用,这就会导致内存泄漏。随着泄漏的累积,app将消耗完内存。

android stdio 接入方式

  • 1.android stdio 将工程切到android模式,在build.gradle(module模式下)添加依赖:
 dependencies {   debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5'   releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5'   testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5' }
  • 2.要监控Activity泄露,自定义Application
public class MyApplication extends Application {    private static final String TAG = "MyApplication";    public static RefWatcher getRefWatcher(Context context) {        MyApplication application = (MyApplication) context.getApplicationContext();        return application.refWatcher;    }    private RefWatcher refWatcher;    @Override    public void onCreate() {        Log.i(TAG,"onCreate first called............");        super.onCreate();        refWatcher = LeakCanary.install(this);    }}
  • 3.在AndroidManifest.xml配置文件中声明MyApplication
<application        android:name=".MyApplication"        android:allowBackup="true"        android:icon="@drawable/icon"        android:label="@string/app_name"        android:supportsRtl="true"        android:theme="@style/AppTheme">
  • 4.一个测试的例子
public class SecondActivity extends AppCompatActivity {    static Demo sDemo;    private static final String TAG = "SecondActivity";    @Override    protected void onCreate(Bundle savedInstanceState) {        Log.i(TAG,"onCreate() is called!!!!!!!!!!!!!!!!");        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_second);        if (sDemo == null) {            sDemo = new Demo();        }        finish();    }    class Demo {        private ArrayList<String> a = new ArrayList<String>();        public Demo() {}    }}
  • 5.执行后结果:

内存泄露的场景举例

0 0