一、设置权限清单
<uses-permission android:name="android.permission.READ_CONTACTS" />
二、在按钮单击中,打开通讯录
btnPhone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI), 100);
}
});
三、在回调事件中,监听并获取
//接受消息
@Override
protected void onActivityResult(int requestCode,int resultCode,Intent data) {
super.onActivityResult(requestCode, resultCode, data);
TextView txtView = (TextView) findViewById(textView);
TextView txtMsg = (TextView) findViewById(R.id.textMsg);
txtView.setText("aaa");
if (requestCode == 100) {
Cursor cursor = null;
Cursor phone = null;
String[] projections = {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.HAS_PHONE_NUMBER
};
cursor = getContentResolver().query(
data.getData(),
projections,
null,
null,
null
);
if ((cursor == null) || (!cursor.moveToFirst())) {
txtView.setText("cursor is null");
} else {
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);
index = phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
String strName = phone.getString(index);
txtView.setText(strName + " ; " + number);
}
}
}
}
}
一、获取全部联系人
//读取联系人的函数
public void f_GetPhone(){
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] cols = {ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
Cursor cursor = getContentResolver().query(uri,
cols,
null,
null,
null);
String strOut;
strOut = "";
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
// 取得联系人名字
int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
int numberFieldColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String name = cursor.getString(nameFieldColumnIndex);
String number = cursor.getString(numberFieldColumnIndex);
strOut += name + number;
//Toast.makeText(this, name + " " + number, Toast.LENGTH_SHORT).show();
}
TextView txtOut = (TextView)findViewById(R.id.textView);
txtOut.setText(strOut);
}
其他地方转载收藏的相关代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
public
static
void
loadContacts(Context context) {
ArrayList<Contact> AllContacts =
new
ArrayList<Contact>();
ContentResolver resolver = context.getContentResolver();
// 要使用RawContacts.CONTACT_ID而不是Contacts.CONTACT_ID
String[] PROJECTION = {
RawContacts.CONTACT_ID, Contacts.DISPLAY_NAME,
Contacts.LOOKUP_KEY, Contacts.PHOTO_THUMBNAIL_URI,
Phone.NUMBER, Phone.TYPE, Contacts.STARRED
};
Cursor cursor = resolver.query(Phone.CONTENT_URI, PROJECTION,
null
,
null
, Contacts.SORT_KEY_PRIMARY);
String preLookupKey =
""
;
Contact preContact =
null
;
if
(cursor.moveToFirst()) {
do
{
long
contractID = cursor.getInt(
0
);
String displayName = cursor.getString(
1
);
String lookupKey = cursor.getString(
2
);
String photoUri = cursor.getString(
3
);
boolean
starred = cursor.getInt(
6
) ==
1
;
if
(lookupKey.equals(preLookupKey) && preContact !=
null
) {
preContact.addPhone(cursor.getString(
4
), cursor.getInt(
5
));
}
else
{
Contact contact =
new
Contact();
contact.setContactId(contractID);
contact.setName(displayName);
contact.setLookupKey(lookupKey);
contact.setPhotoUri(photoUri);
contact.addPhone(cursor.getString(
4
), cursor.getInt(
5
));
contact.setStarred(starred);
AllContacts.add(contact);
preLookupKey = lookupKey;
preContact = contact;
}
}
while
(cursor.moveToNext());
}
else
{
// No Phone Number Found
}
cursor.close();
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
public
static
void
loadStrequent() {
ArrayList<Contact> StrequentContacts =
new
ArrayList<Contact>();
String[] projection = { Contacts._ID, Contacts.DISPLAY_NAME,
Contacts.LOOKUP_KEY, Contacts.PHOTO_THUMBNAIL_URI,
Contacts.TIMES_CONTACTED, Contacts.LAST_TIME_CONTACTED,
Contacts.STARRED, Contacts.PHOTO_ID };
ContentResolver resolver = AppApplication.globalApplication
.getContentResolver();
// 显示最近联系人和收藏的联系人
Cursor cursor = resolver.query(Contacts.CONTENT_STREQUENT_URI,
projection,
null
,
null
,
null
);
// 加载最近联系人,不包括收藏的联系人
//Cursor cursor = resolver.query(
// Uri.withAppendedPath(Contacts.CONTENT_URI, "frequent"),
// projection, null, null, null);
while
(cursor.moveToNext()) {
Contact contact =
new
Contact();
long
contractID = cursor.getInt(
0
);
String displayName = cursor.getString(
1
);
String lookupKey = cursor.getString(
2
);
String photoUri = cursor.getString(
3
);
int
TIMES_CONTACTED = cursor.getInt(
4
);
long
LAST_TIME_CONTACTED = cursor.getLong(
5
);
boolean
starred = cursor.getInt(
6
) ==
1
;
contact.setContactId(contractID);
contact.setName(displayName);
contact.setLookupKey(lookupKey);
contact.setPhotoUri(photoUri);
contact.setStarred(starred);
contact.Times_Contacted = TIMES_CONTACTED;
contact.Last_Time_Contacted = LAST_TIME_CONTACTED;
StrequentContacts.add(contact);
}
cursor.close();
// notify
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
public
static
void
loadCallLogsCombined() {
if
(AllContacts.size() ==
0
) {
loadContacts();
}
ArrayList<Contact> recentContacts =
new
ArrayList<Contact>();
String[] projection = {
Calls._ID, Calls.TYPE, Calls.CACHED_NAME,
Calls.CACHED_NUMBER_TYPE, Calls.DATE, Calls.DURATION,
Calls.NUMBER
};
ContentResolver resolver = AppApplication.globalApplication
.getContentResolver();
Cursor cursor = resolver.query(Calls.CONTENT_URI, projection,
null
,
null
, Calls.DEFAULT_SORT_ORDER);
while
(cursor.moveToNext()) {
long
callID = cursor.getInt(
0
);
int
callType = cursor.getInt(
1
);
String name = cursor.getString(
2
);
int
numberType = cursor.getInt(
3
);
long
date = cursor.getLong(
4
);
int
duration = cursor.getInt(
5
);
String number = cursor.getString(
6
);
if
(TextUtils.isEmpty(name)) {
boolean
matched =
false
;
for
(Iterator<Contact> iterator = recentContacts.iterator(); iterator
.hasNext();) {
Contact con = iterator.next();
if
(con.Last_Contact_Number.equals(number)) {
matched =
true
;
con.Times_Contacted++;
break
;
}
}
if
(!matched) {
Contact tmpContact =
new
Contact();
tmpContact.Times_Contacted =
1
;
tmpContact.Last_Contact_Call_ID = callID;
tmpContact.Last_Contact_Call_Type = callType;
tmpContact.Last_Contact_Number = number;
tmpContact.Last_Contact_Phone_Type = numberType;
tmpContact.Last_Time_Contacted = date;
tmpContact.Last_Contact_Duration = duration;
recentContacts.add(tmpContact);
}
}
else
{
boolean
matched =
false
;
for
(Iterator<Contact> iterator = recentContacts.iterator(); iterator
.hasNext();) {
Contact con = iterator.next();
if
(con.Last_Contact_Number.equals(number)) {
matched =
true
;
con.Times_Contacted++;
break
;
}
}
if
(!matched) {
match2:
for
(Iterator<Contact> iterator = AllContacts
.iterator(); iterator.hasNext();) {
Contact con = iterator.next();
ArrayList<PhoneStruct> phones = con.getPhones();
for
(Iterator<PhoneStruct> iterator2 = phones
.iterator(); iterator2.hasNext();) {
PhoneStruct phoneStruct = iterator2.next();
if
(phoneStruct.phoneNumber.equals(number)) {
matched =
true
;
Contact tmpContact = con.clone();
tmpContact
.setPhones(
new
ArrayList<Contact.PhoneStruct>());
tmpContact.Times_Contacted =
1
;
tmpContact.Last_Contact_Call_ID = callID;
tmpContact.Last_Contact_Call_Type = callType;
tmpContact.Last_Contact_Number = number;
tmpContact.Last_Contact_Phone_Type = numberType;
tmpContact.Last_Time_Contacted = date;
tmpContact.Last_Contact_Duration = duration;
recentContacts.add(tmpContact);
break
match2;
}
}
}
}
}
}
cursor.close();
}
|
获取联系人和电话号码
private void queryContactPhoneNumber() { String[] cols = {ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER}; Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, cols, null, null, null); for (int i = 0; i < cursor.getCount(); i++) { cursor.moveToPosition(i); // 取得联系人名字 int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME); int numberFieldColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); String name = cursor.getString(nameFieldColumnIndex); String number = cursor.getString(numberFieldColumnIndex); Toast.makeText(this, name + " " + number, Toast.LENGTH_SHORT).show(); } }
根据电话号码查询联系人姓名的方法:
public class AndroidTest extends Activity { private static final String TAG = "AndroidTest"; private TextView m_TextView; private EditText m_EditText; private String mNumber; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); m_TextView = (TextView) findViewById(R.id.TextView01); m_EditText = (EditText) findViewById(R.id.EditText01); m_TextView.setTextSize(20); /** * 设置当m_EditText中为空时提示的内容 * 在XML中同样可以实现:android:hint="请输入账号" */ m_EditText.setHint("请输入账号"); /* 设置EditText事件监听 */ m_EditText.setOnKeyListener(new EditText.OnKeyListener() { public boolean onKey(View arg0, int arg1, KeyEvent arg2) { // TODO Auto-generated method stub // 得到文字,将其显示到TextView中 // m_TextView.setText("文本框中内容是:" + m_EditText.getText().toString()); return false; } }); m_EditText.setOnFocusChangeListener(new OnFocusChangeListener() { public void onFocusChange(View v, boolean hasFocus) { // TODO Auto-generated method stub mNumber = ((EditText)v).getText().toString(); Log.d(TAG, "mNumber = " + mNumber); getPeople(); } }); m_EditText.addTextChangedListener(new TextWatcher() { public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub // 得到文字,将其显示到TextView中 m_TextView.setText("文本框中内容是:" + m_EditText.getText().toString()); } }); } /* * 根据电话号码取得联系人姓名 */ public void getPeople() { String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER}; Log.d(TAG, "getPeople ---------"); // 将自己添加到 msPeers 中 Cursor cursor = this.getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, // Which columns to return. ContactsContract.CommonDataKinds.Phone.NUMBER + " = '" + mNumber + "'", // WHERE clause. null, // WHERE clause value substitution null); // Sort order. if( cursor == null ) { Log.d(TAG, "getPeople null"); return; } Log.d(TAG, "getPeople cursor.getCount() = " + cursor.getCount()); for( int i = 0; i < cursor.getCount(); i++ ) { cursor.moveToPosition(i); // 取得联系人名字 int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME); String name = cursor.getString(nameFieldColumnIndex); Log.i("Contacts", "" + name + " .... " + nameFieldColumnIndex); // 这里提示 force close m_TextView.setText("联系人姓名:" + name); } } }