I'm using code based on this answer Android Get Random Contact to query contacts that have a phone number, then select a random one and get its number:
// Query the contacts
Cursor cursor = getContentResolver().query(
Contacts.CONTENT_URI,
new String[] { Contacts._ID, Contacts.HAS_PHONE_NUMBER },
Contacts.HAS_PHONE_NUMBER + "=1",
null,
null);
int cursorSize = cursor != null ? cursor.getCount() : 0;
if (cursorSize > 0) {
try {
for (int i = 0; i < MAX_TRIES; i++) {
// Select a random contact
cursor.moveToPosition(random.nextInt(cursorSize));
// Test if the current selected contact has at least one phone number
Boolean hasPhone = Integer.parseInt(cursor.getString(
cursor.getColumnIndex(Contacts.HAS_PHONE_NUMBER))) > 0;
if (hasPhone) {
String contactId = cursor.getString(cursor.getColumnIndex(Contacts._ID));
phoneNumber = this.selectPhoneNumber(contactId);
// If a non-empty phone number has been successfully selected, break the loop
if (!TextUtils.isEmpty(phoneNumber)) {
break;
}
}
}
} finally {
cursor.close();
}
}
My question is: is this fast enough to use on the main thread, for example in the onCreate of an Activity? I'm worried about ANRs. (Or should I use a CursorLoader to to perform the cursor query on a background thread so that it does not block the application's UI?)