在 Android 中防止内存泄漏

Preventing memory leaks in Android

通过获取应用程序上下文,在我需要上下文的每个 Activity 中获取对上下文对象的引用是否明智?我了解到它可能会造成内存泄漏以绕过 Activity 的上下文对象,但是当您创建复杂的 Activities 时,似乎几乎总是需要一个上下文对象。我之前在 Activity class 的顶部声明了一个 Context 变量,并在 onCreate 中使用 "this" 关键字对其进行了初始化。我已经知道这可能是一种糟糕的形式,但是在调用 getApplicationContext()onCreate 中初始化 Context 对象是否可以?换句话说,这是否有助于解决我的问题。

此外,限制静态变量的使用是否更好?如果我没记错的话,如果我调用一个静态方法,或者从另一个 Activity 引用一个静态变量,那么不会将另一个 Activity 也保留在内存中吗?

  1. 您的 Activity 中确实不需要 Context 字段,因为您始终可以使用 getBaseContext()getApplicationContext() 获取上下文,或 this(因为 Activity 本身就是上下文)。

  2. 如果你想让自己 Activity class 变瘦,你可能必须将你的 Context 传给其他 class。只要那些 class 的生命周期与您的 Activity 的生命周期相同,这就完全没问题。这意味着,当您的 Activity 被销毁时,任何对象都不应该具有对您传递的上下文的引用。

  3. 只要不引用静态字段,静态方法就非常好。如果它们没有状态,请使用静态方法。出于很多原因,静态场是危险的。因此,仅将它们用于正确的场景。

我觉得你需要了解Application Context和Activity Context的区别,请参考the answer here

But is it ok to initialise the Context object in onCreate calling getApplicationContext()? In other words does this help solve my problem.

为什么需要初始化上下文对象? Activity 本身已经是一个上下文。例如:

    Intent intent = new Intent(this, MainActivity.class);

您不需要从应用程序上下文初始化上下文,因为 activity 上下文具有更多功能。请参考这个link.

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?

为了将数据从一个 activity 发送到另一个 activity,您可能需要 parcelable object and bundle, or Event Bus 来解耦两者 sender/receiver activity.

对于静态方法,您可能需要将它们分组到实用工具下 class。