Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Android 實作:叫出系統聯絡人挑選器並取回號碼

Android 裡其實沒有什麼高深的技術,把官方文件讀通就能動手。下面這個例子改寫自文件中的範例,稍作補充。

發出挑選請求

用 Intent.ACTION_PICK 搭配 content://contacts,並把型別設為 Phone.CONTENT_TYPE,可以讓系統只列出「有電話號碼」的聯絡人,省去後續過濾:

Intent pickContactIntent = new Intent(Intent.ACTION_PICK,
        Uri.parse("content://contacts"));
pickContactIntent.setType(Phone.CONTENT_TYPE); // 只顯示有號碼的聯絡人
startActivityForResult(pickContactIntent, 11);

接收回傳結果

在 onActivityResult() 中比對 requestCode,取出 contactUri 後,用 ContentResolver 查一次,只取需要的欄位:

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (requestCode == 11 && resultCode == RESULT_OK)
    {
        Uri contactUri = data.getData();

        // 只需要名稱與號碼兩個欄位
        String[] projection = {
                ContactsContract.PhoneLookup.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER
        };

        // 注意:query() 應在子線程執行,避免阻塞 UI 執行緒,
        // 這裡為了範例簡潔而直接呼叫,實務上建議改用 CursorLoader
        Cursor cursor = getContentResolver()
                .query(contactUri, projection, null, null, null);
        cursor.moveToFirst();

        int indexPhoneNumber = cursor.getColumnIndex(Phone.NUMBER);
        int indexDisplayName = cursor.getColumnIndex(
                ContactsContract.PhoneLookup.DISPLAY_NAME);
        String phoneNumber = cursor.getString(indexPhoneNumber);
        String displayName = cursor.getString(indexDisplayName);

        if (phoneNumber != null && displayName != null)
        {
            if (phoneNumber.startsWith("+86"))
                phoneNumber = phoneNumber.substring(3);

            EditText textNumber = (EditText) findViewById(R.id.text_number);
            textNumber.setText("\"" + displayName + "\"" + phoneNumber);
        }
    }
}

兩個實務提醒:查詢屬於 potentially 耗時的 I/O,正式專案請放到子線程或用 CursorLoader;另外記得在清單中宣告 READ_CONTACTS 權限,並處理 Android 6.0 以後的執行期權限請求,否則會拿到空結果。

Copyright © Linux教程網 All Rights Reserved