如何提供上下文来调用所需的功能在我自己的工具类 [英] How to provide Context to call necessary functions in my own utility class

查看:117
本文介绍了如何提供上下文来调用所需的功能在我自己的工具类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时候,我需要提供上下文对象调用特定功能,如

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

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

为了启动一个服务

context.startService(intent);

或者,提供一个Context对象做一个查询

Or, provide a Context object to do a query

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

如果这是在延伸活动的UI类来完成,这很好。 但是,如果我想创建自己的工具类(单身)不扩展任何东西,并调用这些功能,我没有必要的上下文对象。现在我的解决方法是通过一个活动的参考,同时初始化工具类和有参考调用这些函数。我不知道什么是做到这一点的正确方法。它不应该是合理的,有充分的类扩展了现场,从而使其可以调用这些功能。

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.

推荐答案

您也可以考虑延长应用程序和初始化你单身,在它的的onCreate - 方法$ C $为常规对象。然后,您可以通过访问应用程序 -object内的活动 getApplication 应用程序还提供了访问应用程序环境,所以你不必担心你的活动中。

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.

这篇关于如何提供上下文来调用所需的功能在我自己的工具类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆