Android - Setting a Timeout for an AsyncTask? Android - Setting a Timeout for an AsyncTask? java java

Android - Setting a Timeout for an AsyncTask?


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.


In the case, your downloader is based upon an for an URL connection, you have a number of parameters that could help you to define a timeout without complex code:

  HttpURLConnection urlc = (HttpURLConnection) url.openConnection();  urlc.setConnectTimeout(15000);  urlc.setReadTimeout(15000);

If you just bring this code into your async task, it is ok.

'Read Timeout' is to test a bad network all along the transfer.

'Connection Timeout' is only called at the beginning to test if the server is up or not.


Use CountDownTimer Class in side the extended class for AsyncTask in the onPreExecute() method:

Main advantage, the Async monitoring done internally in the class.

public class YouExtendedClass extends AsyncTask<String,Integer,String> {...public YouExtendedClass asyncObject;   // as CountDownTimer has similar method -> to prevent shadowing...@Overrideprotected void onPreExecute() {    asyncObject = this;    new CountDownTimer(7000, 7000) {        public void onTick(long millisUntilFinished) {            // You can monitor the progress here as well by changing the onTick() time        }        public void onFinish() {            // stop async task if not in progress            if (asyncObject.getStatus() == AsyncTask.Status.RUNNING) {                asyncObject.cancel(false);                // Add any specific task you wish to do as your extended class variable works here as well.            }        }    }.start();...

change CountDownTimer(7000, 7000) -> CountDownTimer(7000, 1000) for example and it will call onTick() 6 times before calling onFinish(). This is good if you want to add some monitoring.

Thanks for all the good advice I got in this page :-)