您的位置:首页 > 移动开发 > Android开发

Android性能提升之LeakCanary

2017-04-11 17:30 459 查看
LeakCanary

内存泄漏排查工具

在build.grade 里加上依赖

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


LeakCanary 初始化。 一般在Application中执行

public class YouApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
//LeakCanary 初始化
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);
}
}


在mainAcitvity中测试下

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

View button = findViewById(R.id.async_task);
button.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
startAsyncTask();
}
});
}

void startAsyncTask() {
// This async task is an anonymous class and therefore has a hidden reference to the outer
// class MainActivity. If the activity gets destroyed before the task finishes (e.g. rotation),
// the activity instance will leak.
new AsyncTask<Void, Void, Void>() {
@Override protected Void doInBackground(Void... params) {
// Do some slow work in background
SystemClock.sleep(20000);
return null;
}
}.execute();
}
}


多次操作该页面,LeakCanary 就可以探测到内存泄漏了。注意要多操作几次,1次的话泄漏规模太小,可能不会探测到。LeakCanary 一旦探测到会弹出提示的。

回到桌面,会看到一个LeakCanary 的图标,如果有多个app 用到就会有多个LeakCanary图标。



点击该图标进去就可以看到相应的记录。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息