选择联系人类似于打开画廊并选择图片,但是如何访问所有联系人并将其与我的应用相关联。 作为练习,我尝试创建一个基本的聊天应用程序,因此我不希望注册的用户显示在我的活动中,但我只想显示联系人中以及正在使用我的应用程序的用户,如whatsapp ,微信或其他任何短信应用。我也在想我是否可以像“联系人”一样访问“收藏夹...”如何实现?
答案 0 :(得分:1)
要检索所有联系人,您可以使用以下方式:
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。当您检索所有联系人时,您可以比较电话号码,并仅将服务器中注册的联系人添加到数组中。
答案 1 :(得分:0)
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();