【问题标题】:Is passing Context as a parameter to a method in a Singleton class causes memory leak将 Context 作为参数传递给 Singleton 类中的方法会导致内存泄漏
【发布时间】:2019-05-12 18:44:31
【问题描述】:

我正在声明一个单例类,我需要为此类中的一种方法传递上下文参数

public class MySingleton() {
    Private Context mContext;
    Private static MySingleton mInstance;

    public static MySingleton mInstance() {
        if (mInstance == null) {
            mInstance = new MySingleton();
        }
        return mInstance;
    }

    public void myMethod(Context context)
    {   
       this.mContext = context;
       // write your code here....
     }
}

这会导致内存泄漏吗?

【问题讨论】:

    标签: java android singleton


    【解决方案1】:

    它可以,因为您不知道您将引用哪种Context。写起来会更安全:

    this.mContext = context.getApplicationContext();
    

    这样,您可以确定 mContext 正在引用 Application 单例。

    【讨论】:

    • 如果我删除了 mContext 并将 context 作为局部变量保留了怎么办?
    • @HmH:这可能是安全的,尽管它取决于你对那个变量做了什么。
    • 这个方法被调用来创建一个AlarmManager,上下文用于发起一个intent和PendingIntent。但是该方法在 3 个不同的地方被调用了 3 次。
    • @HmH:你所描述的应该是安全的,特别是如果你没有在你的单例字段中持有任何这些东西。您始终可以使用 Leak Canary 之类的工具来尝试查看您是否正在泄漏上下文。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    • 2020-03-27
    • 1970-01-01
    • 2018-02-14
    • 2019-06-11
    • 1970-01-01
    相关资源
    最近更新 更多