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

Android 讀取與管理通訊錄:ContactsContract 查詢、檢視與刪除

編輯:關於 Android 程式設計

Android 4.0 之後,存取聯絡人一律透過 ContactsContract 這組 ContentProvider 常數,搭配 ContentResolver 就能完成查詢、檢視與刪除。下面用一個實作把整個流程走過一遍:清單顯示所有聯絡人,長按可檢視電話號碼或刪除該筆資料。

主畫面版面

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/text"
        android:textSize="30px"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="手機聯絡人列表"/>

    <ListView
        android:id="@+id/contactslist"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

單列版面(供 SimpleAdapter 使用)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/_id"
        android:textSize="30px"
        android:layout_width="240px"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/name"
        android:textSize="30px"
        android:layout_width="240px"
        android:layout_height="wrap_content"/>

</LinearLayout>

Activity 程式碼

package com.example.contactproject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends Activity {

    private ListView contactslist = null;
    private SimpleAdapter simpleadapter = null;
    private Cursor result = null;
    private List<Map<String, Object>> allContacts = new ArrayList<Map<String, Object>>();

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

        this.contactslist = (ListView) super.findViewById(R.id.contactslist);

        // 查詢所有聯絡人
        this.result = super.getContentResolver().query(
                ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        super.startManagingCursor(result);

        while (result.moveToNext()) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("_id", result.getInt(result.getColumnIndex(ContactsContract.Contacts._ID)));
            map.put("name", result.getString(
                    result.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
            this.allContacts.add(map);
        }

        this.simpleadapter = new SimpleAdapter(this, this.allContacts, R.layout.contacts,
                new String[] { "_id", "name" },
                new int[] { R.id._id, R.id.name });
        this.contactslist.setAdapter(this.simpleadapter);

        // 註冊長按選單
        this.registerForContextMenu(this.contactslist);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("聯絡人操作");
        menu.add(Menu.NONE, Menu.FIRST + 1, 1, "查看詳情");
        menu.add(Menu.NONE, Menu.FIRST + 2, 2, "刪除聯絡人");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info =
                (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        int position = info.position;
        String contactsId = this.allContacts.get(position).get("_id").toString();

        switch (item.getItemId()) {
            case Menu.FIRST + 1: // 查詢號碼
                String phoneSelection = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?";
                String[] phoneSelectionArgs = new String[] { contactsId };

                Cursor phoneCursor = super.getContentResolver().query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null, phoneSelection, phoneSelectionArgs, null);

                StringBuffer buf = new StringBuffer("電話號碼是:");
                while (phoneCursor.moveToNext()) {
                    buf.append(phoneCursor.getString(phoneCursor.getColumnIndex(
                            ContactsContract.CommonDataKinds.Phone.NUMBER))).append(" ");
                }
                phoneCursor.close();
                Toast.makeText(this, buf.toString(), Toast.LENGTH_LONG).show();
                break;

            case Menu.FIRST + 2: // 刪除聯絡人
                super.getContentResolver().delete(
                        Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, contactsId),
                        null, null);
                this.allContacts.remove(position);
                this.simpleadapter.notifyDataSetChanged();
                Toast.makeText(this, "資料已經刪除", Toast.LENGTH_LONG).show();
                break;
        }
        return super.onContextItemSelected(item);
    }
}

權限設定

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

幾個實作重點與注意事項

為什麼要 second query 一次才拿得到號碼?這是 ContactsContract 的設計:Contacts.CONTENT_URI 回傳的是「聯絡人」層級的聚合資料,而電話號碼屬於「資料」層級,存放在 CommonDataKinds.Phone 底下,兩者以 CONTACT_ID 關聯。同理,Email 要查 CommonDataKinds.Email,地址要查 StructuredPostal。

查詢時用 ? 佔位符。範例中的 phoneSelection = "... CONTACT_ID =?" 搭配 selectionArgs,比字串拼接安全,也能避免資料中的單引號造成語法錯誤。

位置與 ID 不要混用。程式碼中同時出現了 position(清單索引)與 contactsId(真正的聯絡人 ID),刪除時用的是後者,這點很關鍵。若清單資料在刪除後未同步更新,用 position 去對應就會出錯,所以 notifyDataSetChanged() 不可省略。

startManagingCursor 已不建議使用。這個方法在 API 11 之後被標記為過時,它會讓 Activity 全權管理 Cursor 的生命週期。現行的做法是用 try-with-resources 風格或明確在 onDestroy 關閉,若使用 Loader(CursorLoader)架構則由 Loader 負責管理,並能自動在資料變更時刷新清單。

Runtime 權限。READ_CONTACTS 與 WRITE_CONTACTS 都屬於危險權限,Android 6.0 以後必須在執行期動態請求,而且讀取與寫入的授權對話框是分開的。此外,「刪除聯絡人」是不可逆的破壞性操作,實務上建議加上確認對話框,並優先考慮用「建立刪除要求」的方式交由系統聯絡人 App 處理,讓使用者保有最終決定權。

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