选择联系人类似于打开图库和选择图片,但如何访问所有联系人并将其与我的应用程序相关联。为了练习我正在尝试创建一个基本的聊天应用程序,所以我不希望注册的用户显示在我的活动中,但我想只显示我的联系人中的用户以及使用我的应用程序的用户就像whatsapp ,微信或任何其他短信应用程序。另外我在想是否可以像联系人那样访问收藏夹...我怎样才能实现这一目标?
要检索所有联系人,您可以使用以下内容:
final ArrayList<Contact> contacts = new ArrayList<>();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor != null) {
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id},
null);
if (phoneCursor != null) {
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts.add(new Contact(name, phoneNumber));
phoneCursor.close();
}
}
}
}
}
cursor.close();
}
例如,为了获得仅使用聊天的人,也许您应该将该信息保存在服务器中,使用电话号码作为ID。当您检索所有联系人时,您可以比较电话号码并仅将数据添加到服务器中注册的那些...
ContentResolver cr = context.getApplicationContext().getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id;
String name;
String phoneNumbers = "";
id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
if (cur.getInt(cur.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String pn = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
if (pCur.isFirst())
phoneNumbers += pn;
else
phoneNumbers += ", " + pn;
}
pCur.close();
}
}
}
cur.close();