Dropbox 如何解决Android App的内存泄漏问题?

{"type":"doc","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"本文最初发布于Dropbox技术博客,经原作者授权由InfoQ中文站翻译并分享。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"当应用程序为对象分配内存,而对象不再被使用时却没有释放,就会发生内存泄漏。随着时间的推移,泄漏的内存会累积,导致应用程序性能变差,甚至崩溃。泄漏可能发生在任何程序和平台上,但由于"},{"type":"link","attrs":{"href":"https:\/\/developer.android.com\/guide\/components\/activities\/activity-lifecycle?fileGuid=dg5RuSiDPDkmicBU","title":"","type":null},"content":[{"type":"text","text":"活动生命周期"}]},{"type":"text","text":"的复杂性,这种情况在Android应用中尤其普遍。最新的Android 模式,如"},{"type":"link","attrs":{"href":"https:\/\/developer.android.com\/topic\/libraries\/architecture\/viewmodel?fileGuid=dg5RuSiDPDkmicBU","title":"","type":null},"content":[{"type":"text","text":"ViewModel"}]},{"type":"text","text":"和"},{"type":"link","attrs":{"href":"https:\/\/developer.android.com\/reference\/androidx\/lifecycle\/LifecycleObserver?fileGuid=dg5RuSiDPDkmicBU","title":"","type":null},"content":[{"type":"text","text":"LifecycleObserver"}]},{"type":"text","text":"可以帮助避免内存泄漏,但如果你遵循旧的模式或不知道要注意什么,很容易漏过错误。"}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"常见例子"}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"引用长期运行的服务"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https:\/\/static001.geekbang.org\/infoq\/74\/749fee0d5444617a4ac48681c9de01dc.png","alt":null,"title":null,"style":[{"key":"width","value":"75%"},{"key":"bordertype","value":"none"}],"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":"center","origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":"Fragment引用了一个活动,而该活动引用一个长期运行的服务"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在这种情况下,我们有一个标准设置,活动持有一个长期运行的服务的引用,然后是Fragment及其视图持有活动的引用。例如,假设活动以某种方式创建了对其子Fragment的引用。然后,只要活动还在,Fragment也会继续存在。那么在Fragment的"},{"type":"codeinline","content":[{"type":"text","text":"onDestroy"}]},{"type":"text","text":"和活动的"},{"type":"codeinline","content":[{"type":"text","text":"onDestroy"}]},{"type":"text","text":"之间就发生了内存泄漏。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https:\/\/static001.geekbang.org\/infoq\/a5\/a56acbe29ef494e868422366bb2a4b86.png","alt":null,"title":null,"style":[{"key":"width","value":"75%"},{"key":"bordertype","value":"none"}],"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":"center","origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":"该Fragment永远不会再使用,但它会一直在内存中"}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"长期运行的服务引用了Fragment视图"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"另一方面,如果服务获得了Fragment视图的引用呢?"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"首先,视图现在将在服务的整个持续时间内保持活动状态。此外,因为视图持有对其父活动的引用,所以该活动现在也会泄漏。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https:\/\/static001.geekbang.org\/infoq\/bf\/bf03b2c00b71243264003a106a657155.png","alt":null,"title":null,"style":[{"key":"width","value":"75%"},{"key":"bordertype","value":"none"}],"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":"center","origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":"只要服务存在,FragmentView 和Activity 都会浪费内存"}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"检测内存泄漏"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"现在,我们已经知道了内存泄漏是如何发生的。让我们讨论下如何检测它们。显然,第一步是检查你的应用是否会因为"},{"type":"codeinline","content":[{"type":"text","text":"OutOfMemoryError"}]},{"type":"text","text":"而崩溃。除非单个屏幕占用的内存比手机可用内存还多,否则肯定在某个地方存在内存泄漏。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https:\/\/static001.geekbang.org\/infoq\/0c\/0c927622532d4bbc0315aff0cc9ebb4a.png","alt":null,"title":null,"style":[{"key":"width","value":"75%"},{"key":"bordertype","value":"none"}],"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"这种方法只告诉你存在的问题,而不是根本原因。内存泄漏可能发生在任何地方,记录的崩溃并不没有指向泄漏,而是指向最终提示内存使用超过限制的屏幕。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"你可以检查所有的面包屑控件,看看它们是否有一些相似之处,但很可能罪魁祸首并不容易识别。让我们研究下其他选项。"}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"LeakCanary"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"link","attrs":{"href":"https:\/\/square.github.io\/leakcanary\/#:~:text=LeakCanary%20is%20a%20memory%20leak,developers%20dramatically%20reduce%20OutOfMemoryError%20crashes.?fileGuid=dg5RuSiDPDkmicBU","title":"","type":null},"content":[{"type":"text","text":"LeakCanary"}]},{"type":"text","text":"是目前最好的工具之一,它是一个用于Android的内存泄漏检测库。我们只需在构建中"},{"type":"link","attrs":{"href":"https:\/\/square.github.io\/leakcanary\/getting_started\/?fileGuid=dg5RuSiDPDkmicBU","title":"","type":null},"content":[{"type":"text","text":"添加一个build.gradle文件依赖项"}]},{"type":"text","text":"。下一次,我们安装和运行我们的应用时,LeakCanary将与它一起运行。当我们在应用中导航时,LeakCanary会偶尔暂停以转储内存,并提供检测到的泄漏痕迹。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"这个工具比我们之前的方法要好得多。但是这个过程仍然是手动的,每个开发人员只有他们个人遇到的内存泄漏的本地副本。我们可以做得更好!"}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"LeakCanary和Bugsnag"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"LeakCanary提供了一个非常方便的代码配方("},{"type":"link","attrs":{"href":"https:\/\/square.github.io\/leakcanary\/recipes\/#uploading-to-bugsnag?fileGuid=dg5RuSiDPDkmicBU","title":"","type":null},"content":[{"type":"text","text":"code recipe"}]},{"type":"text","text":"),用于将发现的泄漏上传到"},{"type":"link","attrs":{"href":"https:\/\/www.bugsnag.com\/?fileGuid=dg5RuSiDPDkmicBU","title":"","type":null},"content":[{"type":"text","text":"Bugsnag"}]},{"type":"text","text":"。我们可以跟踪内存泄漏,就像我们在应用程序中跟踪任何其他警告或崩溃。我们甚至可以更进一步,使用"},{"type":"link","attrs":{"href":"https:\/\/www.bugsnag.com\/integrations?fileGuid=dg5RuSiDPDkmicBU","title":"","type":null},"content":[{"type":"text","text":"Bugsnag Integration"}]},{"type":"text","text":"将其连接到项目管理软件,如Jira,以获得更好的可见性和问责制。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https:\/\/static001.geekbang.org\/infoq\/95\/95803f8dca7ba2cafb63a52d7fb79d1e.png","alt":null,"title":null,"style":[{"key":"width","value":"75%"},{"key":"bordertype","value":"none"}],"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":"center","origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":"Bugsnag连接到Jira"}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"LeakCanary和集成测试"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"另一种提高自动化的方法是将LeakCanary与CI测试连接起来。同样,我们有一个"},{"type":"link","attrs":{"href":"https:\/\/square.github.io\/leakcanary\/recipes\/#running-leakcanary-in-instrumentation-tests?fileGuid=dg5RuSiDPDkmicBU","title":"","type":null},"content":[{"type":"text","text":"代码配方"}]},{"type":"text","text":"。以下内容来自官方文件:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"LeakCanary提供了一个专门用于在UI测试中检测漏洞的构件,它提供了一个运行侦听器,后者会等待测试结束,如果测试成功,它将查找留存的对象,在需要时触发堆转储并执行分析。"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"注意,LeakCanary会降低测试速度,因为它每次都会在其侦听的测试结束后转储堆。在我们的例子中,由于我们的"},{"type":"link","attrs":{"href":"https:\/\/dropbox.tech\/mobile\/revamping-the-android-testing-pipeline-at-dropbox?fileGuid=dg5RuSiDPDkmicBU","title":"","type":null},"content":[{"type":"text","text":"选择性测试和分片设置"}]},{"type":"text","text":",额外增加的时间可以忽略不计。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"最终,就像CI上的任何其他构建或测试失败一样,内存泄漏也会被暴露出来,并且漏洞跟踪信息也被记录了下来。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在CI上运行LeakCanary帮助我们学到了更好的编码模式,特别是涉及到新的库时,在任何代码进入生产环境前。例如,当我们使用"},{"type":"link","attrs":{"href":"https:\/\/github.com\/airbnb\/mavericks?fileGuid=dg5RuSiDPDkmicBU","title":"","type":null},"content":[{"type":"text","text":"MvRx"}]},{"type":"text","text":"测试时,它发现了这个漏洞:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"plain"},"content":[{"type":"text","text":"Test failed because application memory leaks were detected: ==================================== HEAP ANALYSIS RESULT ==================================== 4 APPLICATION LEAKS References underlined with \"~~~\" are likely causes. Learn more at https:\/\/squ.re\/leaks. 198449 bytes retained by leaking objects Signature: 6bf2ba80511dcb6ab9697257143e3071fca4 ┬─── \n│ GC Root: System class \n│ ├─ com.airbnb.mvrx.mocking.MockableMavericks class \n│ Leaking: NO (a class is never leaking) \n│ ↓ static MockableMavericks.mockStateHolder \n│ ~~~~~~~~~~~~~~~ \n├─ com.airbnb.mvrx.mocking.MockStateHolder instance \n│ Leaking: UNKNOWN \n│ ↓ MockStateHolder.delegateInfoMap \n│ ~~~~~~~~~~~~~~~ \n├─ java.util.LinkedHashMap instance \n│ Leaking: UNKNOWN \n│ ↓ LinkedHashMap.header \n│ ~~~~~~ \n├─ java.util.LinkedHashMap$LinkedEntry instance \n│ Leaking: UNKNOWN \n│ ↓ LinkedHashMap$LinkedEntry.prv \n│ ~~~ \n├─ java.util.LinkedHashMap$LinkedEntry instance \n│ Leaking: UNKNOWN \n│ ↓ LinkedHashMap$LinkedEntry.key \n│ ~~~ \n╰→ com.dropbox.product.android.dbapp.photos.ui.view.PhotosFragment instance \n Leaking: YES (ObjectWatcher was watching this because com.dropbox.product.android.dbapp.photos.ui.view.PhotosFragment received Fragment#onDestroy() callback and Fragment#mFragmentManager is null) \n key = 391c9051-ad2c-4282-9279-d7df13d205c3 \n watchDurationMillis = 7304 \n retainedDurationMillis = 2304 198427 bytes retained by leaking objects \n Signature: d1c9f9707034dd15604d8f2e63ff3bf3ecb61f8\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"事实证明,在编写测试时,我们没有正确地清理测试。添加几行代码可以避免泄漏:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"plain"},"content":[{"type":"text","text":" @After\n fun teardown() {\n scenario.close()\n val holder = MockableMavericks.mockStateHolder\n holder.clearAllMocks()\n }\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"你可能会想:既然这种内存泄漏只发生在测试中,那么修复它真的那么重要吗?好吧,那就看你了!与代码检查一样,泄漏检测可以告诉你什么时候出现了"},{"type":"link","attrs":{"href":"https:\/\/en.wikipedia.org\/wiki\/Code_smell?fileGuid=dg5RuSiDPDkmicBU","title":"","type":null},"content":[{"type":"text","text":"代码气味"}]},{"type":"text","text":"或"},{"type":"link","attrs":{"href":"https:\/\/en.wikipedia.org\/wiki\/Software_design_pattern?fileGuid=dg5RuSiDPDkmicBU","title":"","type":null},"content":[{"type":"text","text":"糟糕的编码模式"}]},{"type":"text","text":"。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"它可以帮助工程师编写更健壮的代码——在本例中,我们知道了"},{"type":"codeinline","content":[{"type":"text","text":"clearAllMocks()"}]},{"type":"text","text":"。泄漏的严重程度,以及是否必须修复,都是工程师可以做出的决定。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"对于我们不想运行泄漏检测的测试,我们编写了一个简单的注解:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"plain"},"content":[{"type":"text","text":"@Retention(RetentionPolicy.RUNTIME)\n@Target({ElementType.METHOD, ElementType.TYPE})\npublic @interface SkipLeakDetection {\n \/**\n * The reason why the test should skip leak detection.\n *\/\n String value();\n}\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我们的类重写了LeakCanary的"},{"type":"codeinline","content":[{"type":"text","text":"FailOnLeakRunListener()"}]},{"type":"text","text":":"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"plain"},"content":[{"type":"text","text":"override fun skipLeakDetectionReason(description: Description): String? {\n return when {\n description.getAnnotation(SkipLeakDetection::class.java) != null ->\n \"is annotated with @SkipLeakDetection\"\n description.testClass.isAnnotationPresent(SkipLeakDetection::class.java) ->\n \"class is annotated with @SkipLeakDetection\"\n else -> null\n }\n}\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"单个测试或整个测试类可以使用这个注解跳过泄漏检测。"}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"修复内存泄漏"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"现在,我们讨论了各种查找和暴露内存泄漏的方法。下面,我们讨论一下如何真正理解和修复它们。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"LeakCanary提供的泄漏跟踪是诊断泄漏最有用的工具。本质上讲,泄漏跟踪打印出与泄漏对象关联的引用链,并解释为什么将其视为泄漏。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"关于如何阅读和使用泄漏跟踪,LeakCanary有了很好的"},{"type":"link","attrs":{"href":"https:\/\/square.github.io\/leakcanary\/fundamentals-fixing-a-memory-leak\/?fileGuid=dg5RuSiDPDkmicBU","title":"","type":null},"content":[{"type":"text","text":"文档"}]},{"type":"text","text":",这里无需重复。取而代之,让我们回顾一下我自己经常要处理的两类内存泄漏。"}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"视图"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我们经常看到视图被声明为类级变量:"},{"type":"codeinline","content":[{"type":"text","text":"private TextView myTextView"}]},{"type":"text","text":";或者,现在有更多的Android代码正在用"},{"type":"link","attrs":{"href":"https:\/\/kotlinlang.org\/?fileGuid=dg5RuSiDPDkmicBU","title":"","type":null},"content":[{"type":"text","text":"Kotlin"}]},{"type":"text","text":"编写:"},{"type":"codeinline","content":[{"type":"text","text":"private lateinit var myTextView: textview"}]},{"type":"text","text":"——非常常见,我们没有意识到这些都可以导致内存泄漏。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"除非在Fragment的"},{"type":"codeinline","content":[{"type":"text","text":"onDestroyView"}]},{"type":"text","text":"中消除对这些字段的引用,(对于"},{"type":"codeinline","content":[{"type":"text","text":"lateinit"}]},{"type":"text","text":"变量不能这么做),否则对这些视图的引用在Fragment的整个生命周期内都会存在,而不是像它们应该的那样在Fragment视图的生命周期内存在。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"导致内存泄漏的一个最简单场景是:我们在FragmentA上。我们导航到FragmentB,现在FragmentA在栈里。FragmentA没有被销毁,但是FragmentA的视图被销毁了。任何绑定到FragmentA生命周期的视图现在已经不需要了,但都还保留在内存中。"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在大多数情况下,这些泄漏很小,不会导致任何性能问题或崩溃。但是对于保存对象和数据、图像、视图\/数据绑定等的视图,我们更有可能遇到麻烦。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"所以,如果可能的话,避免在类级变量中存储视图,或者确保在"},{"type":"codeinline","content":[{"type":"text","text":"onDestroyView"}]},{"type":"text","text":"中正确地清理它们。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"说到视图\/数据绑定,Android的"},{"type":"link","attrs":{"href":"https:\/\/developer.android.com\/topic\/libraries\/view-binding?fileGuid=dg5RuSiDPDkmicBU","title":"","type":null},"content":[{"type":"text","text":"视图绑定文档"}]},{"type":"text","text":"明确地告诉我们:字段必须被清除以防止泄漏。他们提供的代码片段建议我们做以下工作:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"plain"},"content":[{"type":"text","text":"private var _binding: ResultProfileBinding? = null\n\/\/ This property is only valid between onCreateView and\n\/\/ onDestroyView.\nprivate val binding get() = _binding!!\noverride fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?\n): View? {\n _binding = ResultProfileBinding.inflate(inflater, container, false)\n val view = binding.root\n return view\n}\noverride fun onDestroyView() {\n super.onDestroyView()\n _binding = null\n}\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"每个 Fragment 中都有很多样板代码(另外,避免使用"},{"type":"link","attrs":{"href":"https:\/\/stackoverflow.com\/questions\/34342413\/what-is-the-kotlin-double-bang-operator?fileGuid=dg5RuSiDPDkmicBU","title":"","type":null},"content":[{"type":"text","text":"!!"}]},{"type":"text","text":",因为如果变量为空,这会抛出"},{"type":"codeinline","content":[{"type":"text","text":"KotlinNullPointerException"}]},{"type":"text","text":"。使用显式空处理来代替。)我们解决这个问题的方法是创建一个"},{"type":"codeinline","content":[{"type":"text","text":"ViewBindingHolder"}]},{"type":"text","text":"(和"},{"type":"codeinline","content":[{"type":"text","text":"DataBindingHolder"}]},{"type":"text","text":"),Fragment可以实现为下面这样:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"plain"},"content":[{"type":"text","text":"interface ViewBindingHolder {\n var binding: B?\n \/\/ Only valid between onCreateView and onDestroyView.\n fun requireBinding() = checkNotNull(binding)\n fun requireBinding(lambda: (B) -> Unit) {\n binding?.let {\n lambda(it)\n }}\n \/**\n * Make sure to use this with Fragment.viewLifecycleOwner\n *\/\n fun registerBinding(binding: B, lifecycleOwner: LifecycleOwner) {\n this.binding = binding\n lifecycleOwner.lifecycle.addObserver(object : DefaultLifecycleObserver {\n override fun onDestroy(owner: LifecycleOwner) {\n owner.lifecycle.removeObserver(this)\n [email protected] = null\n }\n })\n }\n}\ninterface DataBindingHolder : ViewBindingHolder\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"这为 Fragment 提供了一种简单而干净的方式:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"确保在需要绑定时提供绑定"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"只有在绑定可用时才执行某些代码"}]}]},{"type":"listitem","attrs":{"listStyle":null},"content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"自动在"},{"type":"codeinline","content":[{"type":"text","text":"onDestroyView"}]},{"type":"text","text":"上清除绑定"}]}]}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"暂时性泄漏"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"这些泄漏只会存在很短时间。特别是,我们遇到过一个由"},{"type":"codeinline","content":[{"type":"text","text":"EditTextView"}]},{"type":"text","text":"异步任务引起的泄漏。异步任务持续的时间恰好比 LeakCanary 的默认等待时间长,因此,即使内存很快就被正确地释放了,也会报告一个泄漏。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"如果你怀疑自己遇到了暂时性泄漏,一个很好的检查方法是使用Android Studio的"},{"type":"link","attrs":{"href":"https:\/\/developer.android.com\/studio\/profile\/memory-profiler?fileGuid=dg5RuSiDPDkmicBU","title":"","type":null},"content":[{"type":"text","text":"内存分析器"}]},{"type":"text","text":"。一旦在分析器中启动会话,就可以按步骤重现泄漏,但是在转储堆并检查之前要等待更长时间。经过这段额外的时间后,泄漏可能就消失了。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https:\/\/static001.geekbang.org\/infoq\/65\/65a40b60466063341938623772fb30ae.png","alt":null,"title":null,"style":[{"key":"width","value":"75%"},{"key":"bordertype","value":"none"}],"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":"center","origin":null},"content":[{"type":"text","marks":[{"type":"size","attrs":{"size":10}}],"text":"Android Studio的内存分析器显示了清理暂时性泄漏的效果"}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"经常测试,尽早修复"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我们希望,通过本文介绍,你能在自己的应用程序中跟踪和解决内存泄漏!与许多Bug和其他问题一样,最好是能经常测试,在糟糕的模式扎根代码库之前尽早修复。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"作为一名开发人员,你一定要记住,虽然内存泄漏并不总是会影响应用性能,但低端机型和手机内存小的用户会感激你为他们所做的工作。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"原文链接:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"https:\/\/dropbox.tech\/mobile\/detecting-memory-leaks-in-android-applications?fileGuid=dg5RuSiDPDkmicBU"}]}]}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章