android从通讯录中选择联系人并读取号码

1.Manifest文件中添加权限配置:

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

2.声明打开联系人应用的Intent:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setClassName("com.android.contacts","com.android.contacts.activities.ContactSelectionActivity");
startActivityForResult(intent, 1);

3.onActivityResult方法中获取号码:

protected void onActivityResult(int requestCode,int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String number = getPhoneNumber(data);
Log.d(TAG,number);
}

private String getPhoneNumber(Intent intent){
Cursor cursor = null;
Cursor phone = null;
try{
    String[] projections = {ContactsContract.Contacts._ID,ContactsContract.Contacts.HAS_PHONE_NUMBER};
    cursor = getContentResolver().query(intent.getData(),projections, null, null, null);
    if ((cursor == null) || (!cursor.moveToFirst())){
    return null;
}
int _id = cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID);
String id = cursor.getString(_id);
int has_phone_number = cursor.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER);
int hasPhoneNumber = cursor.getInt(has_phone_number);
String phoneNumber = null;
if(hasPhoneNumber>0){
 phone = getContentResolver().query(
 ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
 null,
 ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "="
 + id, null, null);
 while(phone.moveToNext()){
 int index = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
 String number = phone.getString(index);
  phoneNumber = number;
  }
  }
  return phoneNumber;
  }catch(Exception e){

}finally{
  if (cursor != null) cursor.close();
  if(phone != null) phone.close();
}
return null;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值