我正在尝试从联系人处获取电子邮件地址和电话号码。我的班级没有extend Activity
,现在我被卡住了。
我该如何克服这个问题?
答案 0 :(得分:6)
获取电子邮件联系人
public void getEmailContacts()
{
try
{
String name;
ContentResolver cr = getContentResolver();
cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,null, null, null);
emailIndex=0;
if (cur.getCount() > 0)
{
ArrayList<String> emailNameList=new ArrayList<String>();
ArrayList<String> emailPhoneList=new ArrayList<String>();
while (cur.moveToNext())
{
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID+ " = " + id, null, null);
while (emails.moveToNext())
{
// This would allow you get several email addresses
String emailAddress = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
Log.v(name+"==>", emailAddress);
if ((!emailAddress.equalsIgnoreCase(""))&&(emailAddress.contains("@")))
{
emailNameList.add(name);
emailPhoneList.add(emailAddress);
emailIndex++;
}
}
emails.close();
}
获取手机联系
String name;
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,null, null, null);
if (cur.getCount() > 0)
{
ArrayList<String> phoneNameList=new ArrayList<String>();
ArrayList<String> PhoneList=new ArrayList<String>();
while (cur.moveToNext())
{
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
phoneNameList.add(name);
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?", new String[] { id }, null);
while (pCur.moveToNext())
{
PhoneList.add(pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
pCur.close();
}
}