2
Hello I’m with a class to make to read an HTML page, but I wanted it to have a time limit for the execution, my code seems to do it, but it does not work as it should, IE, the time I put is not happening anything
private class GrabURL extends AsyncTask<String, Void, Void> {
InputStream is = null;
int response = -1;
URL url;
URLConnection conn;
String retorno = null;
private ProgressDialog Dialog = new ProgressDialog(TelaLogin.this);
protected void onPreExecute() {
Dialog.setMessage("Carregando. Aguarde...");
Dialog.setCanceledOnTouchOutside(false);
Dialog.show();
}
protected Void doInBackground(String... urls) {
try {
url = new URL(urls[0]);
conn = url.openConnection();
if(!(conn instanceof HttpURLConnection))
{
retorno = "Erro-Tempo";
return null;
}
else
{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.setReadTimeout(8000); // 8 segundos para ler
httpConn.setConnectTimeout(4000); // 4 segundos para conectar
httpConn.connect();
response = httpConn.getResponseCode();
if(response == HttpURLConnection.HTTP_OK)
{
is = httpConn.getInputStream();
retorno = inputStreamToString(is).toString();
}
else
retorno = "Erro-Tempo";
}
}catch(SocketTimeoutException ex){
retorno = "Erro-Tempo";
cancel(true);
}catch (ClientProtocolException e) {
retorno = "Invalido-Erro";
cancel(true);
} catch (IOException e) {
retorno = "Invalido-Erro";
cancel(true);
}
return null;
}
protected void onPostExecute(Void unused) {
Dialog.dismiss();
trataRetorno(retorno);
}
}
What is going wrong, what is your claim to the timeout’s? What’s wrong? What’s the problem?
– Fernando Leal
I want to take too long to download the content to be canceled and generate a message to the user saying that his connection is bad. My code keeps trying to connect all the time, even if it takes more than 8 seconds, it does not cancel any time.
– Gabriel Duarte
Vixi, it seems to me to be a problem that, look at this another topic in English, you’re running this on a
AsyncTask
?– Fernando Leal
I am running the way it is up there "new Graburl(). execute("...");" .
– Gabriel Duarte