I have an AsyncTask which calls a third party API and pass few parameters and gets JSON as result. But, sometimes it takes too much time to execute. Suppose , i want to execute this AsyncTask only for 30 seconds and if it is not completed within 30 seconds, then abort the AsyncTask and continue executing the remaining code. Can you give some reference/example for this?
Asked
Active
Viewed 356 times
1 Answers
2
You can set CountDownTimer
to stop the AsyncTask
if it runs more than 30 seconds.
For Example:
new CountDownTimer(30000, 28000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
asyncTask.cancel(true); //
}
}.start();
Another way is Handler.
new Handler().postDelayed(new Runnable(){
@Override
public void run() {
asyncTask.cancel(true);
}
},30000)
Another simple way is to set Connection Timeout for your HTTP call to 30 seconds. It will automatically ends the async task after 30 seconds.

Bhuvanesh BS
- 13,474
- 12
- 40
- 66
-
Sure you can do. It actually runs in the background. Don't use UI component inside countdown timer. – Bhuvanesh BS Aug 13 '17 at 08:32
-
See my updated answer. If you also need to use UI component inside it. You can use a handler. – Bhuvanesh BS Aug 13 '17 at 08:35