Android的一些随机的联系 [英] Android Get Random Contact
问题描述
我想从手机的联系人列表中的联系人随机,但没有明显放缓的手机。这意味着,我不能只抓住所有的联系人,并将他们粘成一个阵列,并挑选从数组随机之一。我希望能够得到一个随机的联系,而不必让所有的联系人的第一。
这是可能的,如果是这样,我怎么会去这样做呢?
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?
推荐答案
更新使用非德precated code。基于这个答案查询:<一href=\"http://stackoverflow.com/questions/1721279/how-to-read-contacts-on-android-2-0/1780818#1780818\">How阅读关于Android 2.0的接触
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();
}
}
我不明白你怎么能选择一个随机否则为1。而这不应该放慢了电话,除非它是一个非常大的联系人列表中。
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.
现在它会检查电话号码的presence如果发现读取所有的人。如果不是,它选择了另一个入口。
Now it checks for the presence of phone numbers and reads all of them if found. If not, it chooses another entry.
这篇关于Android的一些随机的联系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!