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

讀取系統通訊錄並回顯:Android ContentResolver 實戰

編輯:關於 Android 程式設計

前面已經把相關布局做好了,本文接着把功能補完:讀取系統通訊錄、列表展示、點選回顯。

讀取系統通訊錄的思路

點擊「選擇通訊錄」按鈕後彈出列表,整個過程分幾步理解。

1. 內容解析器:系統通訊錄對外提供了一個 ContentProvider,我們通過 ContentResolver 去查詢。

2. URL 地址:查 API 文檔的清單文件,再對照 ContentProvider 源碼(通訊錄數據庫由多張表組成),統一格式為 content://com.android.contacts/表名。

3. 核心表結構:

raw_contacts 通訊錄表,contact_id 是聯繫人唯一 ID。
data 用戶信息表,用 raw_contact_id 作為外鍵與 raw_contacts 關聯;其中 data1 字段同時存放電話號碼和聯繫人名稱,mimetype_id 用來標識當前行 data1 的數據類型。
mimetypes 類型表,與 data 表的 mimetype_id 做關聯查詢,取出具體類型:
電話號碼為 vnd.android.cursor.item/phone_v2,用戶名稱為 vnd.android.cursor.item/name。

4. 訪問方式:content://com.android.contacts/raw_contacts 與 content://com.android.contacts/data。

代碼實現

讀通訊錄屬於耗時操作,所以放在子執行緒中查詢,查完通過 Handler 通知主線程刷新列表。

 private ListView lv_contact;
private List<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
private MyAdapter mAdapter;

private Handler mHandler = new Handler() {
 @Override public void handleMessage(Message msg) {
  // 8. 填充數據適配器
  mAdapter = new MyAdapter();
  lv_contact.setAdapter(mAdapter);
 }
};

@Override protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_contact_list);
 initUI();
 initData();
}

class MyAdapter extends BaseAdapter {
 @Override public int getCount() { return contactList.size(); }

 @Override public HashMap<String, String> getItem(int i) { return contactList.get(i); }

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

 @Override public View getView(int i, View view, ViewGroup viewGroup) {
  View v = View.inflate(getApplicationContext(), R.layout.listview_contact_item, null);
  TextView tv_name = (TextView) v.findViewById(R.id.tv_name);
  TextView tv_phone = (TextView) v.findViewById(R.id.tv_phone);
  tv_name.setText(getItem(i).get("name"));
  tv_phone.setText(getItem(i).get("phone"));
  return v;
 }
}

/** 獲取通訊錄數據 */
private void initData() {
 // 讀取系統通訊錄可能是一個耗時操作,放到子線程中處理
 new Thread(){
  public void run(){
   // 1. 獲取內容解析器對象
   ContentResolver contentResolver = getContentResolver();

   // 2. 查詢通訊錄表(需要讀取通訊錄權限)
   Cursor cursor = contentResolver.query(
     Uri.parse("content://com.android.contacts/raw_contacts"),
     new String[]{"contact_id"}, null, null, null);
   contactList.clear();

   // 3. 循環游標,直到沒有數據為止
   while (cursor.moveToNext()){
    String id = cursor.getString(0);

    // 4. 根據唯一 id 查詢 data 表,獲取 data1 與 mimetype 字段
    Cursor indexCursor = contentResolver.query(
      Uri.parse("content://com.android.contacts/data"),
      new String[]{"data1", "mimetype"},
      "raw_contact_id = ?", new String[]{id}, null);

    // 5. 逐行判斷類型並填充
    HashMap<String, String> hashMap = new HashMap<String, String>();
    while (indexCursor.moveToNext()){
     String data = indexCursor.getString(0);
     String type = indexCursor.getString(1);
     // 6. 區分類型去給 hashMap 填充數據
     if (type.equals("vnd.android.cursor.item/phone_v2")) {
      if (!TextUtils.isEmpty(data)) hashMap.put("phone", data);
     } else if (type.equals("vnd.android.cursor.item/name")) {
      if (!TextUtils.isEmpty(data)) hashMap.put("name", data);
     }
    }
    indexCursor.close();
    contactList.add(hashMap);
   }
   cursor.close();

   // 7. 通過消息機制通知主線程使用已填充好的數據集合
   mHandler.sendEmptyMessage(0);
  }
 }.start();
}

效果:

點擊回顯

點擊某個聯繫人條目,把號碼帶回上一頁並自動填入輸入框:

 private void initUI() {
  lv_contact = (ListView) findViewById(R.id.lv_contact);
  lv_contact.setOnItemClickListener(new AdapterView.OnItemClickListener() {
   @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    // 1. 獲取點中條目對應的集合對象
    if (mAdapter != null) {
     HashMap<String, String> hashMap = mAdapter.getItem(i);
     // 2. 取出電話號碼
     String phone = hashMap.get("phone");
     // 3. 此號碼需要給上一個界面使用
     // 4. 通過 setResult 把數據返回
     Intent intent = new Intent();
     intent.putExtra("phone", phone);
     setResult(0, intent);
     finish();
    }
   }
  });
 }

上一頁在 onActivityResult 中接收:

 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (data != null) {
   String phone = data.getStringExtra("phone");
   // 過濾特殊字符:中劃線與空格
   phone = phone.replace("-", "").replace(" ", "").trim();
   et_phone_number.setText(phone);
   // 存儲至 sp,避免返回時丟失
   SpUtil.putString(getApplicationContext(), ConstantValue.CONTACT_PHONE, phone);
  }
  super.onActivityResult(requestCode, resultCode, data);
 }

用 sp 做狀態持久化

填完號碼進入下一頁再返回,會發現輸入框空了。解法是進入時主動從 sp 回顯:

 private void initUI() {
  et_phone_number = (EditText) findViewById(R.id.et_phone_number);
  // 回顯已保存的號碼
  String contact_phone = SpUtil.getString(this, ConstantValue.CONTACT_PHONE, "");
  et_phone_number.setText(contact_phone);

  bt_select_number = (Button) findViewById(R.id.bt_select_number);
  bt_select_number.setOnClickListener(new View.OnClickListener() {
   @Override public void onClick(View view) {
    Intent intent = new Intent(getApplicationContext(), ContactListActivity.class);
    startActivityForResult(intent, 0);
   }
  });
 }

實戰中還要注意兩點:一是讀通訊錄需要在 AndroidManifest.xml 中聲明 READ_CONTACTS 權限,Android 6.0 以上還要動態申請;二是 Cursor 必須關閉,否則容易觸發 Cursor 洩水生氣的告警,用 try-with-resources 或 Android 4.0 以後的 Cursor 接口都能更省心。

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