Android-獲取聯(lián)系人信息,兼容華為手機(jī)

一,清單文件,添加權(quán)限

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

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

<uses-permission android:name="android.permission.GET_ACCOUNTS" /> <!-- 獲取用戶聯(lián)系人數(shù)據(jù) -->

二,動(dòng)態(tài)申請(qǐng)權(quán)限


三,跳轉(zhuǎn)系統(tǒng)聯(lián)系人界面

//權(quán)限申請(qǐng)成功后,打開通訊錄

public void openPhoneBook() {

Intent intent =new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);

? ? startActivityForResult(intent, Constant.REQUEST_CODE_PHONE);

}

四,回調(diào)數(shù)據(jù)



//獲取到電話

private void getPhoneBookName(Intent data) {

if (data !=null) {

Uri uri = data.getData();

? ? ? ? String[] contact =new String[2];

? ? ? ? //得到ContentResolver對(duì)象**

? ? ? ? ContentResolver cr = getContentResolver();

? ? ? ? //取得電話本中開始一項(xiàng)的光標(biāo)**

? ? ? ? Cursor cursor=cr.query(uri,null,null,null,null);

? ? ? ? if(cursor!=null)

{

cursor.moveToFirst();

? ? ? ? ? ? String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));

? ? ? ? ? ? Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,

? ? ? ? ? ? ? ? ? ? ContactsContract.CommonDataKinds.Phone.CONTACT_ID +"=" + ContactId, null, null);

? ? ? ? ? ? if(phone !=null){

phone.moveToFirst();

? ? ? ? ? ? ? ? contact[0] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

? ? ? ? ? ? ? ? String phoneNum = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

? ? ? ? ? ? ? ? //? 把電話號(hào)碼中的? -? 符號(hào) 替換成空格

? ? ? ? ? ? ? ? phoneNum = phoneNum.replaceAll("-", " ");

? ? ? ? ? ? ? ? // 空格去掉? 為什么不直接-替換成"" 因?yàn)闇y(cè)試的時(shí)候發(fā)現(xiàn)還是會(huì)有空格 只能這么處理

? ? ? ? ? ? ? ? phoneNum = phoneNum.replaceAll(" ", "");

? ? ? ? ? ? ? ? contact[1] = phoneNum;

? ? ? ? ? ? }

phone.close();

? ? ? ? ? ? cursor.close();

? ? ? ? }

String contactName = contact[0]; //姓名

? ? ? ? String phoneNum = contact[1];//電話

? ? }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容