android 内存分析工具leakcanary接入

在你的app访问量越来越大时,很多问题就会暴露出来,就要进行优化了,比如内存优化,要想我们自己去排查的话,还是有点小麻烦的,现在不管什么功能,除了自身的业务都有对应的框架给你使用,使很多事情变的简单化,比如内存泄露来说,今天就可以通过leakcanary接入来帮你排查,一般只要找到问题所在,改起来都不是什么困难事,就怕你找不到问题所在,现在讲下leakcanary接入,非常简单,简单的让你不敢相信。

第一步:

在你的build.gradle文件下添加如下,第一个是说只有在你非正式包下进行

 debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3'
  releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3'

第二步:

package com.leakcanary;
import android.app.Application;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
/**
 * Created by admin on 2017/9/25.
 */
public class MyApplication  extends Application {
        private RefWatcher mRefWatcher;
        @Override
        public void onCreate () {
        super.onCreate();
        mRefWatcher = LeakCanary.install(this);
       }
}
在Application中进行配置.


演示

现在写一个单例引起的内存泄露问题,然后让LeakCanary帮你排查

package com.leakcanary;
import android.content.Context;
/**
 * Created by admin on 2017/9/25.
 */
public class CommonUtils {
    private static CommonUtils INSTANCE = null;
    private Context context;
    private CommonUtils(Context context){
            this.context = context;
    }
    public static CommonUtils getInstance(Context context){
        if(null==INSTANCE){
            INSTANCE = new CommonUtils(context);
        }
        return INSTANCE;
    }
}
在MainActivity中进行

package com.leakcanary;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CommonUtils.getInstance(this);
    }
}
运行起来后 对屏幕进行旋转:然后在桌面点击Leaks,当然也许其他项目也会使用,这样会导致桌面很多Leaks,没关系,点击打开包名就知道;


这个很明确的告诉你由于Context引起的内存泄露,至于怎么解决很简单使用Appliaction就行

猜你喜欢

转载自blog.csdn.net/coderinchina/article/details/78087756