background thread is more safe then main thread use async task for this coz some times may be contacts is more and device RAM is less then app will be crash
Android get random contact - ok to run in Activity and on main UI thread?
-
14-06-2023 - |
質問
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?)
解決
所属していません StackOverflow