2014-03-13 19 views
0

我使用基於這個答案Android Get Random Contact 來查詢有一個電話號碼的聯繫人代碼,然後選擇一個隨機並獲得其編號:Android獲得隨機聯繫 - 確定在Activity和主UI線程中運行?

// 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?)

+0

後臺線程更安全,然後主線程使用異步任務,因爲這個因爲有些時候可能聯繫人更多和設備內存少,然後應用程序將崩潰 –

回答

1

後臺線程更安全,然後主線程使用異步任務聯繫人更多,設備內存不足,那麼應用程序將崩潰

相關問題