LeakCanary是一個非常受歡迎的android內(nèi)存泄漏檢測工具捐腿,只需要在項(xiàng)目中引入即可
debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.5'
然后 沒有什么 初始化驶拱,注冊 之類的任何操作坛增,就OK了翅雏。
很是奇怪撒穷,下面從 LeakCanary 如何啟動調(diào)用和工作原理做一下 簡單的總結(jié)分析妆绞;
LeakCanary如何啟動調(diào)用
既然LeakCanary,沒有任何初始化的代碼調(diào)用恋沃,LeakCanary 就有可能在AndroidManifest清單文件中 聲明了ContentProvider必搞,借助ContentProvider的特性來實(shí)現(xiàn)初始化;
先看一下 debug.apk中的 清單文件內(nèi)容:
果然如此囊咏,LeakCanary的aar中 已經(jīng)聲明了這個 AppWatcherInstaller 對象恕洲,所以就不需要在app中的AndroidManifest中 再次聲明了;
/**
* Content providers are loaded before the application class is created. [AppWatcherInstaller] is
* used to install [leakcanary.AppWatcher] on application start.
*/
internal sealed class AppWatcherInstaller : ContentProvider() {
/**
* [MainProcess] automatically sets up the LeakCanary code that runs in the main app process.
*/
internal class MainProcess : AppWatcherInstaller()
/**
* When using the `leakcanary-android-process` artifact instead of `leakcanary-android`,
* [LeakCanaryProcess] automatically sets up the LeakCanary code
*/
internal class LeakCanaryProcess : AppWatcherInstaller()
override fun onCreate(): Boolean {
val application = context!!.applicationContext as Application
AppWatcher.manualInstall(application)
return true
}
...
看一下 自定義的AppWatcherInstaller 內(nèi)容提供者的代碼梅割。
自定義的AppWatcherInstaller 對象霜第,會在Application調(diào)用onCreate方法之前,創(chuàng)建并調(diào)用其自身的onCraete方法;
而且注釋中 已經(jīng)給出了 這一解釋, Content providers are loaded before the application class is created. [AppWatcherInstaller] is used to install [leakcanary.AppWatcher] on application start
從而 調(diào)用
AppWatcher.manualInstall(application)
觸發(fā)了LeakCanary 的初始化方法;
LeakCanary的工作原理
LeakCanary的初始化
//AppWatcher
fun manualInstall(application: Application) {
InternalAppWatcher.install(application)
}
#InternalAppWatcher
fun install(application: Application) {
checkMainThread()
if (this::application.isInitialized) {
return
}
InternalAppWatcher.application = application
if (isDebuggableBuild) {
SharkLog.logger = DefaultCanaryLog()
}
val configProvider = { AppWatcher.config }
ActivityDestroyWatcher.install(application, objectWatcher, configProvider)
FragmentDestroyWatcher.install(application, objectWatcher, configProvider)
onAppWatcherInstalled(application)
}
LeakCanary的初始化 先調(diào)用了AppWatcher的manualInstall方法炮捧,然后又調(diào)用了 InternalAppWatcher的 install方法,關(guān)鍵代碼就在 install方法中惦银;
install方法進(jìn)行了如下操作:
- 檢測當(dāng)前是否在主線程
checkMainThread()
- 持有Application對象
InternalAppWatcher.application = application
3.分別調(diào)了ActivityDestroyWatcher和FragmentDestroyWatcher 的伴生對象的 install 方法
- ActivityDestroyWatcher.install
//ActivityDestroyWatcher
internal class ActivityDestroyWatcher private constructor(
private val objectWatcher: ObjectWatcher,
private val configProvider: () -> Config
) {
private val lifecycleCallbacks =
object : Application.ActivityLifecycleCallbacks by noOpDelegate() {
override fun onActivityDestroyed(activity: Activity) {
if (configProvider().watchActivities) {
objectWatcher.watch(
activity, "${activity::class.java.name} received Activity#onDestroy() callback"
)
}
}
}
companion object {
fun install(
application: Application,
objectWatcher: ObjectWatcher,
configProvider: () -> Config
) {
val activityDestroyWatcher =
ActivityDestroyWatcher(objectWatcher, configProvider)
application.registerActivityLifecycleCallbacks(activityDestroyWatcher.lifecycleCallbacks)
}
}
}
ActivityDestroyWatcher.install方法 為application 注冊了一個 Activity生命周期變化監(jiān)聽的對象 lifecycleCallbacks 咆课;在每個Activity對象 被銷毀 調(diào)用onDestroyed方法時,使用objectWatcher 對象來 檢測activity對象的回收
- FragmentDestroyWatcher.install
FragmentDestroyWatcher.install方法扯俱,和ActivityDestroyWatcher.install類型书蚪,也是為aplication對象 注冊了一個Activity生命周期變化的監(jiān)聽對象,但是主要是為了 監(jiān)聽Fragment對象的銷毀 ,在調(diào)用 onFragmentDestroyed(),onFragmentViewDestroyed()時迅栅,使用objectWatcher 對象來 檢測view對象和fragment對象的回收殊校。
//FragmentDestroyWatcher
fun install(
application: Application,
objectWatcher: ObjectWatcher,
configProvider: () -> AppWatcher.Config
) {
val fragmentDestroyWatchers = mutableListOf<(Activity) -> Unit>()
if (SDK_INT >= O) {
fragmentDestroyWatchers.add(
AndroidOFragmentDestroyWatcher(objectWatcher, configProvider)
)
}
...
application.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks by noOpDelegate() {
override fun onActivityCreated(
activity: Activity,
savedInstanceState: Bundle?
) {
for (watcher in fragmentDestroyWatchers) {
watcher(activity)
}
}
})
}
//AndroidOFragmentDestroyWatcher
internal class AndroidOFragmentDestroyWatcher(
private val objectWatcher: ObjectWatcher,
private val configProvider: () -> Config
) : (Activity) -> Unit {
private val fragmentLifecycleCallbacks = object : FragmentManager.FragmentLifecycleCallbacks() {
override fun onFragmentViewDestroyed(
fm: FragmentManager,
fragment: Fragment
) {
val view = fragment.view
if (view != null && configProvider().watchFragmentViews) {
objectWatcher.watch(
view, "${fragment::class.java.name} received Fragment#onDestroyView() callback " +
"(references to its views should be cleared to prevent leaks)"
)
}
}
override fun onFragmentDestroyed(
fm: FragmentManager,
fragment: Fragment
) {
if (configProvider().watchFragments) {
objectWatcher.watch(
fragment, "${fragment::class.java.name} received Fragment#onDestroy() callback"
)
}
}
}
override fun invoke(activity: Activity) {
val fragmentManager = activity.fragmentManager
fragmentManager.registerFragmentLifecycleCallbacks(fragmentLifecycleCallbacks, true)
}
}
LeakCanary 檢測對象是否被回收
LeakCanary 檢測內(nèi)存泄漏的關(guān)鍵就是,在Activity或者Fragment銷毀的時候读存,觸發(fā)一次gc內(nèi)存回收为流,然后判斷Activity或者Fragment對象 是否依然存在,如果對象依然存在沒有被回收让簿,就說明 可能存在內(nèi)存泄漏敬察,積累過多可能引發(fā)OOM內(nèi)存溢出。
這樣就有一個 疑問尔当,如何判斷一個對象是否被gc回收呢莲祸?
借助弱引用的特性,只要jvm的垃圾回收器 掃描到 弱引用對象 ,弱引用對象 就會被回收釋放掉锐帜,但是如果 沒有被回收 只能說明 這個對象還被其他static變量引用 或者native method引用田盈;
偽代碼如下:
Integer a=1;
ReferenceQueue<Integer> referenceQueue = new ReferenceQueue<>();
WeakReference<Integer> weakReference = new WeakReference<>(a, referenceQueue);
//觸發(fā)gc,5秒后 檢測referenceQueue是否存在對象
System.gc();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (referenceQueue.poll() != null) {
//a對象 已經(jīng)被回收
}
}
},5000);