LeakCanary用法(内存泄漏检查)

来源:互联网 发布:双色球软件2016破解 编辑:程序博客网 时间:2024/06/11 23:06

前段时间需要对项目进行优化,用到了一个工具,其实也超简单,做下记录方便记忆。

开发用到的工具是AndroidStudio.


1.build.gradle中添加依赖

 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.在Application中添加如下代码:

public class MyApplication extends Application {    @Override    public void onCreate() {        super.onCreate();        if(!LeakCanary.isInAnalyzerProcess(this)){            return;        }        LeakCanary.install(this);    }}
这样就可以了。

同时也可以做一下内存泄漏相关的实验:

TextView mTvHello;    private static Handler handler;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mTvHello = (TextView) findViewById(R.id.tv_hello);        handler =new Handler(){            @Override            public void handleMessage(Message msg) {                super.handleMessage(msg);                if(msg.what == 1){                    mTvHello.setText("hello");                }            }        };        handler.sendEmptyMessageDelayed(1,100);    }

运行后查看leaks


这里的handler出现了内存泄漏,因为是静态的,且没有remove掉所以此处会出现内存泄漏问题。

所以在开发中使用静态变量时要注意,此处也可以进行避免,如改为非静态或者在onDestory中移除消息并置空。

 @Override    protected void onDestroy() {        super.onDestroy();        if(handler!= null){            handler.removeCallbacksAndMessages(null);            handler=null;        }    }






0 0
原创粉丝点击