I believe that many developers will not be unfamiliar with android memory leakage. In terms of optimizing performance, memory leakage, especially in large projects, is often difficult to locate due to the collaborative development of multiple people.
Here is an open source tool, LeakCanary, from square company, which can help you to monitor memory leakage.
So, how to use it?
Let's see how to connect it in.
1. Add the file build.gradle as follows:
dependencies {
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3'
}
2. Create a custom Application class. In the class, add the following code:
public class MyApplication extends Application {
@Override public void onCreate() {
super.onCreate();
LeakCanary.install(this);
}
}
public class MyApplication extends Application {
public static RefWatcher getRefWatcher(Context context) {
MyApplication application = (MyApplication) context.getApplicationContext();
return application.refWatcher;
}
private RefWatcher refWatcher;
@Override public void onCreate() {
super.onCreate();
refWatcher = LeakCanary.install(this);
}
}
4. When the interface you want to observe exits, such as a fragment, add the following code:
public abstract class MyFragment extends Fragment {
@Override public void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = MyApplication.getRefWatcher(getActivity());
refWatcher.watch(this);
}
}
5. You can observe the log on logcat:
In com.kv.leakcanary:1.0:1 com.kv.leakcanary.MainActivity has leaked:
* GC ROOT thread java.lang.Thread.<Java Local> (named 'AsyncTask #1')
* references com.kv.leakcanary.MainActivity$3.this$0 (anonymous class extends android.os.AsyncTask)
* leaks com.kv.leakcanary.MainActivity instance
* Reference Key: e71f3bf5-d786-4145-8539-584afaecad1d
* Device: Genymotion generic Google Nexus 6 - 5.1.0 - API 22 - 1440x2560 vbox86p
* Android Version: 5.1 API: 22
* Durations: watch=5086ms, gc=110ms, heap dump=435ms, analysis=2086ms
For more detailed functions, please refer to the following links.
This article refers to the following articles:
https://www.jianshu.com/p/7db231163168
http://blog.csdn.net/yangzhaomuma/article/details/52008100