2017-09-15 97 views
0

我有很多記錄,我從web服務中提取,我需要在本地緩存它們。在執行此操作時(超過1000條記錄)UI線程被阻止,並且收到ANR警告。我認爲使用IntentService不會阻止用戶界面。我做錯了什麼?通過IntentService在Sqlite數據庫中存儲內容會阻塞UI線程

很少的代碼片段:

public class ContentIntentService extends IntentService { 

@Override 
protected void onHandleIntent(Intent workIntent) { 
    code = workIntent.getStringExtra("CODE"); 
    getContent(code); 
} 

private void getContent(final String code) { 
    if (apiService == null) { 
     Retrofit client = ApiClient.getClient(); 
     if (client != null) 
      apiService = client.create(ApiInterface.class); 
    } 
    if (apiService == null) { 
     MobileValetHelper.onConnectionFailed(mAppContext); 
     return; 
    } 
    Call<SectionsResponse> call = apiService.getOutletContent(outletCode, outletCode, MobileValetHelper.getContentSessionToken(mAppContext)); 
    call.enqueue(new Callback<SectionsResponse>() { 
     @Override 
     public void onResponse(@NonNull Call<SectionsResponse> call, @NonNull Response<SectionsResponse> response) { 
      if (response != null 
        && response.body() != null 
        && response.body().status != null 
        && response.body().status.equalsIgnoreCase("Success") 
        && response.body().sessionToken != null 
        && response.body().data != null 
        ) { 
         DataCacheHelper dataCacheHelper = new DataCacheHelper(ContentIntentService.this); 
         dataCacheHelper.insertItems(ContentIntentService.this, items); 
        } 
      } else if (response != null 
        && response.errorBody() != null) { 
       Log.e(TAG, "getContent response.errorBody(): " + response.errorBody().string()); 
      } 
     } 

     @Override 
     public void onFailure(@NonNull Call<SectionsResponse> call, @NonNull Throwable t) { 
      Log.e(TAG, "getContent onFailure: " + t.toString()); 
     } 
    }); 
} 

}

公共類DataCacheHelper { 私人ContentIntentService mIntentService;

public DataCacheHelper(ContentIntentService service) { 
     mIntentService = service; 
    } 

    public void insertItems(final ArrayList<CategoryItem> items) { 

     if (mIntentService != null && items != null) { 
      try { 
       ContentValues[] valueList = new ContentValues[items.size()]; 
       int i = 0; 
       ContentValues values; 
       for (final CategoryItem item : items) { 
        values = ItemsTable.getContentValues(item); 
        valueList[i++] = values; 
       } 
       context.getContentResolver().bulkInsert(provider.CONTENT_URI, valueList); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
    } 
} 

}

+0

你是如何開始服務的? –

回答

1

首先,切勿從IntentService異步的東西。一旦onHandleIntent()返回,IntentService將被銷燬。在你的情況下,網絡I/O可能仍在繼續,更不用說磁盤I/O了。

其次,在主應用程序線程上調用onResponse(),這是您難度的來源。

因此,請使用​​代替enqueue(),並直接在onHandleIntent()的線程上執行所有工作。

+0

謝謝:)幫助我。 –