如何在android中调用getContentResolver?

eid*_*lon 12 android android-contentresolver android-context

我正在编写一个库类来封装我的第一个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
    }
}
Run Code Online (Sandbox Code Playgroud)

getGroups是我希望避免传递的方法,Context或者ContentResolver如果可以的话,因为我希望将它干净地装入黑盒子.

cod*_*cat 9

你可以像这样使用:

getApplicationContext().getContentResolver() with the proper context.
getActivity().getContentResolver() with the proper context.
Run Code Online (Sandbox Code Playgroud)


tec*_*ces 7

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


eid*_*lon 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,为了在我的库类中获取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;
}
Run Code Online (Sandbox Code Playgroud)