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;
}