效能相關:UI卡頓 / ANR / 記憶體洩漏——>OOM
記憶體洩漏的本質:較長生命週期物件持有較短生命週期的引用導致,較短引用沒法釋放記憶體。
GcRoots:Garbage Collector 的物件, 收集非GC Roots的引用物件,通常的GC Root有哪些?
通過System Class Loader或者Boot Class Loader載入的class物件,通過自定義類載入器載入的class不一定是GC Root
處於啟用狀態的執行緒
棧中的物件
JNI棧中的物件
JNI中的全域性物件
正在被用於同步的各種鎖物件
JVM自身持有的物件,比如系統類載入器等。
複製程式碼
通常這裡涉及的 靜態的物件,其它執行執行緒持有當前的引用。
LeakCanary原理watch一個即將要銷燬的物件:
- 棧(stack)
- 堆(heap)
- 方法區(method)
常見的記憶體洩漏:
- 單例持有context, 寫成 ApplicationContext
- 非靜態內部類建立靜態例項造成的記憶體洩漏(改成靜態的內部類)
- Handler(TLS,handler生命週期跟Activity的生命週期不一樣) handler.postDelay延遲傳送。原因message 持有handler,handler持有Activity,將Handler設定為靜態的(以弱引用的方式持有Activity)
- 執行緒的記憶體洩漏。AsyncTask,Thread+Runnable,以及Handler(將他們定義為static, 呼叫AsyncTask的Cancel方法)
- Webview,hybird。webview載入網頁申請native記憶體載入頁面,(1.將webview放在單獨的Webview的程式裡; 2. 在Webview所在的Activity在onDestory的時候killProcess)
LeakCanary原始碼:
記憶體洩漏會造成OOM的罪魁禍首 探究原始碼,檢測Activity洩漏的機制,LeakCanary的原理
Activity洩漏檢測原理
- 將Activity Destory之後將它放在一個WeakReference
- 將這個WeakReference放到引用佇列ReferenceQueue
####ReferenceQueue 軟引用/弱引用
物件被GC回收,Java虛擬機器會把它加入到ReferenceQueue中
關於ReferenceQueue: www.cnblogs.com/dreamroute/…
四種引用型別:
StrongReference
softReference(記憶體空間不夠時才回收)
WeakReference()
virtualReference(虛引用)
RefWatcher
監控Activity的記憶體洩漏
LeakCanary.enableDisplayLeakActivity(控制彈框)
-
建立一個refwatcher,啟動一個ActivityRefWatcher監聽Activity的生命週期的情況(新版本沒有排除系統Reference的引用)
//Refwatcher類結構 public final class RefWatcher { public static final RefWatcher DISABLED = new RefWatcherBuilder<>().build(); private final WatchExecutor watchExecutor;//執行記憶體洩漏檢測用的 private final DebuggerControl debuggerControl;//查詢是否在程式碼除錯中,除錯的時候就不檢測 private final GcTrigger gcTrigger;//處理GC的,用於判斷洩漏之前給最後一次機會是否會GC,否者會顯示出來 private final HeapDumper heapDumper;//Dump出記憶體洩漏的堆檔案 private final HeapDump.Listener heapdumpListener;//分析產生Heap檔案的回撥 private final HeapDump.Builder heapDumpBuilder; private final Set<String> retainedKeys;//待檢測的產生洩漏的Key private final ReferenceQueue<Object> queue;//引用佇列,判斷弱引用持有的物件是否執行了GC回收 ...... } public void watch(Object watchedReference, String referenceName) { if (this == DISABLED) { return; } checkNotNull(watchedReference, "watchedReference"); checkNotNull(referenceName, "referenceName"); final long watchStartNanoTime = System.nanoTime(); //返回一個Key值,唯一的 String key = UUID.randomUUID().toString(); //加入key到待檢測的佇列當中 retainedKeys.add(key); final KeyedWeakReference reference = new KeyedWeakReference(watchedReference, key, referenceName, queue); //開啟非同步執行緒分析弱引用reference ensureGoneAsync(watchStartNanoTime, reference); } 複製程式碼
-
通過ActivityLifecycleCallbacks把Activity的ondestory生命週期關聯
原來的ActivityRefWatcher被廢棄了
/** * @deprecated This was initially part of the LeakCanary API, but should not be any more. * {@link AndroidRefWatcherBuilder#watchActivities} should be used instead. * We will make this class internal in the next major version. */ @SuppressWarnings("DeprecatedIsStillUsed") @Deprecated public final class ActivityRefWatcher {} 複製程式碼
換成 AndroidRefWatcherBuilder, 其實最終繫結 ActivityRefWatcher的生命週期
// LeakCanary的入口 public static @NonNull RefWatcher install(@NonNull Application application) { return refWatcher(application).listenerServiceClass(DisplayLeakService.class) .excludedRefs(AndroidExcludedRefs.createAppDefaults().build()) .buildAndInstall(); } /** * Creates a {@link RefWatcher} instance and makes it available through {@link * LeakCanary#installedRefWatcher()}. * * Also starts watching activity references if {@link #watchActivities(boolean)} was set to true. * * @throws UnsupportedOperationException if called more than once per Android process. */ public @NonNull RefWatcher buildAndInstall() { if (LeakCanaryInternals.installedRefWatcher != null) { throw new UnsupportedOperationException("buildAndInstall() should only be called once."); } RefWatcher refWatcher = build(); if (refWatcher != DISABLED) { LeakCanaryInternals.setEnabledAsync(context, DisplayLeakActivity.class, true); if (watchActivities) { //這裡又呼叫原來廢棄的ActivityRefWatcher的方法 ActivityRefWatcher.install(context, refWatcher); } if (watchFragments) { FragmentRefWatcher.Helper.install(context, refWatcher); } } LeakCanaryInternals.installedRefWatcher = refWatcher; return refWatcher; } //ActivityRefWatcher類下面的 public static void install(@NonNull Context context, @NonNull RefWatcher refWatcher) { Application application = (Application) context.getApplicationContext(); //建立activityRefWatcher ActivityRefWatcher activityRefWatcher = new ActivityRefWatcher(application,refWatcher); //繫結生命週期 application.registerActivityLifecycleCallbacks (activityRefWatcher.lifecycleCallbacks); } private final Application.ActivityLifecycleCallbacks lifecycleCallbacks = new ActivityLifecycleCallbacksAdapter() { @Override public void onActivityDestroyed(Activity activity) { //呼叫watch方法,監聽activity的洩漏 refWatcher.watch(activity); } }; 複製程式碼
-
最後線上程池中去開始分析我們的洩漏
//開啟執行緒池分析
private void ensureGoneAsync(final long watchStartNanoTime, final KeyedWeakReference reference) {
watchExecutor.execute(new Retryable() {
@Override public Retryable.Result run() {
return ensureGone(reference, watchStartNanoTime);
}
});
}
//容錯性考慮
@SuppressWarnings("ReferenceEquality") // Explicitly checking for named null.
Retryable.Result ensureGone(final KeyedWeakReference reference, final long watchStartNanoTime) {
long gcStartNanoTime = System.nanoTime();
//從watch到GC的時間
long watchDurationMs = NANOSECONDS.toMillis(gcStartNanoTime - watchStartNanoTime);
//把已經回收的物件引用從 標記記憶體洩漏的retainedKeys中清除掉
removeWeaklyReachableReferences();
if (debuggerControl.isDebuggerAttached()) {
// The debugger can create false leaks.
return RETRY;
}
if (gone(reference)) {
return DONE;
}
//觸發GC後又會把回收的物件引用加入到Queue中。
gcTrigger.runGc();
removeWeaklyReachableReferences();
if (!gone(reference)) {
long startDumpHeap = System.nanoTime();
long gcDurationMs = NANOSECONDS.toMillis(startDumpHeap - gcStartNanoTime);
File heapDumpFile = heapDumper.dumpHeap();
if (heapDumpFile == RETRY_LATER) {
// Could not dump the heap.
return RETRY;
}
long heapDumpDurationMs = NANOSECONDS.toMillis(System.nanoTime() - startDumpHeap);
HeapDump heapDump = heapDumpBuilder.heapDumpFile(heapDumpFile).referenceKey(reference.key)
.referenceName(reference.name)
.watchDurationMs(watchDurationMs)
.gcDurationMs(gcDurationMs)
.heapDumpDurationMs(heapDumpDurationMs)
.build();
heapdumpListener.analyze(heapDump);
}
return DONE;
}
//從retainedKeys中去除已經GC掉的物件
private void removeWeaklyReachableReferences() {
// WeakReferences are enqueued as soon as the object to which they point to becomes weakly
// reachable. This is before finalization or garbage collection has actually happened.
KeyedWeakReference ref;
while ((ref = (KeyedWeakReference) queue.poll()) != null) {
retainedKeys.remove(ref.key);
}
}
複製程式碼
在ServiceHeapDumpListener (implements HeapDump.Listener)開啟真正的分析:
@Override public void analyze(@NonNull HeapDump heapDump) {
checkNotNull(heapDump, "heapDump");
HeapAnalyzerService.runAnalysis(context, heapDump, listenerServiceClass);
}
複製程式碼
public final class HeapAnalyzerService extends ForegroundService
implements AnalyzerProgressListener {
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) {
setEnabledBlocking(context, HeapAnalyzerService.class, true);
setEnabledBlocking(context, listenerServiceClass, true);
Intent intent = new Intent(context, HeapAnalyzerService.class);
intent.putExtra(LISTENER_CLASS_EXTRA, listenerServiceClass.getName());
intent.putExtra(HEAPDUMP_EXTRA, heapDump);
ContextCompat.startForegroundService(context, intent);
}
public HeapAnalyzerService() {
super(HeapAnalyzerService.class.getSimpleName(), R.string.leak_canary_notification_analysing);
}
@Override protected void onHandleIntentInForeground(@Nullable Intent intent) {
if (intent == null) {
CanaryLog.d("HeapAnalyzerService received a null intent, ignoring.");
return;
}
String listenerClassName = intent.getStringExtra(LISTENER_CLASS_EXTRA);
HeapDump heapDump = (HeapDump) intent.getSerializableExtra(HEAPDUMP_EXTRA);
//這裡去除調heapDump.excludedRefs對應的系統的
HeapAnalyzer heapAnalyzer =
new HeapAnalyzer(heapDump.excludedRefs, this, heapDump.reachabilityInspectorClasses);
//進一步分析記憶體
AnalysisResult result = heapAnalyzer.checkForLeak(heapDump.heapDumpFile, heapDump.referenceKey,
heapDump.computeRetainedHeapSize);
AbstractAnalysisResultService.sendResultToListener(this, listenerClassName, heapDump, result);
}
}
複製程式碼
- 將.hprof轉化成 SnapShot
- 優化GCRoots
checkForLeak
- 解析dump下檔案的hprof,把dump檔案parse成Snapshot檔案
- 根據前面的弱引用定義的
findLeakTrace: 找到最短的路勁,找到記憶體洩漏大小。
/**
* Searches the heap dump for a {@link KeyedWeakReference} instance with the corresponding key,
* and then computes the shortest strong reference path from that instance to the GC roots.
*/
public @NonNull AnalysisResult checkForLeak(@NonNull File heapDumpFile,
@NonNull String referenceKey,
boolean computeRetainedSize) {
long analysisStartNanoTime = System.nanoTime();
if (!heapDumpFile.exists()) {
Exception exception = new IllegalArgumentException("File does not exist: " + heapDumpFile);
return failure(exception, since(analysisStartNanoTime));
}
try {
listener.onProgressUpdate(READING_HEAP_DUMP_FILE);
//1. 將hprof檔案轉化成Snapshot快照檔案,包含了所有引用物件的路徑。
HprofBuffer buffer = new MemoryMappedFileBuffer(heapDumpFile);
HprofParser parser = new HprofParser(buffer);
listener.onProgressUpdate(PARSING_HEAP_DUMP);
Snapshot snapshot = parser.parse();
listener.onProgressUpdate(DEDUPLICATING_GC_ROOTS);
//2.刪除重複的GCRoots以及物件
deduplicateGcRoots(snapshot);
listener.onProgressUpdate(FINDING_LEAKING_REF);
Instance leakingRef = findLeakingReference(referenceKey, snapshot);
// False alarm, weak reference was cleared in between key check and heap dump.
if (leakingRef == null) {
return noLeak(since(analysisStartNanoTime));
}
return findLeakTrace(analysisStartNanoTime, snapshot, leakingRef, computeRetainedSize);
} catch (Throwable e) {
return failure(e, since(analysisStartNanoTime));
}
}
複製程式碼
- 找到洩漏的路徑
private AnalysisResult findLeakTrace(long analysisStartNanoTime, Snapshot snapshot,
Instance leakingRef, boolean computeRetainedSize) {
listener.onProgressUpdate(FINDING_SHORTEST_PATH);
ShortestPathFinder pathFinder = new ShortestPathFinder(excludedRefs);
ShortestPathFinder.Result result = pathFinder.findPath(snapshot, leakingRef);
// False alarm, no strong reference path to GC Roots.
if (result.leakingNode == null) {
return noLeak(since(analysisStartNanoTime));
}
listener.onProgressUpdate(BUILDING_LEAK_TRACE);
LeakTrace leakTrace = buildLeakTrace(result.leakingNode);
String className = leakingRef.getClassObj().getClassName();
long retainedSize;
if (computeRetainedSize) {
listener.onProgressUpdate(COMPUTING_DOMINATORS);
// Side effect: computes retained size.
snapshot.computeDominators();
Instance leakingInstance = result.leakingNode.instance;
retainedSize = leakingInstance.getTotalRetainedSize();
// TODO: check O sources and see what happened to android.graphics.Bitmap.mBuffer
if (SDK_INT <= N_MR1) {
listener.onProgressUpdate(COMPUTING_BITMAP_SIZE);
retainedSize += computeIgnoredBitmapRetainedSize(snapshot, leakingInstance);
}
} else {
retainedSize = AnalysisResult.RETAINED_HEAP_SKIPPED;
}
return leakDetected(result.excludingKnownLeaks, className, leakTrace, retainedSize,
since(analysisStartNanoTime));
}
複製程式碼
補充:Application:單例模式
- 例項建立方式
- 全域性例項
- 生命週期, 整個生命週期。
Application應用場景
- 初始化 全域性物件、環境配置變數
- 獲取應用當前的記憶體情況
- 監聽應用程式內 所有Activity的生命週期
- 記憶體監控 (onTrimMemory)TrimMemoryLevel、onLowMemory、onTerminate()、onConfigurationChanged
/** @hide */
//記憶體級別,對記憶體進行釋放。
@IntDef(prefix = { "TRIM_MEMORY_" }, value = {
TRIM_MEMORY_COMPLETE,
TRIM_MEMORY_MODERATE,
TRIM_MEMORY_BACKGROUND,
TRIM_MEMORY_UI_HIDDEN,
//記憶體不足
TRIM_MEMORY_RUNNING_CRITICAL,
TRIM_MEMORY_RUNNING_LOW,
TRIM_MEMORY_RUNNING_MODERATE,
})
複製程式碼
onTrimMemory跟 onLowMemory都是記憶體優化的地方。
MAT以及Android Studio本身的記憶體監控: blog.csdn.net/u012760183/…
網路流量和冷啟動
- 整體的效能解決思路
- 應用效能型別
- 各種效能資料指標
效能解決思路
- 監控效能指標,量化指標
- 根據上報統計資訊
- 持續監控並觀察
應用效能種類
- 資源消耗
- 流暢度(網路請求、UI繪製、冷啟動)
各個效能資料指標
-
網路請求流量
通過運營商的網路訪問Internet。
-
日常開發中可以通過tcpdump + Wireshark抓包測試法
-
TrafficStats類:getMobileTxPackets, getMobileRxPackets, getMobileTxBytes, getMobileRxBytes
(讀取linux檔案系統的)
-
-
冷啟動
adb shell am start -W packagename /MainActivity
日誌列印:起點 ->終點
起點:Application的onCreate方法
終點:首頁ActivityOncreate載入完成
- UI卡頓Fps幀率
Fps:
Choreographer:通過日誌監控掉幀現象。
Vsync: 同步訊號,硬體終端
流暢度:實際幀率/理論幀率