0

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?

djac
  • 187
  • 19

1 Answers1

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