Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel an Android AsyncTask after a certain amount of time? (Eg. 10 seconds)

I want to use a AsyncTask to check an InetAddress, such as in the code below. The variable tempInet is a global variable that indicates whether the website was contactable or not.

I begin the AsyncTask with the code... new InetAsyncTask().execute("www.facebook.com");

My problem is that I want the AsyncTask to cancel itself after (say) 10 seconds.

Some other questions suggest using the get(10, TimeUnit.SECONDS) method. I would like to do this but not sure where/how to put the get method. With execute? In the doInBackground method?

Also, does the get() method block the main thread? If it does, what is the point of it?

Any help appreciated.

 class InetAsyncTask extends AsyncTask<String, String, Boolean> {



    @Override
    protected Boolean doInBackground(String... params) {

        try {                 
                InetAddress.getByName("www.facebook.com");
                return true;          

                } catch (UnknownHostException e) {  
                  return false;
                }

    } //end doInBackground function



    protected void onPostExecute(Boolean... result) {

           tempInet = result[0];

    }


   } //end class

Related Questions

Android - Setting a Timeout for an AsyncTask?

stop async task after 60 second

Android Developers AsyncTask Documentation

http://developer.android.com/reference/android/os/AsyncTask.html

like image 637
Mel Avatar asked Nov 13 '22 08:11

Mel


1 Answers

You should make a handler which cancels the Asynctask (http://developer.android.com/reference/android/os/AsyncTask.html#cancel(boolean))

Send a delayed message to this Handler like:

Handler.sendMessageDelayed(msg, delayMillis)

private android.os.Handler mHandler = new android.os.Handler() {

    @Override
    public void handleMessage(Message msg) {
        (Your AsyncTask object).cancel(true);
    }
}
like image 117
Ion Aalbers Avatar answered Nov 16 '22 04:11

Ion Aalbers