Is passing Context as a parameter to a method in a Singleton class causes memory leak

喜欢而已 提交于 2021-02-10 14:33:40

问题


I'm declaring a Singleton class where I need to pass context parameter for one of the methods in this class

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....
     }
}

will this cause a memory leak.


回答1:


It could, as you do not know what sort of Context you will be referencing. It would be safer to write:

this.mContext = context.getApplicationContext();

This way, you are certain that mContext is referencing the Application singleton.



来源:https://stackoverflow.com/questions/56102382/is-passing-context-as-a-parameter-to-a-method-in-a-singleton-class-causes-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!