1.在AndroidManifest中加入讀寫權(quán)限
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
2.Android系統(tǒng)管理聯(lián)系人的URI
獲取聯(lián)系人的ID和NAME:ContactsContract.Contacts.CONTENT_URI
獲取聯(lián)系人的電話號碼:ContactsContract.CommonDataKinds.Phone.CONTENT_URI
獲取聯(lián)系人的郵箱地址:ContactsContract.CommonDataKinds.Email.CONTENT_URI
(注:Contacts有兩個表佳谦,分別是rawContact和Data,rawContact記錄了用戶的id和name,其中id欄名稱為:ContactsContract.Contacts._ID, name名稱欄為ContactContract.Contracts.DISPLAY_NAME,電話信息表的外鍵id為ContactsContract.CommonDataKinds.Phone.CONTACT_ID,電話號碼欄名稱為:ContactsContract.CommonDataKinds.Phone.NUMBER.
3.調(diào)用系統(tǒng)聯(lián)系人獲取電話號碼
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(intent, 0);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 0) {
String phoneNumber = "";
if(data != null) {
Uri uri = data.getData();
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (null != cursor && cursor.moveToFirst()){
phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//得到純數(shù)字電話號碼
if (phoneNumber.startsWith("+86")) {
phoneNumber = phoneNumber.replace("+86", "");
}
phoneNumber = phoneNumber.replace(" ", "");
phoneNumber = phoneNumber.replace("-", "");
editText.setText(phoneNumber);
cursor.close();
}
}
}
}