【发布时间】:2011-02-04 06:16:23
【问题描述】:
我正在编写一个库类来将我的一些逻辑封装在我的第一个 Android 应用程序中。我要封装的功能之一是查询通讯录的功能。因此,它需要一个ContentResolver。我试图弄清楚如何将库函数保持在黑盒状态......也就是说,避免让每个Activity 在其自己的上下文中传递以获取ContentResolver。
问题是我一生都无法弄清楚如何从我的库函数中获取ContentResolver。我找不到包含getContentResolver 的导入。谷歌搜索说使用getContext 获取Context 以调用getContentResolver,但我也找不到包含getContext 的导入。下一篇文章说使用getSystemService 来获取一个调用getContext 的对象。但是 - 我也找不到任何包含 getSystemService 的导入!
所以我一直想知道,我怎样才能在封装的库函数中获得 ContentResolver,还是我几乎坚持让每个调用 Activity 传递对其自身上下文的引用?
我的代码基本上是这样的:
public final class MyLibrary {
private MyLibrary() { }
// take MyGroupItem as a class representing a projection
// containing information from the address book groups
public static ArrayList<MyGroupItem> getGroups() {
// do work here that would access the contacts
// thus requiring the ContentResolver
}
}
getGroups 是我希望避免传入 Context 或 ContentResolver 的方法,因为我希望能将其彻底黑盒化。
【问题讨论】:
标签: android android-context android-contentresolver