我必须尝试从手机获取 WhatsApp 联系人,我得到了 WhatsApp 联系人的总数,但是从
RawContacts
如何获取我不知道的 WhatsApp 号码和姓名。我试图找到解决方案,但无法得到确切的解决方案。请帮助我。
我把我的代码放在下面。
ContentResolver cr = context.getContentResolver();
Cursor c = cr.query(
ContactsContract.RawContacts.CONTENT_URI,
new String[] { ContactsContract.RawContacts.CONTACT_ID, ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY },
ContactsContract.RawContacts.ACCOUNT_TYPE + "= ?",
new String[] { "com.whatsapp" },
null);
ArrayList<String> myWhatsappContacts = new ArrayList<>();
String projection[] = { ContactsContract.CommonDataKinds.Phone.NUMBER };
if(c != null) {
if (c.getCount() > 0) {
while (c.moveToNext()) {
String whatsappContactId = c.getString(c.getColumnIndex(ContactsContract.RawContacts.Data._ID));
Cursor dataCursor = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{whatsappContactId}, null);
// You can also read RawContacts.CONTACT_ID to read the
// ContactsContract.Contacts table or any of the other related ones.
String number = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER));
myWhatsappContacts.add(number);
}
}
}
showLogI(TAG, " WhatsApp contact size : " + myWhatsappContacts.size());
要检索 WhatsApp 联系人,包括他们的姓名和电话号码,您需要查询
RawContacts
和 Android Contacts ContentProvider
中的数据表。您当前的方法已经很接近了,但还存在一些问题和需要改进。
这是固定版本:
ContentResolver cr = context.getContentResolver();
// Query for WhatsApp contacts
Cursor rawContactsCursor = cr.query(
ContactsContract.RawContacts.CONTENT_URI,
new String[]{ContactsContract.RawContacts.CONTACT_ID},
ContactsContract.RawContacts.ACCOUNT_TYPE + " = ?",
new String[]{"com.whatsapp"},
null
);
ArrayList<String> myWhatsappContacts = new ArrayList<>();
if (rawContactsCursor != null) {
if (rawContactsCursor.getCount() > 0) {
while (rawContactsCursor.moveToNext()) {
String contactId = rawContactsCursor.getString(rawContactsCursor.getColumnIndex(ContactsContract.RawContacts.CONTACT_ID));
// Query for phone numbers and names for the contact
Cursor dataCursor = cr.query(
ContactsContract.Data.CONTENT_URI,
new String[]{
ContactsContract.Data.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
},
ContactsContract.Data.CONTACT_ID + " = ? AND " +
ContactsContract.Data.MIMETYPE + " = ?",
new String[]{
contactId,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
},
null
);
if (dataCursor != null) {
while (dataCursor.moveToNext()) {
String name = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
String number = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
myWhatsappContacts.add(name + " : " + number);
}
dataCursor.close();
}
}
}
rawContactsCursor.close();
}
// Log the result
Log.i(TAG, "WhatsApp contact size: " + myWhatsappContacts.size());
for (String contact : myWhatsappContacts) {
Log.i(TAG, "WhatsApp Contact: " + contact);
}
我做了什么?
积分