Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.


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
...
@Override
protected 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 :-)


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.


I don't think there's anything like that built into AsyncTask. Your approach seems to be a good one. Just be sure to periodically check the value of isCancelled() in your AsyncTask's doInBackground method to end this method once the UI thread cancels it.

If you want to avoid using the handler for some reason, you could check System.currentTimeMillis periodically within your AsyncTask and exit on timeout, although I like your solution better since it can actually interrupt the thread.