android开发笔记之内存泄漏检测工具leakcanary

这里写图片描述

leakcanary简单介绍

LeakCanary是GitHub上著名的开源组织Square贡献的一个内存泄漏自动检测工具。
优点:自动化发现内存泄漏;配置非常的简单。
补充一点:内存泄漏往往发生在,生命周期较长的对象,直接或间接的持有了生命周期较短的对象的强引用,导致生命周期较短的对象不能及时的释放。

leakcanary使用方法

leakcanary使用方法极其简单,我们可以查看一下github leakcanary的说明。

我们测试的版本为1.5.4:

github leakcanary上的使用方法介绍是极其的简单:

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

In your build.gradle:

 dependencies {
   debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.4'
   releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.4'
 }

第二步:在Application中初始化LeakCanary:

In your Application class:

import android.app.Application;
import com.squareup.leakcanary.LeakCanary;
p
ublic class ExampleApplication extends Application {

  @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;
    }
    LeakCanary.install(this);
    // Normal app init code...
  }
}

第三步,在AndroidManifest.xml文件中修改应用的名字类:

    <application
        android:name="android.com.demo_01.ExampleApplication"

一个例子

定义一个测试类—TestLeakSingleton :

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));
    }
}

新建一个简单的界面:

public class MainActivity extends AppCompatActivity {

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

}

生成APK,安装到手机上测试:

操作:
1,启动这个Activity
2,退出activity
3,重复以上二个操作

不一会,在通知栏出现了一个通知:

这里写图片描述

点击进去,如下显示:

这里写图片描述

参考资料

1.leakcanary
https://github.com/square/leakcanary
2.LeakCanary 使用一
http://m.blog.csdn.net/wangsongbin893603021/article/details/75007034

猜你喜欢

转载自blog.csdn.net/hfreeman2008/article/details/78285760
今日推荐