我有很多記錄,我從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();
}
}
}
}
你是如何開始服務的? –