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

谁说我不能喝 提交于 2019-12-22 00:09:24

问题


Sometimes I need to provide a Context object to call specific functions, such as

Intent intent = new Intent(context, MyClass.class);

in order to start a service

context.startService(intent);

Or, provide a Context object to do a query

Cursor cursor = context.managedQuery(uri, projection, null, null, null);

If this is done in a UI class which extends Activity, that's fine. However, If I want to create my own utility class (a singleton) that doesn't extend anything and call these functions, I don't have necessary Context object. 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. It should not be reasonable to have every class to extends Context so that it can call those functions.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4158785/how-to-provide-context-to-call-necessary-functions-in-my-own-utility-class

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