httpurlconnection is very slow on Android 4.2

删除回忆录丶 提交于 2019-12-03 06:58:14

Set urlConnection.setConnectTimeout() to a lower timeout.

The class documentation for URLConnection.setConnectTimeout() says:

Sets the maximum time in milliseconds to wait while connecting. Connecting to a server will fail with a SocketTimeoutException if the timeout elapses before a connection is established. The default value of 0 causes us to do a blocking connect. This does not mean we will never time out, but it probably means you'll get a TCP timeout after several minutes.

Warning: if the hostname resolves to multiple IP addresses, this client will try each in RFC 3484 order. If connecting to each of these addresses fails, multiple timeouts will elapse before the connect attempt throws an exception. Host names that support both IPv6 and IPv4 always have at least 2 IP addresses.

I originally had mine set to urlConnection.setConnectTimeout(30000); and then changed it to urlConnection.setConnectTimeout(1000). Immediately, I saw quicker results.

Hope this helps!

You mentionned you are using AsyncTask, are you trying to run several tasks at the same time ?

If that's the case, you should be aware that starting with Android 4.0, AsyncTasks are serialized by default. That means the executor will run one task at a time.

If you want to keep the previous behavior, you can use the following construct:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
  myTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
else {
  myTask.execute();
}

See this blog post for more information:
http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!