So my problem is that i have a AsyncTask that scraps html from a page on a server so i used Jsoup as a library . so the problem is that i want to set a timeout to cancel the Task if i don't receive any data from the page and display that there is a "communication error " on a toast
is there anyway to kill or stop the asynctask within it self and return a result on onPostExecute
{
private class getPageTitle extends AsyncTask<Void, Void, String> {
String title;
@Override
protected void onPreExecute() {
super.onPreExecute();
connectServerProgressDialog = new ProgressDialog(LoginScreen.this);
connectServerProgressDialog.setTitle("CheckingServer");
connectServerProgressDialog.setMessage("Loading...");
connectServerProgressDialog.setIndeterminate(true);
connectServerProgressDialog.show();
}
@Override
protected String doInBackground(Void... params) {
try {
// Connect to the web site
Document document = Jsoup.connect(CONNECT_URL).get();
title = document.title();
} catch (IOException e) {
e.printStackTrace();
}
return null ;
}
@Override
protected void onPostExecute(String result) {
if(result!=null){
switch (title) {
case "0":
Toast.makeText(LoginScreen.this,"offline",Toast.LENGTH_SHORT).show();
connectServerProgressDialog.dismiss();
break;
case "1":
connectServerProgressDialog.dismiss();
Toast.makeText(LoginScreen.this,"Connected",Toast.LENGTH_SHORT).show();
break;
}}else{
Toast.makeText(LoginScreen.this,"Communication error",Toast.LENGTH_SHORT).show();
}
}
}}
I have a convention that I use for
AsyncTask
subclasses.AsyncTask
can be re-used. The interface is named in the formblahblahListener
.blahblahCompleted()
andblahblahException()
.AsyncTask
constructor or set with asetListener()
method.WeakReference
field so that if the listener goes away before the task completes, the listener can still be garbage-collected.Exception
. If an exception occurs in the background method, this field remembers the exception in order to report it to the client.onPostExecute()
method, check if the Exception field is null. If it is, callblahblahCompleted()
with the result. If it isn't, callblahblahException()
with the exception. Also check if theWeakReference
is still valid.For killing the task, you can have a timeout set on your connection. Then when your connection times out, you will get an exception, which is remembered and reported.
So using that convention, your code would look like this:
And your client code would look something like this, with your
Activity
implementing that inner interface:NOTE: Because the listener is held in a
WeakReference
, you can't use an anonymous inner class for the listener, because the reference will go away almost immediately and be eligible for garbage collection.I use this convention consistently, and the extra boilerplate code in the
AsyncTask
subclass makes it a lot cleaner to use in the client class.