【问题标题】:Is there any other way of accessing to contacts without using `getContentResolver()`?有没有其他方法可以在不使用`getContentResolver()`的情况下访问联系人?
【发布时间】:2018-11-25 07:32:16
【问题描述】:

我的应用程序总是很慢,有时会崩溃,因为要访问联系人列表,我正在使用 getContentResolver() 这使我的应用程序运行另一个附加进程到主进程。每当该附加进程运行时,我的应用程序就会开始变慢并崩溃。

那么,有没有什么想法可以访问联系人列表而不传递给getContentResolver()

【问题讨论】:

标签: android android-contentprovider android-contacts android-contentresolver


【解决方案1】:

使用AsyncTaskLoader 从设备中获取联系人,推荐使用,因为它是异步的,也适用于活动生命周期。

【讨论】:

  • @Vall0n 我在后台服务中调用getContentResolver()
  • @Hitami AsyncTask 在后台服务中不起作用
  • @De_Scholar 如果你使用 IntentService 那么它已经在不同的线程中运行了,不用担心,否则如果是 Service 那么你需要使用 AsyncTask 或 Thread。
【解决方案2】:

您应该使用AsynTask 在后台线程中完成这项工作

private class LoadContacts extends AsyncTask<Void, Boolean, Boolean> {  
    protected void onPreExecute() {
        Log.e("LS", "Start !");
    }

    @Override
    protected Boolean doInBackground(Void... params) {
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        try {
            if (cur.getCount() > 0) {
                while (cur.moveToNext()) {
                    String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                    String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                    if (cur.getInt(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                        Cursor pCur = cr.query(
                                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                null,
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                                new String[]{id},
                                null
                        );
                        while (pCur.moveToNext()) {
                            String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                            String data = "Name : " + name + " - Phone : " + phoneNo;
                        }
                        pCur.close();
                    }
                }
            }
            cur.close();
        } catch (NullPointerException | java.io.IOException e) {
            Log.e("LS", e.getMessage());
        }
        return true;
    }

    protected void onPostExecute(Boolean result) {
        Log.e("LS", "Done !");
    }
}

【讨论】:

  • 这个级别的嵌套不好。您应该检查反转 if 语句/提前返回并委托给方法
猜你喜欢
  • 2018-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多