在我們開發應用程序時,通常都會用到獲取手機聯系人信息這一十分常用的功能,最近項目裡也要實現此功能,想到以後的APP還十分可能還有此功能,就干脆把這個小功能放到一個類中去,這樣以後再遇到這個需求就不需要再去寫代碼了,直接把這個類拷過來就可以用了.
以下是獲取聯系人demo的效果圖,比較簡陋,能說明問題就好.
以一個列表的形式顯示所有聯系,如果有頭像則顯示頭像,沒有頭像則顯示APP默認icon..<喎?/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+z8LD5srHt+LXsLrDtcTA4LT6wus6PC9wPgo8cD48cHJlIGNsYXNzPQ=="brush:java;">/**
* @author renzhiqiang 獲取手機聯系人姓名,電話,郵箱,頭像
*/
public class GetContacts {
private static ArrayList getAllContacts(Context context) {
ArrayList contacts = new ArrayList();
Cursor cursor = context.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
//新建一個聯系人實例
MyContacts temp = new MyContacts();
String contactId = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
temp.name = name;
//獲取聯系人所有電話號
Cursor phones = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
+ contactId, null, null);
while (phones.moveToNext()) {
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
temp.phones.add(phoneNumber);
}
phones.close();
//獲取聯系人所有郵箱.
Cursor emails = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = "
+ contactId, null, null);
while (emails.moveToNext()) {
String email = emails
.getString(emails
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
temp.emails.add(email);
}
emails.close();
// 獲取聯系人頭像
temp.photo = getContactPhoto(context, contactId,
R.drawable.ic_launcher);
contacts.add(temp);
}
return contacts;
}
/**
* 獲取手機聯系人頭像
*
* @param c
* @param personId
* @param defaultIco
* @return
*/
private static Bitmap getContactPhoto(Context c, String personId,
int defaultIco) {
byte[] data = new byte[0];
Uri u = Uri.parse("content://com.android.contacts/data");
String where = "raw_contact_id = " + personId
+ " AND mimetype ='vnd.android.cursor.item/photo'";
Cursor cursor = c.getContentResolver()
.query(u, null, where, null, null);
if (cursor.moveToFirst()) {
data = cursor.getBlob(cursor.getColumnIndex("data15"));
}
cursor.close();
if (data == null || data.length == 0) {
return BitmapFactory.decodeResource(c.getResources(), defaultIco);
} else
return BitmapFactory.decodeByteArray(data, 0, data.length);
}
}沒有任何難點,只是做了一個小小的封裝,使得以後不必再重復的去實現.