How to provide Context to call necessary functions in my own utility class

风格不统一 提交于 2019-12-04 18:29:14

You might also consider extending Application and initializing your singletons in it's onCreate-Method as regular objects. You can then access the Application-Object within Activities using getApplication. Application also provides access to the application context, so you won't have to worry about that within your activities.

That way all of your shared application state is concentrated at a single place, and you don't have to mess around with static initializers.

Now my workaround is to pass an activity reference while initializing the utility class and have that reference to call those functions. I'm wondering what's the correct way to do that.

Absolutely not. You are leaking that activity's memory by holding a static reference to it.

Have the methods on your utility class take a Context as a parameter. Or, use getApplicationContext() to get the singleton application context and supply that to your utility class constructor. The application context object will live as long as the process does.

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