天天看点

LeakCanary 使用一

一概要:

LeakCanary是GitHub上著名的开源组织Square贡献的一个内存泄漏自动检测工具。

优点:自动化发现内存泄漏;配置非常的简单。

缺点:配置时集成到低版本的应用会有bug,这时尝试修改版本:compileSdkVersion 21。

配置请参考:https://github.com/square/leakcanary

#补充一点:内存泄漏往往发生在,生命周期较长的对象,直接或间接的持有了生命周期较短的对象的强引用,导致

生命周期较短的对象不能及时的释放。

二使用:

接入步骤:

1,在Gradle中添加依赖(LeakCanary的非常好的一点是,在debug版本时才会检测,在release版本会跳过检测)

//leakcanary 检测内存泄漏
    debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.1'
    releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
    testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
           

2,在Application中初始化LeakCanary

public class ExampleApplication extends Application {

        public static RefWatcher getRefWatcher(Context context) {
            ExampleApplication application = (ExampleApplication) context.getApplicationContext();
            return application.refWatcher;
        }

        private RefWatcher refWatcher;

        @Override public void onCreate() {
            super.onCreate();
            if (LeakCanary.isInAnalyzerProcess(this)) {
                // This process is dedicated to LeakCanary for heap analysis.
                // You should not init your app in this process.
                return;
            }
            refWatcher = LeakCanary.install(this);
        }
    }
           

Ok,这样基本的接入就已经完成了。

这里为了测试,故意写一个内存泄漏的用法,一个单例SingleTon对象,持有Activity对象。

public class TestLeakSingleton {

    private TextView tv;
    private Context context;

    private static TestLeakSingleton singleton = null;

    public static TestLeakSingleton getInstance(Context context){
        if(singleton == null){
            singleton = new TestLeakSingleton(context);
        }
        return singleton;
    }

    private TestLeakSingleton(Context context){
        this.context = context;
    }

    public void setTvAppName(TextView tv){
        this.tv = tv;
        tv.setText(context.getString(R.string.app_name));
    }
}
           

在Activity中的使用:

@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_testsecond);
        TextView textView = (TextView) findViewById(R.id.tv_appname);
        TestLeakSingleton.getInstance(this).setTvAppName(textView);
    }
           

操作:1,启动这个Activity;2,退出activity。

结果:看到很多博客都说,会直接在在通知栏出现相关的通知。我的实际情况是:

1,APP安装启动之后,在应用菜单中发现图标。

LeakCanary 使用一

执行上述操作后出现了一个类似的Toast的弹窗如:

LeakCanary 使用一

2,点击这个Toast中的logo,然后在通知栏才会有相关通知。

LeakCanary 使用一

3,点击通知后就有详细的说明。(第二方法是直接点击应用菜单中Leaks图片,也能进入到此详情页)

LeakCanary 使用一

#第一部分:指明TestLeakSingeton的单例模式;

#第二部分:指明造成泄漏的引用context。

#第三部分:指明造成泄漏的类对象。

继续阅读