AsyncTask stops working after some time

388 Views Asked by At

I've been using AsyncTask for some time already and it never stopped working after some time like in this case. After I open my app for the first time everything works fine and I can execute AsyncTask many times.

The problem is after I close my app and put device to stand still for a couple of minutes, AsyncTask becomes impossible to execute. Usually it takes for 1-2 seconds to load data, but in this case it takes for a couple of minutes.

This is my AsyncTask:

class MyAsyncTask extends AsyncTask<String, Void, ArrayList<MyObject>> {

private ProgressDialog dialog;
private FragmentActivity context;

public MyAsyncTask(FragmentActivity activity) {
    context = activity;
    dialog = new ProgressDialog(context);
}

protected void onPreExecute() {
    this.dialog.setMessage("...");
    this.dialog.show();
}

@Override
protected ArrayList<MyObject> doInBackground(String... params) {
    HttpURLConnection connection = null;
    ArrayList<MyObject> objects = null;

    try {
        URL url = new URL(params[0]);
        connection = (HttpURLConnection) url.openConnection();
        InputStream in = connection.getInputStream();
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(in));
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return null;
        }
        String line;
        objects = new ArrayList<MyObject>();
        MyObject mo = new MyObject();

        while ((line = reader.readLine()) != null) {
            // Process data
        }

        reader.close();

    } catch (Exception e) {
        return null;
    } finally {
        if (connection != null)
            connection.disconnect();
    }

    return objects;

}

@Override
protected void onPostExecute(ArrayList<MyObject> data) {
    if (dialog.isShowing()) {
        dialog.dismiss();
    }

    if (data == null) {
        Toast.makeText(context, "fail", Toast.LENGTH_SHORT).show();
    }

    else {

    }

}
}

One more thing I've noticed is that when I press back or home buttons on my device and go back on home screen, in LogCat I see this warning:

W/IInputConnectionWrapper(22155): showStatusIcon on inactive InputConnection

I thought that this warning only appears if I don't close my connection but connection.disconnect(); is always called inside finally block. This could maybe be a part of the problem.

What do you think could be a problem?

UPDATE1

Now I noticed that after a couple of minutes I receive the following exception:

java.net.SocketException: recvfrom failed: ETIMEDOUT (Connection timed out)
0

There are 0 best solutions below