在Android中获取联系人的groupId/GroupName,可以通过使用ContentResolver查询数据库来实现。以下是一个简单的示例代码:
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.Groups;
import android.provider.ContactsContract.RawContacts;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(Contacts.CONTENT_URI, null, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(Contacts._ID));
String displayName = cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME));
Cursor groupMembershipCursor = contentResolver.query(Data.CONTENT_URI,
new String[]{GroupMembership.GROUP_ROW_ID},
Data.CONTACT_ID + "=? AND " + Data.MIMETYPE + "=?",
new String[]{contactId, GroupMembership.CONTENT_ITEM_TYPE}, null);
if (groupMembershipCursor != null) {
while (groupMembershipCursor.moveToNext()) {
String groupId = groupMembershipCursor.getString(groupMembershipCursor.getColumnIndex(GroupMembership.GROUP_ROW_ID));
Cursor groupNameCursor = contentResolver.query(Groups.CONTENT_URI,
new String[]{Groups.TITLE},
Groups._ID + "=?",
new String[]{groupId}, null);
if (groupNameCursor != null) {
while (groupNameCursor.moveToNext()) {
String groupName = groupNameCursor.getString(groupNameCursor.getColumnIndex(Groups.TITLE));
System.out.println("Contact Name: " + displayName + ", Group ID: " + groupId + ", Group Name: " + groupName);
}
groupNameCursor.close();
}
}
groupMembershipCursor.close();
}
}
cursor.close();
}
}
}
在这个示例中,我们首先获取了联系人的ID和显示名称,然后查询联系人所属的群组ID,最后通过群组ID查询群组名称。
注意:这个示例代码仅供参考,实际应用中需要根据具体需求进行调整和优化。
领取专属 10元无门槛券
手把手带您无忧上云