Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 通訊錄管理(一):如何正確取得聯絡人資料

編輯:關於 Android 程式設計

Android 的通訊錄與簡訊是透過 ContentProvider 對開發者開放介面的,因此一切都得從 ContentResolver 下手。

這塊最容易翻車的地方在於表的 URI 特別容易混淆——raw_contacts、data、mimetype 幾張表彼此關聯,少寫一層就會拿到空結果。接下來幾篇,我會依序整理聯絡人取得、通話記錄取得、簡訊取得、簡訊詳情與簡訊發送。

一、先看聯絡人相關的表結構

對開發者而言,主要關注三張表:

  • raw_contacts:每一筆「原始聯絡人」,存放 _id。
  • data:實際的資料內容,用 mimetype 欄位區分是姓名、電話還是其他。
  • 以及關聯這兩者的結構設計。

關鍵觀念:姓名和電話不是同一列的兩個欄位,而是 data 表中兩筆不同的記錄,靠 mimetype 區分。這也是為什麼取值時必須跑巢狀迴圈。

二、資料模型

package cn.zxw.contact.domain;

/**
 * 聯絡人
 */
public class ContactsInfo {

    public int _id;
    public String name;
    public String phone;
    public String email;

    public ContactsInfo() {
        super();
    }

    public ContactsInfo(int _id, String name, String phone, String email) {
        super();
        this._id = _id;
        this.name = name;
        this.phone = phone;
        this.email = email;
    }

    @Override
    public String toString() {
        return "ContactsInfo [_id=" + _id + ", name=" + name
                + ", phone=" + phone + ", email=" + email + "]";
    }
}

三、取得聯絡人

/**
 * 取得聯絡人清單
 */
public static List<ContactsInfo> getContactsInfos(Context context) {

    ContentResolver resolver = context.getContentResolver();
    List<ContactsInfo> infos = new ArrayList<ContactsInfo>();

    // 先取得所有 raw_contacts 的 _id
    // 對應的 authority 是 ContactsContract.AUTHORITY(com.android.contacts)
    // 讀取此內容提供者需要 READ_CONTACTS 權限
    Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
    Cursor cursor1 = resolver.query(uri, new String[] {"_id"}, null, null, null);

    while (cursor1.moveToNext()) {
        int _id = cursor1.getInt(0);
        ContactsInfo info = new ContactsInfo();
        info._id = _id;

        // 再針對每個 _id 去 data 表撈實際內容
        uri = Uri.parse("content://com.android.contacts/raw_contacts/"
                + _id + "/data");
        Cursor cursor2 = resolver.query(uri,
                new String[] {"data1", "mimetype"}, null, null, null);

        while (cursor2.moveToNext()) {
            String data1 = cursor2.getString(0);
            String mimetype = cursor2.getString(1);

            if ("vnd.android.cursor.item/phone_v2".equals(mimetype)) {
                info.phone = data1;    // 號碼
            } else if ("vnd.android.cursor.item/name".equals(mimetype)) {
                info.name = data1;     // 姓名
            }
        }
        cursor2.close();
        infos.add(info);
    }
    cursor1.close();

    return infos;
}

幾個實務提醒:

  • 請改用 ContactsContract.CommonDataKinds.Phone 與 StructuredName 的常數,而不是硬寫 mimetype 字串。Google 已經幫你把這些常數定義好了,自己打字串容易出錯。
  • 上面是 N+1 查詢,每個聯絡人都要多跑一次 query,聯絡人上千筆時會明顯卡頓。實務上建議一次撈 data 表再用 mimetype 分組,或直接用 ContactsContract.Contacts 的 has_phone_number 搭配一次查詢完成。
  • Cursor 一定要關,建議改用 try-with-resources 或 useCursor 相關輔助,避免 Cursor 洩漏導致 CursorWindowAllocationException。

四、順帶取得通話記錄

/**
 * 取得所有通話記錄
 */
public List<CallLogInfo> getCallLog(Context context) {
    List<CallLogInfo> infos = new ArrayList<CallLogInfo>();
    ContentResolver cr = context.getContentResolver();

    Uri uri = CallLog.Calls.CONTENT_URI;
    String[] projection = new String[] {
            CallLog.Calls.NUMBER,
            CallLog.Calls.DATE,
            CallLog.Calls.TYPE
    };

    Cursor cursor = cr.query(uri, projection, null, null, null);
    while (cursor.moveToNext()) {
        String number = cursor.getString(0);
        long date = cursor.getLong(1);
        int type = cursor.getInt(2);
        infos.add(new CallLogInfo(number, date, type));
    }
    cursor.close();

    return infos;
}

五、顯示在 ListView 上

package cn.zxw.contact;

import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import cn.zxw.contact.domain.ContactsInfo;
import cn.zxw.contact.utils.ContactsMsgUtils;

public class ContactsActivity extends Activity {

    private ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts_msg_calllog);

        lv = (ListView) findViewById(R.id.lv);

        List<ContactsInfo> infos =
                ContactsMsgUtils.getContactsInfos(getApplicationContext());
        lv.setAdapter(new MyAdapter(infos));
    }

    private class MyAdapter extends BaseAdapter {

        private final List<ContactsInfo> infos;

        MyAdapter(List<ContactsInfo> infos) {
            this.infos = infos;
        }

        @Override
        public int getCount() {
            return infos.size();
        }

        @Override
        public Object getItem(int position) {
            return infos.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(getApplicationContext(),
                    R.layout.contacts_list_item, null);

            TextView tv_number = (TextView) view.findViewById(R.id.tv_number);
            TextView tv_name = (TextView) view.findViewById(R.id.tv_name);

            ContactsInfo info = infos.get(position);
            tv_number.setText(info.phone);
            tv_name.setText(info.name);

            return view;
        }
    }
}

這段 Adapter 是教學用的寫法,每次 getView 都重新 inflate。正式專案請務必加上 ViewHolder 與 convertView 重用,否則聯絡人一多就會明顯掉幀。

六、權限别忘了

<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />

從 Android 6.0(API 23)開始,這兩個都是危險權限,必須在執行期以 requestPermissions() 動態向使用者請求,並處理好「使用者拒絕」與「使用者勾選不再詢問」兩種情況。只在 Manifest 宣告是不夠的。

另外從 Android 10 開始,READ_CALL_LOG 屬於受限制權限,上架 Google Play 需要提交用途說明並通過審核;部分中國大陸的應用商店也有各自的規範。設計功能前先確認政策,能省下不少後續麻煩。

下一篇我們來談通話記錄的取得與呈現。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved