且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

防止Android中的内存泄漏

更新时间:2022-02-04 23:53:15

我认为您需要了解应用程序上下文和活动上下文之间的区别,请参阅

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.