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
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With