I am trying to download data in Async Task. But there has been a delay for around 10 to 12 seconds when that activity is called for the first time. When application is closed and opened immediately there has no been any delay. I observed that there has been delay near function getInputStream().
I have seen other suggestions in SO saying to use.
urlConnection.setReadTimeout(time);
But there has been no use.
I also tried adding this line as suggested in https://stackoverflow.com/a/1921530/7512939:
System.setProperty("http.keepAlive", "false");
Here is my code:
public class GetAllStationsAndStopsAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... objects) {
String urlString = getUrl();
HttpURLConnection urlConnection = null;
BufferedReader bufferedReader;
String line;
InputStream inputStream;
StringBuilder json_result = new StringBuilder();
try {
System.setProperty("http.keepAlive", "false");
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(2000);
urlConnection.setConnectTimeout(2000);
urlConnection.setRequestMethod("GET");
Log.v(TAG, "before");
inputStream = new BufferedInputStream(urlConnection.getInputStream());
Log.v(TAG, "before 1");
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = bufferedReader.readLine()) != null) {
json_result.append(line);
}
Log.v(TAG, "before 2");
} catch (Exception e) {
Log.e(TAG, "before first error"+e.getLocalizedMessage());
getActivity().runOnUiThread(new Runnable() {
public void run() {
new GetAllStationsAndStopsAsyncTask().execute();
}
});
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
Please let me know how to avoid this huge delay. TIA