简体   繁体   English

为什么使用活动上下文会导致上下文内存泄漏

[英]Why using Activity context cause Context memory leak

I've searched many times on Google about "use Application Context or Activity Context ". 我在Google上搜索过很多有关“使用应用程序上下文活动上下文 ”的信息。

Most of the answers are: "Use application context getApplicationContext() as much as possible to prevent Context memory leak". 大多数答案是:“尽可能使用应用程序上下文getApplicationContext()来防止上下文内存泄漏”。

I am confused: 我很困惑:

Why using Activity context may cause memory leak although: 为什么使用Activity上下文可能导致内存泄漏,但:

" Activity context is associated with to the activity and can be destroyed if the activity is destroyed" 活动上下文与活动相关联,如果活动被破坏,则可以被破坏”

BUT

" Application context is associated with the application and will always be same throughout the life of application -- it does not change" ? 应用程序上下文与应用程序相关联,并且在应用程序的整个生命周期中始终是相同的-不会改变”?

Activity instances are transient: they come and go based on user interaction with your app. Activity实例是瞬态的:它们根据用户与您的应用程序的交互来来去去。 Your app overall has a single Application instance which exists for the lifetime of the process of your app. 您的应用程序总体上只有一个Application实例,该实例在应用程序的整个生命周期中都存在。 Take a simple example: the user starts your app via the launcher (home screen), your MainActivity is created and launched. 举个简单的例子:用户通过启动器(主屏幕)启动您的应用程序,创建并启动了MainActivity If this was the first launch then your app's process is started an an Application context created as well. 如果这是第一次启动,则将启动您的应用程序流程,并创建一个Application上下文。 The user presses the BACK key and your MainActivity is exited, going through its onDestroy() . 用户按下BACK键,并通过其onDestroy()退出MainActivity Now if the user re-launches your app, a new instance of MainActivity is created. 现在,如果用户重新启动您的应用程序,则将创建一个新的MainActivity实例。 However, your app's process was not killed (assuming there was no memory pressure) so the Application object singleton still exists and is valid. 但是,您的应用程序进程并未终止(假设没有内存压力),因此Application对象单例仍然存在并且有效。 Your original MainActivity instance does not exist. 您原来的MainActivity实例不存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM