从远程 Web 服务器请求的图像与本地镜像相比,Drawable.createFromStream 似乎更慢。这有道理吗?
我有以下代码通过 Android 应用程序的 HTTP 从 Web 服务器获取图像。
HttpClient httpclient = new DefaultHttpClient();
HttpParams httpparams = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(httpparams, CONNECT_TIMEOUT_MS);
HttpConnectionParams.setSoTimeout (httpparams, CONNECT_TIMEOUT_MS);
// For test only
long time = System.currentTimeMillis();
HttpResponse response = httpclient.execute(new HttpGet(strUrl));
StatusLine statusLine = response.getStatusLine();
Log.w("getimage", "Time to get image was " + (System.currentTimeMillis() - time) + "ms");
// Check response
if(statusLine.getStatusCode() == HttpStatus.SC_OK)
{
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
Log.w("getimage", "This is how many bytes we skipped: " + inputStream.skip(1000000));
image = Drawable.createFromStream(inputStream, "src name");
}
Log.w("getimage", "Time to return from image call was " + (System.currentTimeMillis()-time) + "ms");
如果我指向我的本地站点(本地网络),第一个计时器日志为 30 毫秒(HTTP 请求),第二个计时器日志为 66 毫秒(HTTP 请求,加上可绘制对象)。
如果我做同样的事情,但指向我的网络服务器,我会得到 298 毫秒(预计会更慢......),但 HTTP 请求和可绘制对象调用则为 1800 毫秒。
这告诉我,Drawable.createFromStream 方法在远程 Web 服务器上花费了长达 1.5 秒的时间?
对此有什么想法吗?它是否执行任何 HTTP 调用?文档很少。在本地运行时一切都很顺利,但在远程运行时却变得非常慢......
最佳答案
我认为是无线时间让我丧命。我对此无能为力,因此我没有串行获取每个图像,而是为每个图像使用一个线程(最多 5 个图像),并并行获取它们。
类似...
m_threadLatch = new CountDownLatch(m_story.photos_thumb.length);
for(int i=0; i<m_story.photos_thumb.length; i++)
{
new HTTPGetImages(((MyApplication)getApplication()).getBaseURL() + m_story.photos_thumb[i]).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
new AddImagesToUI().execute();
AddImagesToUI 等待 m_threadLatch,并将图像添加到 UI。结果?不到一秒!感谢上帝的并行性!
关于java - Drawable.createFromStream 使用来自远程服务器的图像花费更长的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18176678/