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

Android 讀取與搜尋聯絡人的實作方式

編輯:關於 Android 程式設計

Android 讀取與搜尋聯絡人的實作方式

在 Android 中讀取聯絡人資料,主要會使用 ContactsContract 提供的內容提供者介面。透過 ContentResolver,開發者可以查詢聯絡人清單,也能依名稱或號碼進行搜尋。

讀取聯絡人

常見做法是查詢 ContactsContract.Contacts.CONTENT_URI,並指定需要的欄位,例如聯絡人 ID 與顯示名稱。

String[] projections = new String[] {
    ContactsContract.Contacts._ID,
    ContactsContract.Contacts.DISPLAY_NAME
};
Cursor cursor = context.getContentResolver()
    .query(ContactsContract.Contacts.CONTENT_URI, projections, null, null, null);
while (cursor.moveToNext()) {
    String id = cursor.getString(0);
    String name = cursor.getString(1);
}
cursor.close();

依名稱搜尋聯絡人

若要以名稱搜尋,可利用 CONTENT_FILTER_URI 搭配搜尋字串。

Uri uri = Uri.withAppendedPath(
    ContactsContract.Contacts.CONTENT_FILTER_URI,
    "Wang"
);
Cursor cursor = context.getContentResolver()
    .query(uri, new String[] { ContactsContract.Contacts._ID }, null, null, null);

取得聯絡人 ID 後,再查詢 ContactsContract.Data.CONTENT_URI,即可取得姓名與電話等詳細資料。

實作提醒

  • 需要在應用程式中宣告讀取聯絡人的權限。
  • 查詢結果使用 Cursor 時,記得妥善關閉。
  • 若裝置版本較新,仍需注意執行期權限請求流程。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved