LeakCanary检测内存泄漏:
LeakCanary是Square公司出的开源框架(Square出品,必属精品),是一个Android和Java的内存泄露傻瓜化并且可视化的内存泄露分析工具,当检测到某个activity有内存泄露,LeakCanary会弹出通知,定位到内存泄露的位置。使用它大大减少OOM的问题,提高App的质量。
1. List item
在 build.gradle 中加入引用:
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.6.1'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.6.1'
testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.6.1'
2.创建Application配置并使用Application:
import android.app.Application;
import android.content.Context;
import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;
public class MyApplication extends Application{
private RefWatcher refWatcher;
@Override
public void onCreate() {
super.onCreate();
refWatcher = LeakCanary.install(this);
}
public static RefWatcher getRefWatcher(Context context){
MyApplication application = (MyApplication)context.getApplicationContext();
return application.refWatcher;
}
}
3.使用 RefWatcher 监控 Activity:
public class TestActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
RefWatcher refWatcher = MyApplication.getRefWatcher(this);
refWatcher.watch(this);
}
}
4.直接运行的时候会产生对应的泄漏app,当发生内存泄漏的时候会在通知栏进行显示并分析泄漏原因,然后打开leaks
app就可以看到泄漏的详细信息;