很簡(jiǎn)單:我們不是創(chuàng)建服務(wù)不是為了賺錢;我們賺錢是為了提供更好的服務(wù)。我們認(rèn)為這才是做事的態(tài)度。

學(xué)習(xí)使用Java的同學(xué)都應(yīng)該知道,Java的JVM給我們提供的垃圾回收機(jī)制是極為好用的。但是我們也很清楚,垃圾回收機(jī)制不是萬能的,使用不當(dāng)很容易造成內(nèi)存泄露。之前我們也介紹過Java中常用的內(nèi)存泄露檢測(cè)工具M(jìn)AT,目前Java程序最常用的內(nèi)存分析工具應(yīng)該是MAT(Memory Analyzer Tool),它是一個(gè)Eclipse插件,同時(shí)也有單獨(dú)的RCP客戶端。
不熟悉MAT的同學(xué),或者對(duì)Java垃圾回收機(jī)制不了解的同學(xué),可以
看我的這篇文章:http://blog.csdn.net/yzzst/article/details/26621861
今天,這里我們不說MAT,我們說一個(gè)更有用的開源工具——LeakCanary。
LeakCanary本質(zhì)上就是一個(gè)基于MAT進(jìn)行Android應(yīng)用程序內(nèi)存泄漏自動(dòng)化檢測(cè)的的開源工具,通過集成這個(gè)工具代碼到自己的Android工程當(dāng)中就能夠在程序調(diào)試開發(fā)過程中通過一個(gè)漂亮的界面。
隨時(shí)發(fā)現(xiàn)和定位內(nèi)存泄漏問題,而不用每次在開發(fā)流程中都抽出專人來進(jìn)行內(nèi)存泄漏問題檢測(cè),極大地方便了Android應(yīng)用程序的開發(fā)。
總的來說,LeakCanary有如下幾個(gè)明顯優(yōu)點(diǎn):
- 針對(duì)Android Activity組件完全自動(dòng)化的內(nèi)存泄漏檢查。
- 可定制一些行為(dump文件和leaktrace對(duì)象的數(shù)量、自定義例外、分析結(jié)果的自定義處理等)。
- 集成到自己工程并使用的成本很低。(*主要)
- 友好的界面展示和通知。
Github地址:https://github.com/square/leakcanary
具體怎么使用?應(yīng)用一下官方的翻譯文檔入下:
LeakCanary
Android 和 Java 內(nèi)存泄露檢測(cè)。
“A small leak will sink a great ship.” - Benjamin Franklin
千里之堤, 毀于蟻穴。 – 《韓非子·喻老》

開始使用
在 build.gradle 中加入引用,不同的編譯使用不同的引用:
dependencies {
debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3'
releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3'
}
在 Application 中:
public class ExampleApplication extends Application {
@Override public void onCreate() {
super.onCreate();
LeakCanary.install(this);
}
這樣,就萬事俱備了! 在 debug build 中,如果檢測(cè)到某個(gè) activity 有內(nèi)存泄露,LeakCanary 就是自動(dòng)地顯示一個(gè)通知。
如何使用
使用 RefWatcher 監(jiān)控那些本該被回收的對(duì)象。
RefWatcher refWatcher = {...};
// 監(jiān)控
refWatcher.watch(schrodingerCat);
LeakCanary.install() 會(huì)返回一個(gè)預(yù)定義的 RefWatcher,同時(shí)也會(huì)啟用一個(gè) ActivityRefWatcher,用于自動(dòng)監(jiān)控調(diào)用 Activity.onDestroy() 之后泄露的 activity。
public class ExampleApplication extends Application {
public static RefWatcher getRefWatcher(Context context) {
ExampleApplication application = (ExampleApplication) context.getApplicationContext();
return application.refWatcher;
}
private RefWatcher refWatcher;
@Override public void onCreate() {
super.onCreate();
refWatcher = LeakCanary.install(this);
}
}
使用 RefWatcher 監(jiān)控 Fragment:
public abstract class BaseFragment extends Fragment {
@Override
public void onDestroy() {
super.onDestroy();
RefWatcher refWatcher = ExampleApplication.getRefWatcher(getActivity());
refWatcher.watch(this);
}
}
工作機(jī)制
- RefWatcher.watch() 創(chuàng)建一個(gè) KeyedWeakReference 到要被監(jiān)控的對(duì)象。
- 然后在后臺(tái)線程檢查引用是否被清除,如果沒有,調(diào)用GC。
- 如果引用還是未被清除,把 heap 內(nèi)存 dump 到 APP 對(duì)應(yīng)的文件系統(tǒng)中的一個(gè) .hprof 文件中。
- 在另外一個(gè)進(jìn)程中的 HeapAnalyzerService 有一個(gè) HeapAnalyzer 使用HAHA 解析這個(gè)文件。
- 得益于唯一的 reference key, HeapAnalyzer 找到 KeyedWeakReference,定位內(nèi)存泄露。
- HeapAnalyzer 計(jì)算 到 GC roots 的最短強(qiáng)引用路徑,并確定是否是泄露。如果是的話,建立導(dǎo)致泄露的引用鏈。
- 引用鏈傳遞到 APP 進(jìn)程中的 DisplayLeakService, 并以通知的形式展示出來。
如何復(fù)制 leak trace?
在 Logcat 中,你可以看到類似這樣的 leak trace:
In com.example.leakcanary:1.0:1 com.example.leakcanary.MainActivity has leaked:
* GC ROOT thread java.lang.Thread.<Java Local> (named 'AsyncTask #1')
* references com.example.leakcanary.MainActivity$3.this$0 (anonymous class extends android.os.AsyncTask)
* leaks com.example.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
你甚至可以通過分享按鈕把這些東西分享出去。
SDK 導(dǎo)致的內(nèi)存泄露
隨著時(shí)間的推移,很多SDK 和廠商 ROM 中的內(nèi)存泄露問題已經(jīng)被盡快修復(fù)了。但是,當(dāng)這樣的問題發(fā)生時(shí),一般的開發(fā)者能做的事情很有限。
LeakCanary 有一個(gè)已知問題的忽略列表,AndroidExcludedRefs.java,如果你發(fā)現(xiàn)了一個(gè)新的問題,請(qǐng)?zhí)嵋粋€(gè) issue 并附上 leak trace, reference key, 機(jī)器型號(hào)和 SDK 版本。如果可以附帶上 dump 文件的 鏈接那就再好不過了。
對(duì)于最新發(fā)布的 Android,這點(diǎn)尤其重要。你有機(jī)會(huì)在幫助在早期發(fā)現(xiàn)新的內(nèi)存泄露,這對(duì)整個(gè) Android 社區(qū)都有極大的益處。
開發(fā)版本的 Snapshots 包在這里: https://oss./content/repositories/snapshots/
leak trace 之外
有時(shí),leak trace 不夠,你需要通過 MAT 或者 YourKit 深挖 dump 文件。
通過以下方法,你能找到問題所在:
- 查找所有的 com.squareup.leakcanary.KeyedWeakReference 實(shí)例。
- 檢查 key 字段
- Find the KeyedWeakReference that has a key field equal to the reference key reported by LeakCanary.
- 找到 key 和 和 logcat 輸出的 key 值一樣的 KeyedWeakReference。
- Referent 字段對(duì)應(yīng)的就是泄露的對(duì)象。
- 剩下的,就是動(dòng)手修復(fù)了。最好是檢查到 GC root 的最短強(qiáng)引用路徑開始。
自定義
UI 樣式
DisplayLeakActivity 有一個(gè)默認(rèn)的圖標(biāo)和標(biāo)簽,你只要在你自己的 APP 資源中,替換以下資源就可。
res/
drawable-hdpi/
__leak_canary_icon.png
drawable-mdpi/
__leak_canary_icon.png
drawable-xhdpi/
__leak_canary_icon.png
drawable-xxhdpi/
__leak_canary_icon.png
drawable-xxxhdpi/
__leak_canary_icon.png
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="__leak_canary_display_activity_label">MyLeaks</string>
</resources>
保存 leak trace
DisplayLeakActivity saves up to 7 heap dumps & leak traces in the app directory. You can change that number by providing R.integer.__leak_canary_max_stored_leaks in your app:
在 APP 的目錄中,DisplayLeakActivity 保存了 7 個(gè) dump 文件和 leak trace。你可以在你的 APP 中,定義 R.integer.__leak_canary_max_stored_leaks 來覆蓋類庫的默認(rèn)值。
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="__leak_canary_max_stored_leaks">20</integer>
</resources>
上傳 leak trace 到服務(wù)器
你可以改變處理完成的默認(rèn)行為,將 leak trace 和 heap dump 上傳到你的服務(wù)器以便統(tǒng)計(jì)分析。
創(chuàng)建一個(gè) LeakUploadService, 最簡(jiǎn)單的就是繼承 DisplayLeakService :
public class LeakUploadService extends DisplayLeakService {
@Override
protected void afterDefaultHandling(HeapDump heapDump, AnalysisResult result, String leakInfo) {
if (!result.leakFound || result.excludedLeak) {
return;
}
myServer.uploadLeakBlocking(heapDump.heapDumpFile, leakInfo);
}
}
請(qǐng)確認(rèn) release 版本 使用 RefWatcher.DISABLED:
public class ExampleApplication extends Application {
public static RefWatcher getRefWatcher(Context context) {
ExampleApplication application = (ExampleApplication) context.getApplicationContext();
return application.refWatcher;
}
private RefWatcher refWatcher;
@Override public void onCreate() {
super.onCreate();
refWatcher = installLeakCanary();
}
protected RefWatcher installLeakCanary() {
return RefWatcher.DISABLED;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
自定義 RefWatcher:
public class DebugExampleApplication extends ExampleApplication {
protected RefWatcher installLeakCanary() {
return LeakCanary.install(app, LeakUploadService.class);
}
}
別忘了注冊(cè) service:
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas./apk/res/android"
xmlns:tools="http://schemas./tools"
>
<application android:name="com.example.DebugExampleApplication">
<service android:name="com.example.LeakUploadService" />
</application>
</manifest>
demo
一個(gè)非常簡(jiǎn)單的 LeakCanary demo: https://github.com/liaohuqiu/leakcanary-demo
|