第一次调用时,在getInputStream()函数附近延迟大约10秒。

时间:2017-04-10 16:36:25

标签: android httpconnection

我正在尝试在Async Task中下载数据。但是,当第一次调用该活动时,会有大约10到12秒的延迟。当申请被关闭并立即打开时,没有任何延迟。我发现函数getInputStream()附近有延迟。

我已经看到SO中的其他建议说要使用。

urlConnection.setReadTimeout(time);

但是没有用。

我也尝试按https://stackoverflow.com/a/1921530/7512939中的建议添加此行:

  System.setProperty("http.keepAlive", "false");

这是我的代码:

  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;
    }

请让我知道如何避免这种巨大的延迟。 TIA

0 个答案:

没有答案