13

我正在编写一个库类来将我的一些逻辑封装在我的第一个 Android 应用程序中。我要封装的功能之一是查询通讯录的功能。因此,它需要一个ContentResolver. 我试图弄清楚如何将库函数保持为黑盒状态......也就是说,避免每次Activity通过在自己的上下文中获取ContentResolver.

问题是我一生都无法弄清楚如何ContentResolver从我的库函数中获取一个。我找不到包含getContentResolver. 谷歌搜索说用来getContext获取Contexton which to call 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 是我希望避免传入 aContextContentResolver如果可以的话的方法,因为我希望将它完全黑盒化。

4

4 回答 4

10

你可以这样使用:

getApplicationContext().getContentResolver() with the proper context.
getActivity().getContentResolver() with the proper context.
于 2013-10-11T07:37:40.557 回答
8

让每个库函数调用传入ContentResolver... 或扩展Application以保持上下文并静态访问它。

于 2011-02-04T19:33:53.623 回答
5

对于将来可能会找到此线程的任何人,这是我最终这样做的方式:

我使用sugarynugs 的方法创建一个类extends Application,然后在应用程序清单文件中添加适当的注册。我的应用程序类的代码是:

import android.app.Application;
import android.content.ContentResolver;
import android.content.Context;

public class CoreLib extends Application {
    private static CoreLib me;

    public CoreLib() {
        me = this;
    }

    public static Context Context() {
        return me;
    }

    public static ContentResolver ContentResolver() {
        return me.getContentResolver();
    }
}

然后,要在我的库类中获取 ContentResolver,我的函数代码是这样的:

public static ArrayList<Group> getGroups(){
    ArrayList<Group> rv = new ArrayList<Group>();

    ContentResolver cr = CoreLib.ContentResolver();
    Cursor c = cr.query(
        Groups.CONTENT_SUMMARY_URI, 
        myProjection, 
        null, 
        null, 
        Groups.TITLE + " ASC"
    );

    while(c.moveToNext()) {
        rv.add(new Group(
            c.getInt(0), 
            c.getString(1), 
            c.getInt(2), 
            c.getInt(3), 
            c.getInt(4))
        );          
    }

    return rv;
}
于 2011-02-06T03:06:30.657 回答
2

如果没有看到更多关于如何编写库的信息,有点困难,但是我没有看到另一个选项来使用上下文,因此在调用该类时传递它。

“随机”类没有获取内容解析器的环境:您需要一个上下文。

现在将您的(活动)上下文实际传递给您的班级并不太奇怪。来自http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html

在 Android 上,上下文用于许多操作,但主要用于加载和访问资源。这就是所有小部件在其构造函数中接收 Context 参数的原因。在一个普通的Android应用中,你通常有两种Context,Activity和Application。它通常是开发人员传递给需要 Context 的类和方法的第一个

(强调我的)

于 2011-02-04T19:34:44.550 回答