I have created IntentService
class and performing asyncTask
but getting exception when onPreExecute()
is called at this code line
If for whatever reason you really really really want to use an AsyncTask (e.g. you've set up your framework to use AsyncTask to make calls to some web api) you can always use wait/notify such as:
public class GetCacheIntentService extends DebuggableIntentService implements ApiAsyncTask.Callback {
private static final String ACTION_GET_CACHE = "action.GET_CACHE";
private static final String EXTRA_INT_START = "extras.START";
private static final String EXTRA_INT_LIMIT = "extras.LIMIT";
private static final int API_GET_CACHE = 0;
private final Object mApiCallLock = new Object();
private GetCacheResponse getCacheResponse;
public GetCacheIntentService() {
super("GetCacheIntentService");
setIntentRedelivery(true);
}
public static void startServiceActionGetCache(Context context, int start, int limit) {
Intent intent = new Intent(context, GetCacheIntentService.class);
intent.setAction(ACTION_GET_CACHE);
intent.putExtra(EXTRA_INT_START, start);
intent.putExtra(EXTRA_INT_LIMIT, limit);
context.startService(intent);
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent == null) {
return;
}
String action = intent.getAction();
if (ACTION_GET_CACHE.equals(action)) {
int start = intent.getIntExtra(EXTRA_INT_START, 0);
int limit = intent.getIntExtra(EXTRA_INT_LIMIT, 100);
getCache(start, limit);
}
}
private void getCache(int start, int limit) {
GetCacheTask task = new GetCacheTask(this, API_GET_CACHE);
task.setStart(start);
task.setLimit(limit);
task.execute();
synchronized (mApiCallLock) {
try {
mApiCallLock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
processResponse(mGetCacheResponse);
}
public void processResponse(GetCacheResponse response) {
// do something
}
@Override
public void onRequestFailed(int id, ApiResponse apiResponse) {
synchronized (mApiCallLock) {
switch (id) {
case API_GET_CACHE:
break;
}
mApiCallLock.notify();
}
}
@Override
public void onRequestSuccess(int id, ApiResponse response) {
synchronized (mApiCallLock) {
switch (id) {
case API_GET_CACHE:
mGetCacheResponse = (GetCacheResponse) response;
break;
}
mApiCallLock.notify();
}
}
}
this is quite ugly though :(