內存泄漏監測-LeakCanary

內存泄漏監測方法之使用LeakCanaryandroid

LeakCanary出處:git

github:https://github.com/square/leakcanary/issuesgithub

square 公司app

這個公司大名不知道,但你必定知道OKHTTP.eclipse

還有不少開源看下圖ide

 

使用方法:this

android studio spa

添加依賴:debug

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

eclipse:自行下包code

使用方法很簡單,在application install就能夠了。

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        LeakCanary.install(this);
    }
}

如如應用存在多個進程,application onreate 會調用屢次。這麼寫是否是有問題。Install屢次。

既然是大廠出的東西,他們是已經考慮到了。

看源碼:

/**
   * Creates a {@link RefWatcher} that reports results to the provided service, and starts watching
   * activity references (on ICS+).
   */
  public static RefWatcher install(Application application,
      Class<? extends AbstractAnalysisResultService> listenerServiceClass,
      ExcludedRefs excludedRefs) {
    //判斷是否在Analyzer進程裏
    if (isInAnalyzerProcess(application)) {
      return RefWatcher.DISABLED;
    }
    enableDisplayLeakActivity(application);
    HeapDump.Listener heapDumpListener =
        new ServiceHeapDumpListener(application, listenerServiceClass);
    RefWatcher refWatcher = androidWatcher(application, heapDumpListener, excludedRefs);
    ActivityRefWatcher.installOnIcsPlus(application, refWatcher);
    return refWatcher;
  }

固然也能夠:

if (LeakCanary.isInAnalyzerProcess(this)) {
  return;
}

這麼判斷。

經過以上操做,功能已經能夠使用了,十分傻瓜。

 

上手試試加如下加代碼:

public class LoginActivity extends Activity {
    static Thread t;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        t = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {

                }
            }
        });
        t.start();

        finish();
    }

結果以下:

 

相關文章
相關標籤/搜索