使用leakcanary 检测内存泄漏

Square开源了一个内存泄露自动探测神器——LeakCanary,它是一个Android和Java的内存泄露检测库,可以大幅度减少了开发中遇到的OOM问题。

加入依赖:

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'
 }

Application 配置:

public class MyAplication extends Application{
    //在自己的Application中添加如下代码
    private RefWatcher refWatcher;

    //在自己的Application中添加如下代码
    public static RefWatcher getRefWatcher(Context context) {
        MyAplication application = (MyAplication) context.getApplicationContext();
        return application.refWatcher;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //在自己的Application中添加如下代码
        refWatcher = LeakCanary.install(this);
    }
}

使用 RefWatcher 监控那些本该被回收的对象:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MyHander myHander = MyHander.getInstance(MainActivity.this);
    
    }

    public void onClicks(View view){
        startActivity(new Intent(MainActivity.this, Main2Activity.class));
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        RefWatcher refWatcher = MyAplication.getRefWatcher(MainActivity.this);
        refWatcher.watch(this);
    }

}

MyHander 内初泄露代码:

public class MyHander {
    private static  MyHander instance;
    private Context context;


    public MyHander(Context context) {
        this.context = context;
    }

    public static MyHander getInstance(Context context) {
        if (instance == null){
            synchronized (MyHander.class){
                if (instance == null){
                    instance = new MyHander(context);
                }

            }

        }
        return instance;
   }

}

最后如果有内存泄漏,会接收到相应的推送。

使用leakcanary 检测内存泄漏_第1张图片

你可能感兴趣的:(使用leakcanary 检测内存泄漏)