簡體   English   中英

Android獲得隨機聯系-可以在Activity和主UI線程上運行嗎?

[英]Android get random contact - ok to run in Activity and on main UI thread?

我使用基於此答案的代碼Android獲取隨機聯系人來查詢具有電話號碼的聯系人,然后選擇一個隨機電話並獲取其電話號碼:

    // 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();
        }
    } 

我的問題是:這樣快到足以在主線程上使用,例如在Activity的onCreate中使用嗎? 我擔心ANR。 (或者我應該使用CursorLoader在后台線程上執行游標查詢,以便它不會阻塞應用程序的UI?)

后台線程更安全,然后主線程對此使用異步任務,這有​​時可能是聯系人較多且設備RAM較小,然后應用程序將崩潰

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM