【问题标题】:How can i query the contacts content provider outside an activity?如何在活动之外查询联系人内容提供者?
【发布时间】:2010-10-08 21:51:55
【问题描述】:

我正在尝试在 Activity 之外查询联系人内容提供者。但是 managedQuery 是 Activity 的一种方法。我可以使用其他任何类/方法来代替 managedQuery 吗?

这是我的代码:

class MyActivity extends Activity {

  private Cursor getContacts() {
 Uri uri = ContactsContract.Contacts.CONTENT_URI;
 String[] projection = new String[] { ContactsContract.Contacts._ID,
   ContactsContract.Contacts.DISPLAY_NAME,
   ContactsContract.Contacts.HAS_PHONE_NUMBER };
 String where = null;
 String[] whereArgs = null;
 String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
   + " COLLATE LOCALIZED ASC";

 return context.managedQuery(uri, projection, where, whereArgs, sortOrder);
  } 
}

【问题讨论】:

    标签: android android-contentprovider


    【解决方案1】:

    请改用ContentResolver.query()

    (调用Context.getContentResolver() 以获取ContentResolver 的实例。无论如何您都需要一个Context,但它不一定是Acitivity)

    Activity.managedQuery() 负责处理与游标相关的 Activity 生命周期。 ContentResolver.query() 不会这样做,因此您必须确保自己关闭并重新查询游标等。

    【讨论】:

    • 这意味着我的类仍然需要从 Context 继承,对吧?
    • 不,但是您需要从某个地方获取有效的上下文(也可以是服务)。您希望在什么使用场景中运行查询?
    • 如何从“任何地方”获取有效上下文?例如来自 Utils 类中定义的静态函数
    • 在静态上下文中,您需要为方法添加上下文参数,或者以静态方式访问应用程序的上下文。从 android.app.Application 中派生出自己的 Application 类,并在 Application Manifest 中注册它,这样在加载应用程序时就会被框架实例化。然后,在您的 Application 类的构造函数中,您可以设置一个引用该实例的静态成员,以便您可以从静态 Utils 方法访问它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多