I have a non Activity class that contains an AsyncTask that calls a URL. If the connection timed out for some reason, I want to inform the user about this by posting Toast. But I just can't get the context.
How can this be achieved?
RPIcall.class
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import java.io.IOException;
class RPicall extends AsyncTask<String, String, Void> {
@Override
protected Void doInBackground(String... uri) {
int timeoutSocket = 3000;
int timeoutConnection = 3000;
try{
Log.v("call URL: ", uri[0]);
HttpGet httpGet = new HttpGet(uri[0]);
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);
} catch (ClientProtocolException e) {
Log.v("Server not Reachable: ", uri[0]);
publishProgress("TimeOut");
} catch (HttpHostConnectException e) {
Log.e("Server not Reachable: ", uri[0]);
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
String test = "test";
Log.v("finished: ", test);
}
}
source
share