Asynctask task execution timeout

Asked

Viewed 130 times

1

How do I limit the running time of a Asynctask and return a warning when the limit is reached ?

The method searches a json of a webservice, but the same may be out of the air, and when this happens the app keeps trying for a long time until it gives the error.

protected String doInBackground(Void... params) {

    StringBuilder content = new StringBuilder();
    try {
        URL url = new URL("endereco.com/dados.php");
        URLConnection urlConnection = url.openConnection();

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            content.append(line + "\n");
        }
        bufferedReader.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
  • I believe it would be the case to set a timeout at the time of opening the connection with the webservice

  • @Henry would be here to serve this timeout URLConnection urlConnection = url.openConnection(); ?

  • That, rephrase the question and add the link code, which I try to formulate an answer.

  • Amended question !

  • 1

    Would that be: urlConnection.setConnectTimeout() right

1 answer

3


Add a timeout for connection with your webservice:

protected String doInBackground(Void...params) {

    StringBuilder content = new StringBuilder();
    try {
        URL url = new URL("endereco.com/dados.php");
        URLConnection urlConnection = url.openConnection();
        urlConnection.setConnectTimeout(5000);
        urlConnection.setReadTimeout(5000);

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            content.append(line + "\n");
        }
        bufferedReader.close();

    } catch(Exception e) {
        e.printStackTrace();
    }

For both methods, enter the value in milliseconds, if the timeout, can capture the event using the exception SocketTimeoutException

  • Henry, either of the 2 if they give the time limit, they fall into Exception correct !? In view he accuses the same error org.json.JSONException: End of input at character 0 of would have treatment to separate what the real reason ?

  • Yeah, they’ll both fall in Exception. About that JSONException, is another problem at some other point.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.