How to use Leak Canary

后端 未结 5 1708
悲&欢浪女
悲&欢浪女 2020-12-24 05:57

I know this is probably a dumb question, but I am pretty new at developing android, and I currently experiencing an OutOfMemoryError in my apps, which I have tried to debug

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-24 06:23

    I used Leak-Canary like below:

    1) Gradle dependency:

    debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.4'
    

    2) Application class:

       @Override
    public void onCreate() {
        super.onCreate();
        if (BuildConfig.DEBUG) {
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                    .detectCustomSlowCalls()
                    .detectNetwork()
                    .penaltyLog()
                    .penaltyDeath()
                    .build());
            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                    .detectActivityLeaks()
                    .detectLeakedClosableObjects()
                    .detectLeakedRegistrationObjects()
                    .detectLeakedSqlLiteObjects()
                    .penaltyLog()
                    .penaltyDeath()
                    .build());
    
            LeakLoggerService.setupLeakCanary(this);
        }
    }
    

    3) LeakLoggerService class: place this class in debug package created by gradle.

    public class LeakLoggerService extends DisplayLeakService {
    
    public static void setupLeakCanary(Application application) {
        if (LeakCanary.isInAnalyzerProcess(application)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            return;
        }
        LeakCanary.install(application, LeakLoggerService.class,
                AndroidExcludedRefs.createAppDefaults().build());
    
    }
    
    @Override
    protected void afterDefaultHandling(HeapDump heapDump, AnalysisResult result, String leakInfo) {
        if (!result.leakFound || result.excludedLeak) {
            return;
        }
    
        Log.w("LeakCanary", leakInfo);
    }
    

    4) Register service to manifest file and 1 permission:

      
      
    

    5) Finally verify if setup is successful: Leak an activity ;)

    public class Main2Activity extends AppCompatActivity {
    static TextView label;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        label = new TextView(this);
        label.setText("asds");
    
        setContentView(label);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 
    }
    }
    

    kill this activity and check logs with tag : LeakCanary

    It should work...

提交回复
热议问题