如何在Android中调用getContentResolver?

How can I call getContentResolver in android?

我正在编写一个库类以在我的第一个Android应用程序中封装一些逻辑。我要封装的功能之一是查询通讯录的功能。因此,它需要一个ContentResolver。我试图弄清楚如何使库函数保持黑框……也就是说,避免让每个Activity在其自己的上下文中传递以获得ContentResolver

问题是我一生无法解决如何从库函数中获取ContentResolver的问题。我找不到包含getContentResolver的导入。谷歌搜索表示使用getContext获取要在其上调用getContentResolverContext,但是我也找不到包含getContext的导入。接下来的帖子说使用getSystemService获取对象来调用getContext。但是-我也找不到任何包含getSystemService的导入!

因此,我很想知道,如何在封装的库函数中获取ContentResolver,还是让每个调用Activity传递引用到其自身上下文中而使我陷入困境?

我的代码基本上是这样的:

1
2
3
4
5
6
7
8
9
10
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是我希望避免必须通过ContextContentResolver传递的方法,因为我希望将其干净地黑盒包装。


您可以这样使用:

1
2
getApplicationContext().getContentResolver() with the proper context.
getActivity().getContentResolver() with the proper context.

使每个库函数调用都通过ContentResolver ...传递或扩展Application以保留上下文并静态访问它。


对于将来可能会发现此线程的任何人,这是我最后的想法:

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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,我的函数代码应为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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;
}


有点困难,没有看到更多有关如何编写库的代码,但是我看不到使用上下文的另一种选择,因此在调用该类时传递了它。

"随机"类没有获取contentresolver的环境:您需要上下文。

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

On Android, a Context is used for many operations but mostly to load and
access resources. This is why all the
widgets receive a Context parameter in
their constructor. In a regular
Android application, you usually have
two kinds of Context, Activity and
Application. It's usually the first
one that the developer passes to
classes and methods that need a
Context

(强调我的)