我正在编写一个库类来封装我在第一个Android应用程序中的一些逻辑。其中我想要封装的一个函数是查询通讯录的函数。因此,它需要一个
问题是,我无论如何都无法找出如何从我的库函数中获取
所以,我很困惑,我该如何在封装的库函数中获取ContentResolver,还是说我基本上必须让每个调用
我的代码基本上像这样:
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
参数。我希望它干净地封装起来。
Application
的任何其他潜在副作用或“陷阱”会是什么?我是否需要在析构方法中进行任何清理或其他操作? - eidylonextends Application
,并且我已经在应用程序清单文件中添加了完全限定的类名作为android:name
。现在,在我的库类中,我正在尝试调用getApplication()
,但它没有找到它作为一个方法,并且没有给我需要添加的重构提示。我该如何调用getApplication()
来获取应用程序句柄? - eidylon