如何在安卓系统中调用getContentResolver函数?

14
我正在编写一个库类来封装我在第一个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方法,但是不想传递ContextContentResolver参数。我希望它干净地封装起来。

4个回答

11

你可以这样使用:

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

8
每个库函数调用都需要传入一个ContentResolver... 或者扩展Application以持有一个上下文并静态访问它。

扩展Application的任何其他潜在副作用或“陷阱”会是什么?我是否需要在析构方法中进行任何清理或其他操作? - eidylon
好的,所以我正在尝试这个方法。我有一个类,它extends Application,并且我已经在应用程序清单文件中添加了完全限定的类名作为android:name。现在,在我的库类中,我正在尝试调用getApplication(),但它没有找到它作为一个方法,并且没有给我需要添加的重构提示。我该如何调用getApplication()来获取应用程序句柄? - eidylon

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;
}

1
你如何管理它的权限?如果你想限制一些使用你的库的应用程序的数据暴露,我们该如何实现? - Manohar

2

没有看到你编写库的更多内容,这有点困难,但我认为另一个选择就是使用上下文,并在调用该类时传递它。

“随机”类没有获取contentresolver的环境:您需要一个上下文。

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

在Android上,Context用于许多操作,但主要用于加载和访问资源。这就是为什么所有小部件在构造函数中都接收一个Context参数。在常规的Android应用程序中,通常有两种类型的Context,Activity和Application。通常是开发人员将其传递给需要Context的类和方法的第一个

(强调我的)


我更新了一个小代码片段,展示了我试图做的事情。 - eidylon
我认为传递上下文以便您可以使用它来获取内容解析器是您的解决方案 :) - Nanne

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接