Timeout on task execution Asynctask

0

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

The method looks for a json from a webservice, but it may be off the air, and when that happens the app will try 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();
    }
    
asked by anonymous 15.02.2018 / 11:06

1 answer

3

Add a timeout to the connection to 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 millisecond, if timeout occurs, you can capture the event using the SocketTimeoutException

    
15.02.2018 / 11:41