編輯:關於 Android 程式設計
在 LeakCanary 出現之前,排查一場 OutOfMemoryError 是一段漫長的體力活。
第一步:收集線上問題。透過 Bugly、友盟這類統計平台彙整 Crash,先摸清 OOM 的規模與分布。
第二步:重現問題。對 Crash 做篩選、歸類、排除干擾項,然後設法在本機重演。有些問題只出現在特定機型上,於是為了湊齊設備,什麼方法都得用上——我曾待過的公司甚至專門派人去租了 50 台手機回來,一天六百塊。接著就是一遍遍嘗試,用最原始、最粗暴的方式還原當時的記憶體狀態。
第三步:Dump hprof。用 DDMS 觀察 Heap,手動觸發 GC(Cause GC),記錄記憶體變化,再導出 hprof 檔。重點看兩個數字:
判斷方式很樸素:反覆打開、關閉同一個頁面,看堆是否單調遞增而不回落。

第四步:用 MAT 打開 hprof,逐一查找那些本該被回收卻還活着的物件。
第五步:計算該物件到 GC Roots 的最短強引用路徑。
第六步:找出路徑上哪一個引用是不該存在的,然後修掉它。
很麻煩,對吧?現在有個類庫能把這一切都自動化。
在 Module.app 的 build.gradle 中引入:
dependencies {
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.4-beta2'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2'
testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta2'
}
注意 release 與 test 用的是 -no-op 版本,所有呼叫都是空實作,不帶入正式包。
然後在 Application 的 onCreate() 中安裝:
public class ExampleApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
LeakCanary.install(this);
}
}
接著故意寫一段會洩露的程式碼。一旦偵測到洩露,通知欄就會跳出提示,點進去可看到完整的引用鏈。

它做到的事:以極低侵入性的方式自動捕捉記憶體洩漏,甚至能抓到 Android 系統元件自身的洩漏,而且完全省掉了「抓 Crash → 歸檔 → 重現場景 → Dump → MAT 分析」這整套流程。
先別看源碼,設想要自己寫一個 LeakCanary,步驟大概是:
除了 LeakCanary.install(this),官方 Demo 還示範了直接用 RefWatcher:
RefWatcher refWatcher = LeakCanary.androidWatcher(
getApplicationContext(),
new ServiceHeapDumpListener(getApplicationContext(), DisplayLeakService.class),
AndroidExcludedRefs.createAppDefaults().build());
refWatcher.watch(this);
看 watch() 的實作:
public void watch(Object watchedReference, String referenceName) {
Preconditions.checkNotNull(watchedReference, "watchedReference");
Preconditions.checkNotNull(referenceName, "referenceName");
// 若在 Debugger 跟蹤過程中,跳過檢測:此時的物件狀態不準確,且會干擾調試
if (debuggerControl.isDebuggerAttached()) {
return;
}
final long watchStartNanoTime = System.nanoTime();
String key = UUID.randomUUID().toString();
retainedKeys.add(key);
final KeyedWeakReference reference =
new KeyedWeakReference(watchedReference, key, referenceName, queue);
watchExecutor.execute(new Runnable() {
@Override
public void run() {
ensureGone(reference, watchStartNanoTime);
}
});
}
逐步拆解:
Set<String> retainedKeys,方便後續查找。KeyedWeakReference。它其實就是 WeakReference 的衍生類,額外帶上 key 與名稱——一個典型的裝飾模式應用。這裡有兩個關鍵結構的分工:retainedKeys 代表「尚未被回收」的對象;而傳入 KeyedWeakReference 構造器的 referenceQueue,則會在對象被判定為弱引用可達後收到對應的弱引用通知,代表「已被回收」。兩邊一對照,就能判斷某個對象的生死。
Executor 把任務派到背景執行。看 AndroidWatchExecutor:public final class AndroidWatchExecutor implements Executor {
static final String LEAK_CANARY_THREAD_NAME = "LeakCanary-Heap-Dump";
private static final int DELAY_MILLIS = 5000;
private final Handler mainHandler;
private final Handler backgroundHandler;
public AndroidWatchExecutor() {
mainHandler = new Handler(Looper.getMainLooper());
HandlerThread thread = new HandlerThread(LEAK_CANARY_THREAD_NAME);
thread.start();
backgroundHandler = new Handler(thread.getLooper());
}
@Override
public void execute(final Runnable command) {
if (isOnMainThread()) {
executeDelayedAfterIdleUnsafe(command);
} else {
mainHandler.post(new Runnable() {
@Override
public void run() {
executeDelayedAfterIdleUnsafe(command);
}
});
}
}
private boolean isOnMainThread() {
return Looper.getMainLooper().getThread() == Thread.currentThread();
}
private void executeDelayedAfterIdleUnsafe(final Runnable runnable) {
// 必須在主執行緒呼叫
Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
@Override
public boolean queueIdle() {
backgroundHandler.postDelayed(runnable, DELAY_MILLIS);
return false;
}
});
}
}
它做的事:先確保任務從主執行緒發起,透過 IdleHandler 等到主線程序列空閒,再轉發到名為 LeakCanary-Heap-Dump 的後台執行緒,並延遲 5 秒執行。等空閒再檢查是刻意的設計——正在忙碌的畫面本就容易產生大量暫時性引用。
ensureGone():void ensureGone(KeyedWeakReference reference, long watchStartNanoTime) {
long gcStartNanoTime = System.nanoTime();
long watchDurationMs = NANOSECONDS.toMillis(gcStartNanoTime - watchStartNanoTime);
// 把 queue 中已回收的弱引用清掉,retainedKeys 只留還活着的
removeWeaklyReachableReferences();
// 已被回收,或在除錯中,直接返回
if (gone(reference) || debuggerControl.isDebuggerAttached()) {
return;
}
// 主動請求一次 GC,再重新清理
gcTrigger.runGc();
removeWeaklyReachableReferences();
if (!gone(reference)) {
long startDumpHeap = System.nanoTime();
long gcDurationMs = NANOSECONDS.toMillis(startDumpHeap - gcStartNanoTime);
File heapDumpFile = heapDumper.dumpHeap();
if (heapDumpFile == null) {
return; // Dump 失敗,放棄本次
}
long heapDumpDurationMs = NANOSECONDS.toMillis(System.nanoTime() - startDumpHeap);
heapdumpListener.analyze(new HeapDump(heapDumpFile, reference.key,
reference.name, excludedRefs,
watchDurationMs, gcDurationMs, heapDumpDurationMs));
}
}
private boolean gone(KeyedWeakReference reference) {
return !retainedKeys.contains(reference.key);
}
private void removeWeaklyReachableReferences() {
// 弱引用一旦可達性消失就會入列,時機早於 finalize 與真正的回收
KeyedWeakReference ref;
while ((ref = (KeyedWeakReference) queue.poll()) != null) {
retainedKeys.remove(ref.key);
}
}
這裡有兩個值得深究的設計:
問題一:retainedKeys 和 queue 是怎麼關聯起來的?答案就在 removeWeaklyReachableReferences()。每次從 queue 取出被回收的弱引用,就把它對應的 key 從 retainedKeys 移除。於是 gone() 回傳 true 就代表該 key 已不在 retainedKeys 中,也就是對象已被回收,不必再觀察。
問題二:為什麼要呼叫兩次 removeWeaklyReachableReferences()?第一次是為了在「主動觸發 GC 之前」先撈一遍——如果對象早已被回收,就不必再花成本去通知 GC、Dump、分析。GC 執行緒的優先級極低,就算你通知了它也不一定馬上執行,所以選擇在什麼時機檢測,比檢測本身更關鍵。第二次則是在 GC 之後重新確認。
我們監測的對象是 Activity。Activity 有明確的生命週期,當它走完 onDestroy() 卻仍存活,就幾乎可以斷定洩漏。所以只要覆寫這個方法:
@Override
protected void onDestroy() {
super.onDestroy();
refWatcher.watch(this);
}
但我們顯然不想每個 Activity 都寫一遍。LeakCanary 的解法是透過 ActivityLifecycleCallbacks 統一轉發:
private final Application.ActivityLifecycleCallbacks lifecycleCallbacks =
new Application.ActivityLifecycleCallbacks() {
@Override public void onActivityCreated(Activity a, Bundle s) { }
@Override public void onActivityStarted(Activity a) { }
@Override public void onActivityResumed(Activity a) { }
@Override public void onActivityPaused(Activity a) { }
@Override public void onActivityStopped(Activity a) { }
@Override public void onActivitySaveInstanceState(Activity a, Bundle b) { }
@Override
public void onActivityDestroyed(Activity activity) {
ActivityRefWatcher.this.onActivityDestroyed(activity);
}
};
void onActivityDestroyed(Activity activity) {
refWatcher.watch(activity);
}
因此在 Application 中只要一行 LeakCanary.install(this) 就足夠:
public final class LeakCanary {
public static RefWatcher install(Application application) {
return install(application, DisplayLeakService.class,
AndroidExcludedRefs.createAppDefaults().build());
}
public static RefWatcher install(Application application,
Class<? extends AbstractAnalysisResultService> listenerServiceClass,
ExcludedRefs excludedRefs) {
if (isInAnalyzerProcess(application)) {
return RefWatcher.DISABLED;
}
enableDisplayLeakActivity(application);
ServiceHeapDumpListener heapDumpListener =
new ServiceHeapDumpListener(application, listenerServiceClass);
RefWatcher refWatcher = androidWatcher(application, heapDumpListener, excludedRefs);
ActivityRefWatcher.installOnIcsPlus(application, refWatcher);
return refWatcher;
}
}
但這個方法有個限制,源碼註釋寫得很明白:
// If you need to support Android < ICS, override onDestroy() in your base activity.
ActivityLifecycleCallbacks 是 API 14(Android 4.0)才有的。低於此版本,仍得回到覆寫 onDestroy() 的老路。另外,它只監測 Activity;Service、BroadcastReceiver 若要監測,得自己動手。
ServiceHeapDumpListener 本身只是轉發器:
public final class ServiceHeapDumpListener implements HeapDump.Listener {
@Override
public void analyze(HeapDump heapDump) {
Preconditions.checkNotNull(heapDump, "heapDump");
HeapAnalyzerService.runAnalysis(context, heapDump, listenerServiceClass);
}
}
而 HeapAnalyzerService 是個 IntentService,運行在獨立進程中——因為分析 hprof 極耗記憶體,必須與主應用隔離:
public final class HeapAnalyzerService extends IntentService {
private static final String LISTENER_CLASS_EXTRA = "listener_class_extra";
private static final String HEAPDUMP_EXTRA = "heapdump_extra";
public static void runAnalysis(Context context, HeapDump heapDump,
Class<? extends AbstractAnalysisResultService> listenerServiceClass) {
Intent intent = new Intent(context, HeapAnalyzerService.class);
intent.putExtra(LISTENER_CLASS_EXTRA, listenerServiceClass.getName());
intent.putExtra(HEAPDUMP_EXTRA, heapDump);
context.startService(intent);
}
@Override
protected void onHandleIntent(Intent intent) {
String listenerClassName = intent.getStringExtra(LISTENER_CLASS_EXTRA);
HeapDump heapDump = (HeapDump) intent.getSerializableExtra(HEAPDUMP_EXTRA);
ExcludedRefs androidDefaults = createAndroidDefaults().build();
HeapAnalyzer heapAnalyzer = new HeapAnalyzer(androidDefaults, heapDump.excludedRefs);
AnalysisResult result = heapAnalyzer.checkForLeak(
heapDump.heapDumpFile, heapDump.referenceKey);
AbstractAnalysisResultService.sendResultToListener(
this, listenerClassName, heapDump, result);
}
}
核心分析在 checkForLeak():
public AnalysisResult checkForLeak(File heapDumpFile, String referenceKey) {
long analysisStartNanoTime = System.nanoTime();
if (!heapDumpFile.exists()) {
return AnalysisResult.failure(
new IllegalArgumentException("File does not exist: " + heapDumpFile),
since(analysisStartNanoTime));
}
ISnapshot snapshot = null;
try {
snapshot = openSnapshot(heapDumpFile);
// 依 key 找回洩露的物件
IObject leakingRef = findLeakingReference(referenceKey, snapshot);
if (leakingRef == null) {
// 誤報:弱引用在 key 檢查與 Dump 之間被清掉了
return AnalysisResult.noLeak(since(analysisStartNanoTime));
}
String className = leakingRef.getClazz().getName();
// 先求最短引用路徑(排除已知洩漏)
AnalysisResult result =
findLeakTrace(analysisStartNanoTime, snapshot, leakingRef, className, true);
// 若排除後找不到,再不排除試一次
if (!result.leakFound) {
result = findLeakTrace(analysisStartNanoTime, snapshot, leakingRef, className, false);
}
return result;
} catch (SnapshotException e) {
return AnalysisResult.failure(e, since(analysisStartNanoTime));
} finally {
cleanup(heapDumpFile, snapshot);
}
}
拿到最短引用路徑後,剩下的就是發送通知、點擊跳轉到分析 App 繪製路徑。
上面那段「先排除、找不到再不排除」的邏輯值得單獨說明:
private AnalysisResult findLeakTrace(long analysisStartNanoTime, ISnapshot snapshot,
IObject leakingRef, String className, boolean excludingKnownLeaks)
throws SnapshotException {
ExcludedRefs excludedRefs = excludingKnownLeaks ? this.excludedRefs : baseExcludedRefs;
PathsFromGCRootsTree gcRootsTree = shortestPathToGcRoots(snapshot, leakingRef, excludedRefs);
if (gcRootsTree == null) {
return AnalysisResult.noLeak(since(analysisStartNanoTime));
}
LeakTrace leakTrace = buildLeakTrace(snapshot, gcRootsTree, excludedRefs);
return AnalysisResult.leakDetected(!excludingKnownLeaks, className,
leakTrace, since(analysisStartNanoTime));
}
唯一的差別是 excludingKnownLeaks——是否排除已知的內存洩漏。
原因很實際:Android 系統本身存在若干已知洩漏,上層 App 工程師無能為力。若不排除,一打開 App 就彈出一堆莫名其妙又修不了的警告,反而干擾真正該處理的問題。做成參數讓使用者自行選擇,對 Framework 工程師或需要做 ROM 的團隊尤其有用。
這份清單由 ExcludedRefs 承載:
public final class ExcludedRefs implements Serializable {
public final Map<String, Set<String>> excludeFieldMap;
public final Map<String, Set<String>> excludeStaticFieldMap;
public final Set<String> excludedThreads;
private ExcludedRefs(Map<String, Set<String>> excludeFieldMap,
Map<String, Set<String>> excludeStaticFieldMap,
Set<String> excludedThreads) {
// 複製一份並轉為不可變集合
this.excludeFieldMap = unmodifiableMap(new LinkedHashMap<>(excludeFieldMap));
this.excludeStaticFieldMap = unmodifiableMap(new LinkedHashMap<>(excludeStaticFieldMap));
this.excludedThreads = unmodifiableSet(new LinkedHashSet<>(excludedThreads));
}
public static final class Builder {
private final Map<String, Set<String>> excludeFieldMap = new LinkedHashMap<>();
private final Map<String, Set<String>> excludeStaticFieldMap = new LinkedHashMap<>();
private final Set<String> excludedThreads = new LinkedHashSet<>();
/** 排除某類別的某個 instance 欄位 */
public Builder instanceField(String className, String fieldName) {
add(excludeFieldMap, className, fieldName);
return this;
}
/** 排除某類別的某個 static 欄位 */
public Builder staticField(String className, String fieldName) {
add(excludeStaticFieldMap, className, fieldName);
return this;
}
/** 排除某個執行緒 */
public Builder thread(String threadName) {
excludedThreads.add(threadName);
return this;
}
private void add(Map<String, Set<String>> map, String className, String fieldName) {
Set<String> fields = map.get(className);
if (fields == null) {
fields = new LinkedHashSet<>();
map.put(className, fields);
}
fields.add(fieldName);
}
public ExcludedRefs build() {
return new ExcludedRefs(excludeFieldMap, excludeStaticFieldMap, excludedThreads);
}
}
}
LeakCanary 的價值不只在「自動化」,更在於它把一套原本只有資深工程師才玩得動的流程——弱引用監測、延遲 GC 時機、hprof 解析、最短強引用路徑計算、干擾項排除——封裝成一行 install()。它背後的每個設計選擇,幾乎都對應著實戰中踩過的坑:為什麼等 Idle 才檢查、為什麼呼叫兩次清理、為什麼分析要放獨立進程、為什麼預設排除系統已知洩漏。讀懂這些,比單純會用這個庫有價值得多。
Android Drawable 全景圖鑑:從 XML 節點到實現類
為什麼要系統地認識 Drawable 日常開發中,我們絕大多數時候並不直接 new 出某個 Drawable 實現類,而是寫 XML。只有當需要在運行時動態修改 Draw
Android 六大基礎佈局完全解析
佈局管理器全都是以 ViewGroup 為基底類別衍生出來的;善用佈局管理器,可以讓介面適配不同手機螢幕的解析度與尺寸大小。 如何使用 XML 檔案定義視圖: 每個 A
Android 表單欄位驗證實作:Android-Validator 應用解析
先看一下完成後的效果: 這裡借用開源的 Android-Validator 元件來完成表單驗證。核心觀念是:先建立一個 Form 用來裝載各個待驗證的控制項,再為每個控
Android 單擊切換圖片的實現與內存溢出啟示
下面通過一個簡單的例子實現「單擊切換圖片」的效果: public class MixView extends ActionBarActivity { int[]