防止Android中的内存泄漏 [英] Preventing memory leaks in Android
问题描述
通过获取应用程序上下文在我需要上下文的每个Activity中获得对上下文对象的引用是否明智?我了解到,它可能会导致内存泄漏,从而使您的Activity的上下文对象泛滥成灾,但是当您创建复杂的Activity时,似乎几乎总是需要Context对象.之前,我在Activity类的顶部声明了一个Context变量,并使用onCreate
中的"this"关键字对其进行了初始化.我已经知道这可能是较差的形式,但是可以在调用getApplicationContext()
的onCreate
中初始化Context对象吗?换句话说,这有助于解决我的问题.
Is it wise to get a reference to a Context object in every Activity where I need a Context by getting the Application context? I have learned that it can create memory leaks to throw around your Activity's context object but when you create complex Activities it seems that a Context object is almost always necessary. I was previously declaring a Context variable at the top of the Activity class and initializing it with the "this" keyword in onCreate
. I already know this can be poor form, but is it ok to initialize the Context object in onCreate
calling getApplicationContext()
? In other words does this help solve my problem.
此外,限制静态变量的使用是否是更好的做法?如果我没记错的话,如果我调用一个静态方法,或者从另一个Activity引用一个静态变量,那是否也将另一个Activity保留在内存中?
Also, is it better practice to limit the use of static variables? If I'm not mistaken, if I call a static method, or reference a static variable from a different Activity, won't that keep the other Activity in memory too?
推荐答案
我认为您需要了解应用程序上下文和活动上下文之间的区别,请参阅
I think you need to understand the differences between Application Context and Activity Context, please refer to the answer here.
但是可以在调用getApplicationContext()的onCreate中初始化Context对象吗?换句话说,这有助于解决我的问题.
But is it ok to initialise the Context object in onCreate calling getApplicationContext()? In other words does this help solve my problem.
为什么需要初始化上下文对象?活动本身已经是一个上下文.例如:
Why do you need to initialise a context object? Activity itself is already a context. For example:
Intent intent = new Intent(this, MainActivity.class);
由于活动上下文具有更多功能,因此您无需从应用程序上下文初始化上下文.请参阅此链接.
You don't need to initialise a context from application context as the activity context has more capabilities. Please refer to this link.
此外,限制静态变量的使用是否是更好的做法?如果我没记错的话,如果我调用一个静态方法,或者从另一个Activity引用一个静态变量,那是否也将另一个Activity保留在内存中?
Also, is it better practice to limit the use of static variables? If I'm not mistaken, if I call a static method, or reference a static variable from a different Activity, won't that keep the other Activity in memory too?
要将数据从一个活动发送到另一个活动,您可能需要事件总线,以分离发送者/接收者的活动
For sending a data from one activity to another activity, you might need parcelable object and bundle, or Event Bus to decouple both sender/receiver activity.
对于静态方法,您可能需要将它们分组在Utility类下.
For static method, you might need to group them under a Utility class.
这篇关于防止Android中的内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!