Android Memory leakage troubleshooting tool LeakCanary and androidleakcanary
Open Source Address: https://github.com/square/leakcanary
Add the dependency in build. gralde and sync it. Add the following content:
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' }
Ellipsis indicates other existing content
Initialize LeakCanary in the Application class .. For example, MyApplication. If no Application exists, create one and inherit from android. app. Application. Do not forget to add it to AndroidManifest. xml; otherwise, it will not work.
Public class MyApplication extends Application {@ Override public void onCreate () {super. onCreate (); if (LeakCanary. isInAnalyzerProcess (this) {// This process is dedicated to LeakCanary for heap analysis. // You shoshould not init your app in this process. return;} LeakCanary. install (this); // your other code starts from below }}
The official demo already exists. You can run it.
package com.github.pandafang.leakcanarytest;import android.app.Activity;import android.os.AsyncTask;import android.os.Bundle;import android.os.SystemClock;import android.view.View;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(); }}
Go to the main interface, press the button, and then press the return key to exit the main interface. After several times, LeakCanary will be able to detect memory leakage. Note that multiple operations are required. If one operation is performed, the leak is too small and may not be detected. A prompt is displayed when LeakCanary is detected.
Return to the desktop and you will see a LeakCanary icon. If multiple apps are used, there will be multiple LeakCanary icons.
Click in to view the memory leakage record.
Click it to view the call stack.