静态类中的活动上下文
通常,你会希望将一些 Android 类包含在更易于使用的实用程序类中。这些实用程序类通常需要上下文来访问 Android 操作系统或应用程序的资源。一个常见的例子是 SharedPreferences 类的包装器。要访问 Androids 共享首选项,必须写:
context.getSharedPreferences(prefsName, mode);
因此,可能会想要创建以下类:
public class LeakySharedPrefsWrapper
{
    private static Context sContext;
    public static void init(Context context)
    {
        sContext = context;
    }
    public int getInt(String name,int defValue)
    {
        return sContext.getSharedPreferences("a name", Context.MODE_PRIVATE).getInt(name,defValue);
    }
}
现在,如果你用你的活动上下文调用 init(),LeakySharedPrefsWrapper 将保留对你的活动的引用,防止它被垃圾收集。
如何避免:
调用静态帮助函数时,可以使用 context.getApplicationContext(); 发送应用程序上下文
创建静态辅助函数时,可以从给定的上下文中提取应用程序上下文(在应用程序上下文中调用 getApplicationContext() 返回应用程序上下文)。所以对我们的包装器的修复很简单:
public static void init(Context context)
{
    sContext = context.getApplicationContext();
}
如果应用程序上下文不适合你的用例,则可以在每个实用程序函数中包含 Context 参数,应避免保留对这些上下文参数的引用。在这种情况下,解决方案看起来像这样:
public int getInt(Context context,String name,int defValue)
{
    // do not keep a reference of context to avoid potential leaks.
    return context.getSharedPreferences("a name", Context.MODE_PRIVATE).getInt(name,defValue);
}