Android - Setting a Timeout for an AsyncTask?

Jake Wilson picture Jake Wilson · Oct 25, 2011 · Viewed 73.2k times · Source

I have an AsyncTask class that I execute that downloads a big list of data from a website.

In the case that the end user has a very slow or spotty data connection at the time of use, I'd like to make the AsyncTask timeout after a period of time. My first approach to this is like so:

MyDownloader downloader = new MyDownloader();
downloader.execute();
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
  @Override
  public void run() {
      if ( downloader.getStatus() == AsyncTask.Status.RUNNING )
          downloader.cancel(true);
  }
}, 30000 );

After starting the AsyncTask, a new handler is started that will cancel the AsyncTask after 30 seconds if it's still running.

Is this a good approach? Or is there something built into AsyncTask that is better suited for this purpose?

Answer

yorkw picture yorkw · Oct 25, 2011

Yes, there is AsyncTask.get()

myDownloader.get(30000, TimeUnit.MILLISECONDS);

Note that by calling this in main thread (AKA. UI thread) will block execution, You probably need call it in a separate thread.