Android Get Random Contact

2019-06-08 06:32发布

I'm trying to get a random contact from a phone's contact list, but without noticeably slowing down the phone. That means that I can't just grab all the contacts and stick them into an array and pick a random one from that array. I'd like to be able to get a random contact without having to get all of the contacts first. Is this possible, and if so, how would I go about doing it?

1条回答
Emotional °昔
2楼-- · 2019-06-08 06:55

Updated to use non-deprecated code. Query based on this answer: How to read contacts on Android 2.0

Cursor managedCursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null); 

Then it's just a matter of getting the size of the Cursor:

int size = managedCursor.getCount();

get a random one, read it and check if it has phone numbers. If not, choose another one:

boolean found = false;
Random rnd = new Random();
while(!found) {
  int index = rnd.nextInt(size);    
  managedCursor.moveToPosition(index);
  String name = managedCursor.getString(people.getColumnIndex(PhoneLookup.DISPLAY_NAME));
  found = Boolean.parseBoolean(managedCursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))); 
  if (found) {
    Cursor phones = getContentResolver().query( 
    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, 
    ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null); 
    while (phones.moveToNext()) { 
     String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
     Log.d("Phone found:", phoneNumber);                 
    } 
    phones.close();
  }
}

I don't see how you could pick a random one otherwise. And this should not slow the phone down unless it's a really large contacts list.

Now it checks for the presence of phone numbers and reads all of them if found. If not, it chooses another entry.

查看更多
登录 后发表回答