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

Android手機衛士實作:讀取手機聯繫人的完整流程

編輯:關於 Android 程式設計

要讓使用者從手機通訊錄裡挑一支號碼,第一步得先把聯繫人讀出來。Android 的聯繫人資料分散在兩張表中,因此讀取方式跟一般查表不太一樣,需要透過 ContentResolver 做兩段式的查詢。

讀取步驟

  • 用 getContentResolver() 取得 ContentResolver 內容解析器。
  • 以 Uri.parse("content://com.android.contacts/raw_contacts") 組出 Uri,呼叫 query() 查 raw_contacts 表,得到 Cursor。
  • 用 while 迴圈搭配 moveToNext() 逐筆走訪,取出 contact_id。
  • id 不為 null 時,再查 data 表:Uri 為 content://com.android.contacts/data,查詢欄位為 data1 與 mimetype,條件是 raw_contact_id 等於該 id。
  • 比對 mimetype 決定資料型別:vnd.android.cursor.item/name 代表姓名,vnd.android.cursor.item/phone_v2 代表電話。
  • 別忘了在清單檔補上 android.permission.READ_CONTACTS 權限。
  • 最後用 ListView 的 setAdapter() 把資料綁到畫面,這裡以 SimpleAdapter 為例,五個參數依序是:上下文、資料集合、項目版面配置、字串陣列(key)、控制項 int 陣列(id)。

PhoneContactsUtil

 package com.qingguow.mobilesafe.utils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; /** * 讀取手機聯系人 * @author taoshihan * */ public class PhoneContactsUtil { public static List<Map<String,String>> getContacts(Context context){ ContentResolver resolver=context.getContentResolver(); Uri uri=Uri.parse("content://com.android.contacts/raw_contacts"); Uri dataUri=Uri.parse("content://com.android.contacts/data"); List<Map<String,String>> contacts=new ArrayList<Map<String,String>>(); //循環聯系人表 Cursor cursor=resolver.query(uri, new String[]{"contact_id"}, null, null, null); while(cursor.moveToNext()){ String id=cursor.getString(cursor.getColumnIndex("contact_id")); if(id!=null){ Map<String,String> contact=new HashMap<String,String>(); //查找數據表 Cursor dataCursor=resolver.query(dataUri, new String[]{"data1","mimetype"},"raw_contact_id=?", new String[]{id}, null); while(dataCursor.moveToNext()){ String data1=dataCursor.getString(dataCursor.getColumnIndex("data1")); String mimetype=dataCursor.getString(dataCursor.getColumnIndex("mimetype")); System.out.println("data1:"+data1+",mimetype:"+mimetype); if(mimetype.equals("vnd.android.cursor.item/name")){ contact.put("name", data1); }else if(mimetype.equals("vnd.android.cursor.item/phone_v2")){ contact.put("phone", data1); } } contacts.add(contact); dataCursor.close(); } } cursor.close(); return contacts; } }

實作上的幾點提醒

兩層迴圈查詢是這段程式最直觀也最耗資源的地方,資料量一大就會感受到效能壓力。真實專案裡比較好的做法是改以投影搭配一次查詢,或把結果快取起來,避免每次進入頁面都重跑。另外,Cursor 記得關閉,並留意 Android 6.0 以後 READ_CONTACTS 屬於執行期權限,需要動態向使用者請求。

以上就是手機衛士讀取聯繫人的完整思路,掌握兩表關聯與 mimetype 的判斷方式,這個功能就不難了。

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