How to provide Context to call necessary functions

2019-04-13 02:10发布

问题:

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.