I have an AsyncTask that calls a webservice and gets a json object from it. I want to set a timeout for this task so that if anything goes wrong(such as internet connection being disconnected or etc), the AsyncTask get cancelled.
Here is my code so far:
@Override
protected void onStart() {
final GetRequestsTask requestTask = new GetRequestsTask();
requestTask.execute(createUrl());
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Log.d("myapp", "entered handler");
if (requestTask.getStatus() == AsyncTask.Status.RUNNING) {
Log.d("myapp", "entered cancelling");
requestTask.cancel(true);
}
}
}, TIME_OUT);
}
The problem is that when the handler reaches "entered cancelling" point and sends the cancel signal to the AsyncTask, it won't cancel and call onCancelled() immediately (it will be called after 10 seconds or so if at all)
My GetRequestTask is linear, meaning that it does not have a loop inside it so I cannot check for isCancelled() manually inside the doInBackground() method.
What do you suggest me to do?